mqtt5 0.31.4

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
use crate::error::{MqttError, Result};
use crate::protocol::v5::reason_codes::ReasonCode;
use crate::types::{ConnectOptions, ConnectResult};
use crate::Transport;
use std::net::ToSocketAddrs;
use tracing::instrument;

#[cfg(all(not(target_arch = "wasm32"), feature = "transport-quic"))]
use crate::transport::quic::QuicConfig;
#[cfg(not(target_arch = "wasm32"))]
use crate::transport::tcp::TcpConfig;
#[cfg(not(target_arch = "wasm32"))]
use crate::transport::tls::TlsConfig;
#[cfg(all(not(target_arch = "wasm32"), feature = "transport-websocket"))]
use crate::transport::websocket::{WebSocketConfig, WebSocketTransport};
#[cfg(all(not(target_arch = "wasm32"), feature = "transport-quic"))]
use crate::transport::QuicTransport;
#[cfg(not(target_arch = "wasm32"))]
use crate::transport::{TcpTransport, TlsTransport, TransportType};

use super::connection::{ConnectionEvent, DisconnectReason};
use super::direct::{AutomaticReconnectLifecycle, StoredSubscription};
use super::state::ClientTransportType;
use super::MqttClient;

impl MqttClient {
    async fn on_successful_connect(
        &self,
        stored_subs: Vec<StoredSubscription>,
        session_present: bool,
    ) {
        self.trigger_connection_event(ConnectionEvent::Connected { session_present })
            .await;
        self.recover_quic_flows().await;
        self.restore_subscriptions_after_connect(stored_subs, session_present)
            .await;
    }

    #[cfg(any(not(feature = "transport-websocket"), not(feature = "transport-quic")))]
    fn unsupported_transport_feature(transport: &str, feature: &str) -> MqttError {
        MqttError::Configuration(format!(
            "{transport} transport is disabled at compile time; enable the `{feature}` feature"
        ))
    }

    pub(crate) fn is_aws_iot_endpoint(hostname: &str) -> bool {
        hostname.contains(".iot.") && hostname.ends_with(".amazonaws.com")
    }

    /// Parses an address string to determine transport type and components
    ///
    /// # Errors
    ///
    /// Returns an error if the address format is invalid
    pub(crate) fn parse_address(address: &str) -> Result<(ClientTransportType, &str, u16)> {
        if let Some(rest) = address.strip_prefix("mqtt://") {
            let (host, port) = Self::split_host_port(rest, 1883)?;
            Ok((ClientTransportType::Tcp, host, port))
        } else if let Some(rest) = address.strip_prefix("mqtts://") {
            let (host, port) = Self::split_host_port(rest, 8883)?;
            Ok((ClientTransportType::Tls, host, port))
        } else if let Some(rest) = address.strip_prefix("ws://") {
            let (host, port) = Self::split_host_port(rest, 80)?;
            #[cfg(feature = "transport-websocket")]
            {
                Ok((
                    ClientTransportType::WebSocket(address.to_string()),
                    host,
                    port,
                ))
            }
            #[cfg(not(feature = "transport-websocket"))]
            {
                let _ = (host, port);
                Err(Self::unsupported_transport_feature(
                    "WebSocket",
                    "transport-websocket",
                ))
            }
        } else if let Some(rest) = address.strip_prefix("wss://") {
            let (host, port) = Self::split_host_port(rest, 443)?;
            #[cfg(feature = "transport-websocket")]
            {
                Ok((
                    ClientTransportType::WebSocketSecure(address.to_string()),
                    host,
                    port,
                ))
            }
            #[cfg(not(feature = "transport-websocket"))]
            {
                let _ = (host, port);
                Err(Self::unsupported_transport_feature(
                    "WebSocket",
                    "transport-websocket",
                ))
            }
        } else if let Some(rest) = address.strip_prefix("tcp://") {
            let (host, port) = Self::split_host_port(rest, 1883)?;
            Ok((ClientTransportType::Tcp, host, port))
        } else if let Some(rest) = address.strip_prefix("ssl://") {
            let (host, port) = Self::split_host_port(rest, 8883)?;
            Ok((ClientTransportType::Tls, host, port))
        } else if let Some(rest) = address.strip_prefix("quic://") {
            let (host, port) = Self::split_host_port(rest, 14567)?;
            #[cfg(feature = "transport-quic")]
            {
                Ok((ClientTransportType::Quic, host, port))
            }
            #[cfg(not(feature = "transport-quic"))]
            {
                let _ = (host, port);
                Err(Self::unsupported_transport_feature(
                    "QUIC",
                    "transport-quic",
                ))
            }
        } else if let Some(rest) = address.strip_prefix("quics://") {
            let (host, port) = Self::split_host_port(rest, 14567)?;
            #[cfg(feature = "transport-quic")]
            {
                Ok((ClientTransportType::QuicSecure, host, port))
            }
            #[cfg(not(feature = "transport-quic"))]
            {
                let _ = (host, port);
                Err(Self::unsupported_transport_feature(
                    "QUIC",
                    "transport-quic",
                ))
            }
        } else {
            let (host, port) = Self::split_host_port(address, 1883)?;
            Ok((ClientTransportType::Tcp, host, port))
        }
    }

    /// Splits a host:port string
    ///
    /// # Errors
    ///
    /// Returns an error if the port is invalid
    pub(crate) fn split_host_port(address: &str, default_port: u16) -> Result<(&str, u16)> {
        let address_without_path = address.split('/').next().unwrap_or(address);

        if let Some(colon_pos) = address_without_path.rfind(':') {
            let host = &address_without_path[..colon_pos];
            let port_str = &address_without_path[colon_pos + 1..];
            let port = port_str
                .parse::<u16>()
                .map_err(|_| MqttError::ConnectionError(format!("Invalid port: {port_str}")))?;
            Ok((host, port))
        } else {
            Ok((address_without_path, default_port))
        }
    }

    pub(crate) fn resolve_addresses(host: &str, port: u16) -> Result<Vec<std::net::SocketAddr>> {
        let addr_str = format!("{host}:{port}");
        tracing::debug!(addr_str = %addr_str, "🌐 DNS RESOLUTION - Starting address resolution");

        let addrs: Vec<_> = addr_str
            .to_socket_addrs()
            .map_err(|e| {
                tracing::error!(addr_str = %addr_str, error = %e, "🌐 DNS RESOLUTION - Failed to resolve address");
                MqttError::ConnectionError(format!("Failed to resolve address: {e}"))
            })?
            .collect();

        tracing::debug!(addr_str = %addr_str, resolved_count = addrs.len(), "🌐 DNS RESOLUTION - Address resolved successfully");

        if addrs.is_empty() {
            return Err(MqttError::ConnectionError(
                "No valid address found".to_string(),
            ));
        }

        Ok(addrs)
    }

    pub(crate) fn select_addresses_for_connection<'a>(
        addrs: &'a [std::net::SocketAddr],
        host: &str,
    ) -> &'a [std::net::SocketAddr] {
        let is_aws_iot = Self::is_aws_iot_endpoint(host);

        if is_aws_iot {
            tracing::debug!("AWS IoT endpoint detected, limiting to first resolved address");
            &addrs[0..1]
        } else {
            addrs
        }
    }

    pub(crate) async fn try_connect_address(
        &self,
        addr: std::net::SocketAddr,
        client_transport_type: ClientTransportType,
        host: &str,
    ) -> Result<TransportType> {
        match client_transport_type {
            ClientTransportType::Tcp => Self::connect_tcp(addr).await,
            ClientTransportType::Tls => self.connect_tls(addr, host).await,
            #[cfg(feature = "transport-websocket")]
            ClientTransportType::WebSocket(url) => Self::connect_websocket(&url).await,
            #[cfg(feature = "transport-websocket")]
            ClientTransportType::WebSocketSecure(url) => {
                self.connect_websocket_secure(addr, host, &url).await
            }
            #[cfg(feature = "transport-quic")]
            ClientTransportType::Quic => self.connect_quic(addr, host).await,
            #[cfg(feature = "transport-quic")]
            ClientTransportType::QuicSecure => self.connect_quic_secure(addr, host).await,
        }
    }

    async fn connect_tcp(addr: std::net::SocketAddr) -> Result<TransportType> {
        let config = TcpConfig::new(addr);
        let mut tcp_transport = TcpTransport::new(config);
        tcp_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("TCP connect failed: {e}")))?;
        Ok(TransportType::Tcp(tcp_transport))
    }

    async fn connect_tls(&self, addr: std::net::SocketAddr, host: &str) -> Result<TransportType> {
        let insecure = self.transport_config.read().await.insecure_tls;
        let tls_config_lock = self.tls_config.read().await;
        let config = if let Some(existing_config) = &*tls_config_lock {
            tracing::debug!(
                "Using stored TLS config - use_system_roots: {}, has_ca: {}, has_cert: {}",
                existing_config.use_system_roots,
                existing_config.root_certs.is_some(),
                existing_config.client_cert.is_some()
            );
            let mut cfg = existing_config.clone();
            cfg.addr = addr;
            cfg.hostname = host.to_string();
            cfg.verify_server_cert = !insecure;
            cfg
        } else {
            tracing::debug!("No stored TLS config, using default");
            TlsConfig::new(addr, host).with_verify_server_cert(!insecure)
        };
        drop(tls_config_lock);

        let mut tls_transport = TlsTransport::new(config);
        tls_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("TLS connect failed: {e}")))?;
        Ok(TransportType::Tls(Box::new(tls_transport)))
    }

    #[cfg(feature = "transport-websocket")]
    async fn connect_websocket(url: &str) -> Result<TransportType> {
        let config = WebSocketConfig::new(url)
            .map_err(|e| MqttError::ConnectionError(format!("Invalid WebSocket URL: {e}")))?;
        let mut ws_transport = WebSocketTransport::new(config);
        ws_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("WebSocket connect failed: {e}")))?;
        Ok(TransportType::WebSocket(Box::new(ws_transport)))
    }

    #[cfg(feature = "transport-websocket")]
    async fn connect_websocket_secure(
        &self,
        addr: std::net::SocketAddr,
        host: &str,
        url: &str,
    ) -> Result<TransportType> {
        let insecure = self.transport_config.read().await.insecure_tls;
        let mut config = WebSocketConfig::new(url)
            .map_err(|e| MqttError::ConnectionError(format!("Invalid WebSocket URL: {e}")))?;

        if insecure {
            let tls_config = TlsConfig::new(addr, host).with_verify_server_cert(false);
            config = config.with_tls_config(tls_config);
        }

        let mut ws_transport = WebSocketTransport::new(config);
        ws_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("WebSocket connect failed: {e}")))?;
        Ok(TransportType::WebSocket(Box::new(ws_transport)))
    }

    #[cfg(feature = "transport-quic")]
    async fn connect_quic(&self, addr: std::net::SocketAddr, host: &str) -> Result<TransportType> {
        let qc = self.transport_config.read().await;
        let server_name = if host.parse::<std::net::IpAddr>().is_ok() {
            "localhost"
        } else {
            host
        };
        let mut config = QuicConfig::new(addr, server_name)
            .with_verify_server_cert(false)
            .with_stream_strategy(qc.stream_strategy)
            .with_flow_headers(qc.flow_headers)
            .with_flow_expire_interval(qc.flow_expire.as_secs())
            .with_datagrams(qc.datagrams)
            .with_connect_timeout(qc.connect_timeout)
            .with_early_data(qc.enable_early_data);
        if let Some(max) = qc.max_streams {
            config = config.with_max_concurrent_streams(max);
        }
        if qc.enable_early_data {
            if let Some(cached) = self.quic_client_config.read().await.clone() {
                config = config.with_cached_client_config(cached);
            }
        }
        drop(qc);
        let mut quic_transport = QuicTransport::new(config);
        quic_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("QUIC connect failed: {e}")))?;
        Ok(TransportType::Quic(Box::new(quic_transport)))
    }

    #[cfg(feature = "transport-quic")]
    async fn connect_quic_secure(
        &self,
        addr: std::net::SocketAddr,
        host: &str,
    ) -> Result<TransportType> {
        let qc: crate::transport::ClientTransportConfig =
            (*self.transport_config.read().await).clone();
        let tls_config_lock = self.tls_config.read().await;
        let server_name = if host.parse::<std::net::IpAddr>().is_ok() {
            "localhost"
        } else {
            host
        };
        let mut config = QuicConfig::new(addr, server_name)
            .with_verify_server_cert(!qc.insecure_tls)
            .with_stream_strategy(qc.stream_strategy)
            .with_flow_headers(qc.flow_headers)
            .with_flow_expire_interval(qc.flow_expire.as_secs())
            .with_datagrams(qc.datagrams)
            .with_connect_timeout(qc.connect_timeout)
            .with_early_data(qc.enable_early_data);

        if let Some(max) = qc.max_streams {
            config = config.with_max_concurrent_streams(max);
        }

        if qc.enable_early_data {
            if let Some(cached) = self.quic_client_config.read().await.clone() {
                config = config.with_cached_client_config(cached);
            }
        }

        if let Some(existing_config) = &*tls_config_lock {
            tracing::debug!(
                "Using stored TLS config for QUIC - use_system_roots: {}, has_ca: {}, has_cert: {}",
                existing_config.use_system_roots,
                existing_config.root_certs.is_some(),
                existing_config.client_cert.is_some()
            );

            if let (Some(ref cert_chain), Some(ref key)) =
                (&existing_config.client_cert, &existing_config.client_key)
            {
                config = config.with_client_cert(cert_chain.clone(), key.clone_key());
            }

            if let Some(ref certs) = existing_config.root_certs {
                config = config.with_root_certs(certs.clone());
            }
        } else {
            tracing::debug!("No stored TLS config for QUIC, using default");
        }
        drop(tls_config_lock);

        let mut quic_transport = QuicTransport::new(config);
        quic_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("QUIC connect failed: {e}")))?;
        Ok(TransportType::Quic(Box::new(quic_transport)))
    }

    pub(crate) async fn try_connect_to_addresses(
        &self,
        addresses: &[std::net::SocketAddr],
        transport_type: ClientTransportType,
        host: &str,
    ) -> Result<ConnectResult> {
        let mut last_error = None;

        for addr in addresses {
            tracing::debug!("Trying to connect to address: {}", addr);

            let transport = match self
                .try_connect_address(*addr, transport_type.clone(), host)
                .await
            {
                Ok(t) => t,
                Err(e) => {
                    tracing::debug!("Failed to connect to {}: {}", addr, e);
                    last_error = Some(e);
                    continue;
                }
            };

            self.reset_reconnect_counter().await;

            let mut inner = self.inner.write().await;
            match inner.connect(transport).await {
                Ok(result) => {
                    #[cfg(feature = "transport-quic")]
                    if let Some(cached) = inner.cached_quic_client_config.take() {
                        *self.quic_client_config.write().await = Some(cached);
                    }
                    let stored_subs = inner.stored_subscriptions.lock().clone();
                    let session_present = result.session_present;
                    drop(inner);

                    self.on_successful_connect(stored_subs, session_present)
                        .await;

                    return Ok(result);
                }
                Err(
                    e @ MqttError::ConnectionRefused(
                        ReasonCode::UseAnotherServer | ReasonCode::ServerMoved,
                    ),
                ) => {
                    drop(inner);
                    return Err(e);
                }
                Err(e) => {
                    drop(inner);
                    last_error = Some(e);
                }
            }
        }

        Err(last_error.unwrap_or_else(|| {
            MqttError::ConnectionError("Failed to connect to any address".to_string())
        }))
    }

    pub(crate) async fn connect_internal(&self, address: &str) -> Result<ConnectResult> {
        const MAX_REDIRECTS: u8 = 3;
        let mut current_address = address.to_string();
        let mut redirect_count: u8 = 0;

        loop {
            let client_id = self.inner.read().await.options.client_id.clone();
            tracing::debug!(
                address = %current_address,
                client_id = %client_id,
                redirect_count,
                "Connection attempt"
            );

            let (client_transport_type, host, port) = Self::parse_address(&current_address)?;
            let addrs = Self::resolve_addresses(host, port)?;
            let addresses_to_try = Self::select_addresses_for_connection(&addrs, host);

            match self
                .try_connect_to_addresses(addresses_to_try, client_transport_type, host)
                .await
            {
                Ok(result) => return Ok(result),
                Err(MqttError::ConnectionRefused(
                    reason @ (ReasonCode::UseAnotherServer | ReasonCode::ServerMoved),
                )) => {
                    let redirect_url = self.inner.write().await.server_redirect.take();
                    if let Some(url) = redirect_url {
                        if redirect_count < MAX_REDIRECTS {
                            tracing::info!(
                                from = %current_address,
                                to = %url,
                                reason = ?reason,
                                "Following server redirect"
                            );
                            redirect_count += 1;
                            current_address = url;
                            continue;
                        }
                    }
                    return Err(MqttError::ConnectionError(
                        "Server redirect failed: too many redirects or missing server reference"
                            .to_string(),
                    ));
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Internal connection method using custom TLS configuration
    ///
    /// # Errors
    ///
    /// Returns an error if TLS connection fails
    pub(crate) async fn connect_internal_with_tls(
        &self,
        tls_config: crate::transport::tls::TlsConfig,
    ) -> Result<ConnectResult> {
        *self.tls_config.write().await = Some(tls_config.clone());

        let mut tls_transport = crate::transport::tls::TlsTransport::new(tls_config);
        tls_transport
            .connect()
            .await
            .map_err(|e| MqttError::ConnectionError(format!("TLS connect failed: {e}")))?;

        let transport = TransportType::Tls(Box::new(tls_transport));

        {
            let mut inner = self.inner.write().await;
            inner.reconnect_attempt = 0;
        }

        let mut inner = self.inner.write().await;
        match inner.connect(transport).await {
            Ok(result) => {
                let stored_subs = inner.stored_subscriptions.lock().clone();
                let session_present = result.session_present;
                drop(inner);

                self.on_successful_connect(stored_subs, session_present)
                    .await;

                Ok(result)
            }
            Err(MqttError::ConnectionRefused(
                reason @ (ReasonCode::UseAnotherServer | ReasonCode::ServerMoved),
            )) => {
                let redirect_url = inner.server_redirect.take();
                drop(inner);
                if let Some(url) = redirect_url {
                    tracing::info!(
                        to = %url,
                        reason = ?reason,
                        "Following server redirect from TLS connection"
                    );
                    return Box::pin(self.connect_internal(&url)).await;
                }
                Err(MqttError::ConnectionError(
                    "Server redirect missing server reference".to_string(),
                ))
            }
            Err(e) => {
                drop(inner);
                Err(e)
            }
        }
    }

    #[instrument(skip(self, options), fields(client_id = %options.client_id, clean_start = %options.clean_start), level = "debug")]
    pub(crate) async fn connect_with_options_internal(
        &self,
        address: &str,
        options: ConnectOptions,
    ) -> Result<ConnectResult> {
        if self.is_connected().await {
            return Err(MqttError::AlreadyConnected);
        }

        {
            let mut inner = self.inner.write().await;
            inner
                .auth_method
                .clone_from(&options.properties.authentication_method);
            inner.options = options.clone();
            inner.last_address = Some(address.to_string());
            inner.automatic_reconnect_lifecycle = AutomaticReconnectLifecycle::Armed;
        }

        let result = self.connect_internal(address).await;

        if let Err(ref error) = result {
            let error_recovery_config =
                crate::client::error_recovery::ErrorRecoveryConfig::default();
            if crate::client::error_recovery::is_recoverable(error, &error_recovery_config)
                .is_some()
            {
                if options.reconnect_config.enabled {
                    tracing::debug!(
                        error = %error,
                        "Initial connection failed with recoverable error, starting background reconnection"
                    );
                    let client = self.clone();
                    tokio::spawn(async move {
                        client.monitor_connection().await;
                    });
                } else {
                    tracing::debug!(error = %error, "Initial connection failed with recoverable error, but automatic reconnection is disabled");
                }
            } else {
                tracing::debug!(error = %error, "Initial connection failed with non-recoverable error, not starting background reconnection");
            }
        } else if result.is_ok() && options.reconnect_config.enabled {
            tracing::debug!(
                "Successful connection, starting monitor task for future disconnections"
            );
            let client = self.clone();
            tokio::spawn(async move {
                client.monitor_connection().await;
            });
        }

        result
    }

    /// Internal TLS connection method (no mutex guard)
    ///
    /// # Errors
    ///
    /// Returns an error if connection fails or configuration is invalid
    pub(crate) async fn connect_with_tls_and_options_internal(
        &self,
        tls_config: crate::transport::tls::TlsConfig,
        options: ConnectOptions,
    ) -> Result<ConnectResult> {
        if self.is_connected().await {
            return Err(MqttError::AlreadyConnected);
        }

        {
            let mut inner = self.inner.write().await;
            inner.options = options.clone();
            inner.last_address = Some(format!(
                "{}:{}",
                tls_config.hostname,
                tls_config.addr.port()
            ));
            inner.automatic_reconnect_lifecycle = AutomaticReconnectLifecycle::Armed;
        }

        let result = self.connect_internal_with_tls(tls_config).await;

        if let Err(ref error) = result {
            if options.reconnect_config.enabled {
                self.trigger_connection_event(ConnectionEvent::Disconnected {
                    reason: DisconnectReason::NetworkError(error.to_string()),
                })
                .await;

                tracing::warn!(
                    "Automatic reconnection with custom TLS config is not yet supported"
                );
            }
        }

        result
    }
}