rzmq 0.5.11

High performance, fully asynchronous, safe pure-Rust implementation of ZeroMQ (ØMQ) messaging with io_uring and TCP Cork acceleration on Linux.
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
use crate::context::Context;
use crate::error::ZmqError;
use crate::runtime::{
  ActorDropGuard, ActorType, Command, MailboxReceiver as GenericMailboxReceiver,
  MailboxSender as GenericMailboxSender, SystemEvent, mailbox,
  system_events::ConnectionInteractionModel,
};
use crate::sessionx::actor::SessionConnectionActorX;
use crate::sessionx::states::ActorConfigX;
use crate::socket::connection_iface::ISocketConnection;
use crate::socket::events::{MonitorSender, SocketEvent};
use crate::socket::options::{SocketOptions, TcpTransportConfig, ZmtpEngineConfig};
use crate::socket::{DEFAULT_RECONNECT_IVL_MS, ISocket};

#[cfg(feature = "io-uring")]
use crate::io_uring_backend::ops::{
  ProtocolConfig as WorkerProtocolConfig, UringOpCompletion as WorkerUringOpCompletion,
  UringOpRequest as WorkerUringOpRequest,
};
#[cfg(feature = "io-uring")]
use crate::socket::connection_iface::UringFdConnection;
#[cfg(feature = "io-uring")]
use crate::uring;
#[cfg(feature = "io-uring")]
use fibre::mpsc;
#[cfg(feature = "io-uring")]
use fibre::oneshot::oneshot;

#[cfg(feature = "io-uring")]
use std::os::unix::io::{AsRawFd, IntoRawFd};

use core::fmt;
use std::io;
use std::net::{SocketAddr as StdSocketAddr, ToSocketAddrs};
use std::sync::Arc;
use std::time::Duration;

use socket2::{SockRef, TcpKeepalive};
use tokio::sync::{Semaphore, broadcast};
use tokio::task::{Id as TaskId, JoinHandle};
use tokio::time::sleep;
use tracing::{debug, error, info, trace, warn};

mod underlying_std_net {
  pub use tokio::net::TcpListener;
  pub use tokio::net::TcpStream;
}

// --- TcpListener Actor ---
pub(crate) struct TcpListener {
  handle: usize,
  endpoint: String,
  mailbox_receiver: GenericMailboxReceiver,
  listener_handle: JoinHandle<()>,
  context: Context,
  parent_socket_id: usize,
  socket_logic: Arc<dyn ISocket>,
}

impl fmt::Debug for TcpListener {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("TcpListener")
      .field("handle", &self.handle)
      .field("endpoint", &self.endpoint)
      .field(
        "mailbox_receiver_is_closed",
        &self.mailbox_receiver.is_closed(),
      )
      .field(
        "listener_handle_is_finished",
        &self.listener_handle.is_finished(),
      )
      .field("context_present", &true)
      .field("parent_socket_id", &self.parent_socket_id)
      .field("socket_logic_present", &true)
      .finish()
  }
}

impl TcpListener {
  pub(crate) fn create_and_spawn(
    handle: usize,
    endpoint: String,
    options: Arc<SocketOptions>,
    socket_logic: Arc<dyn ISocket>,
    context_handle_source: Arc<std::sync::atomic::AtomicUsize>,
    monitor_tx: Option<MonitorSender>,
    context: Context,
    parent_socket_id: usize,
  ) -> Result<(GenericMailboxSender, JoinHandle<()>, String), ZmqError> {
    let capacity = context.inner().get_actor_mailbox_capacity();
    let (tx, rx) = mailbox(capacity);

    let bind_addr_str_for_parse = endpoint
      .strip_prefix("tcp://")
      .ok_or_else(|| ZmqError::InvalidEndpoint(endpoint.clone()))?;

    // Use std::net::ToSocketAddrs for a blocking DNS lookup.
    let mut addrs_iter = bind_addr_str_for_parse.to_socket_addrs().map_err(|e| {
      ZmqError::DnsResolutionFailed(format!(
        "Failed to resolve listener address '{}': {}",
        bind_addr_str_for_parse, e
      ))
    })?;

    let addr_for_bind_call = addrs_iter.next().ok_or_else(|| {
      ZmqError::DnsResolutionFailed(format!(
        "No IP addresses found for listener host '{}'",
        bind_addr_str_for_parse
      ))
    })?;

    let domain = if addr_for_bind_call.is_ipv4() {
      socket2::Domain::IPV4
    } else {
      socket2::Domain::IPV6
    };

    let s = socket2::Socket::new(domain, socket2::Type::STREAM, None).map_err(ZmqError::from)?;
    s.set_reuse_address(true).map_err(ZmqError::from)?;

    if domain == socket2::Domain::IPV6 {
      s.set_only_v6(false).map_err(ZmqError::from)?; //TODO: Probably make this configurable with options
    }

    s.bind(&addr_for_bind_call.into())
      .map_err(|e| ZmqError::from_io_endpoint(e, &endpoint))?;

    s.listen(options.backlog.unwrap_or(128) as i32)
      .map_err(ZmqError::from)?;

    let actual_bind_addr = s.local_addr().map_err(ZmqError::from)?.as_socket().unwrap();

    let std_listener_os: std::net::TcpListener = s.into();
    std_listener_os
      .set_nonblocking(true)
      .map_err(ZmqError::from)?;
    let tokio_listener =
      underlying_std_net::TcpListener::from_std(std_listener_os).map_err(ZmqError::from)?;

    let resolved_uri = format!("tcp://{}", actual_bind_addr);
    tracing::info!(listener_handle = handle, local_addr = %resolved_uri, user_uri = %endpoint, "TCP Listener bound");

    let max_conns = options.max_connections.unwrap_or(std::usize::MAX);
    let conn_limiter = Arc::new(Semaphore::new(max_conns.max(1)));

    let transport_cfg = TcpTransportConfig {
      tcp_nodelay: options.tcp_nodelay,
      keepalive_time: options.tcp_keepalive_idle,
      keepalive_interval: options.tcp_keepalive_interval,
      keepalive_count: options.tcp_keepalive_count,
    };

    let accept_loop_parent_hdl = handle;
    let accept_loop_hdl_id = context.inner().next_handle();

    let accept_loop_task_jh = tokio::spawn(TcpListener::run_accept_loop(
      accept_loop_hdl_id,
      accept_loop_parent_hdl,
      resolved_uri.clone(),
      Arc::new(tokio_listener),
      transport_cfg.clone(),
      options.clone(),
      socket_logic.clone(),
      context_handle_source.clone(),
      monitor_tx.clone(),
      context.clone(),
      parent_socket_id,
      conn_limiter.clone(),
    ));

    let listener_actor = TcpListener {
      handle,
      endpoint: resolved_uri.clone(),
      mailbox_receiver: rx,
      listener_handle: accept_loop_task_jh,
      context: context.clone(),
      parent_socket_id,
      socket_logic,
    };

    let cmd_loop_jh = tokio::spawn(listener_actor.run_command_loop(parent_socket_id));

    Ok((tx, cmd_loop_jh, resolved_uri))
  }

  async fn run_command_loop(mut self, parent_socket_id: usize) {
    let listener_cmd_loop_handle = self.handle;
    let endpoint_uri_clone_log = self.endpoint.clone();
    let event_bus = self.context.event_bus();
    let mut system_event_rx = event_bus.subscribe();
    tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener command loop started");
    let mut final_error_for_actor_stopping: Option<ZmqError> = None;

    let mut actor_drop_guard = ActorDropGuard::new(
      self.context,
      listener_cmd_loop_handle,
      ActorType::Listener,
      Some(endpoint_uri_clone_log.clone()),
      Some(parent_socket_id),
    );

    let _loop_result: Result<(), ()> = async {
      loop {
        tokio::select! {
          biased;
          event_result = system_event_rx.recv() => {
            match event_result {
              Ok(SystemEvent::ContextTerminating) => {
                tracing::info!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener received ContextTerminating, stopping accept loop.");
                self.listener_handle.abort(); break;
              }
              Ok(SystemEvent::SocketClosing{ socket_id }) if socket_id == self.parent_socket_id => {
                tracing::info!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, parent_id = self.parent_socket_id, "TCP Listener received SocketClosing for parent, stopping accept loop.");
                self.listener_handle.abort(); break;
              }
              Ok(_) => {}
              Err(broadcast::error::RecvError::Lagged(n)) => {
                tracing::warn!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, skipped = n, "System event bus lagged!");
                self.listener_handle.abort();
                final_error_for_actor_stopping = Some(ZmqError::Internal("Listener event bus lagged".into())); break;
              }
              Err(broadcast::error::RecvError::Closed) => {
                tracing::error!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "System event bus closed unexpectedly!");
                self.listener_handle.abort();
                final_error_for_actor_stopping = Some(ZmqError::Internal("Listener event bus closed".into())); break;
              }
            }
          }
          cmd_result = self.mailbox_receiver.recv() => {
            match cmd_result {
              Ok(Command::Stop) => {
                tracing::info!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener received Stop command");
                self.listener_handle.abort(); break;
              }
              Ok(other_cmd) => tracing::warn!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener received unhandled command: {:?}", other_cmd.variant_name()),
              Err(_) => {
                tracing::info!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener command mailbox closed, stopping accept loop.");
                self.listener_handle.abort();
                if final_error_for_actor_stopping.is_none() { final_error_for_actor_stopping = Some(ZmqError::Internal("Listener command mailbox closed by peer".into()));}
                break;
              }
            }
          }
        }
      }
      Ok(())
    }.await;

    tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener command loop finished, awaiting accept loop task.");
    if let Err(e) = self.listener_handle.await {
      if !e.is_cancelled() {
        tracing::error!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener accept loop task panicked: {:?}", e);
        if final_error_for_actor_stopping.is_none() {
          final_error_for_actor_stopping = Some(ZmqError::Internal(format!(
            "Listener accept loop panicked: {:?}",
            e
          )));
        }
      } else {
        tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener accept loop task was cancelled as expected.");
      }
    } else {
      tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener accept loop task joined cleanly.");
    }

    if let Some(err) = final_error_for_actor_stopping.take() {
      actor_drop_guard.set_error(err);
    } else {
      actor_drop_guard.waive();
    }

    tracing::info!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "TCP Listener command loop actor fully stopped.");
  }

  async fn run_accept_loop(
    accept_loop_handle: usize,
    _listener_cmd_loop_handle: usize,
    endpoint_uri: String,
    listener: Arc<underlying_std_net::TcpListener>,
    transport_config: TcpTransportConfig,
    socket_options: Arc<SocketOptions>,
    socket_logic: Arc<dyn ISocket>,
    handle_source: Arc<std::sync::atomic::AtomicUsize>,
    monitor_tx: Option<MonitorSender>,
    context: Context,
    parent_socket_core_id: usize,
    connection_limiter: Arc<Semaphore>,
  ) {
    #[cfg(feature = "io-uring")]
    if socket_options.io_uring.session_enabled {
      uring::global_state::get_global_uring_worker_op_tx()
        .expect("URING HAS NOT BEEN INITIALIZED!");
    }

    let mut actor_drop_guard = ActorDropGuard::new(
      context.clone(),
      accept_loop_handle,
      ActorType::AcceptLoop,
      Some(endpoint_uri.clone()),
      Some(parent_socket_core_id),
    );
    tracing::debug!(handle = accept_loop_handle, uri = %endpoint_uri, "TCP Accept loop (unified) started.");
    let mut loop_error_to_report: Option<ZmqError> = None;

    loop {
      let permit = match connection_limiter.clone().acquire_owned().await {
        Ok(p) => p,
        Err(_) => {
          loop_error_to_report = Some(ZmqError::Internal("Connection limiter closed".into()));
          break;
        }
      };

      match listener.accept().await {
        Ok((tokio_tcp_stream, peer_addr)) => {
          let _permit_guard = permit;
          let peer_addr_str = peer_addr.to_string();
          tracing::info!(
            "Accepted TCP connection from {} (for listener {})",
            peer_addr_str,
            endpoint_uri
          );

          if let Some(ref tx) = monitor_tx {
            let _ = tx.try_send(SocketEvent::Accepted {
              endpoint: endpoint_uri.clone(),
              peer_addr: peer_addr_str.clone(),
            });
          }

          let use_io_uring_for_session =
            socket_options.io_uring.session_enabled && cfg!(feature = "io-uring");
          let connection_specific_uri = format!("tcp://{}", peer_addr_str);

          tokio::spawn({
            let context_clone = context.clone();
            let socket_options_clone = socket_options.clone();
            let transport_config_clone = transport_config.clone();
            let monitor_tx_clone = monitor_tx.clone();
            let endpoint_uri_listener = endpoint_uri.clone();
            let handle_source_clone = handle_source.clone();
            let actual_connected_uri = connection_specific_uri.clone();
            let logical_uri = endpoint_uri_listener.to_string(); // e.g., "tcp://127.0.0.1:5558"
            let socket_logic = socket_logic.clone();

            async move {
              let max_connection_permit = _permit_guard; 

              let mut connection_iface_for_event: Option<Arc<dyn ISocketConnection>> = None;
              let mut interaction_model_for_event: Option<ConnectionInteractionModel> = None;
              let mut managing_actor_task_id_for_event: Option<TaskId> = None;
              let mut setup_successful = true;
              let mut sca_or_session_join_handle_opt: Option<JoinHandle<()>> = None;

              if use_io_uring_for_session {
                #[cfg(feature = "io-uring")]
                {
                  match tokio_tcp_stream.into_std() {
                    Ok(std_stream) => {
                      if socket_options_clone.tcp_cork {
                        tracing::debug!(
                          handle = accept_loop_handle,
                          fd = std_stream.as_raw_fd(),
                          "TcpListener: Applying TCP_CORK to accepted connection FD for IO URing."
                        );
                        let sock_ref = socket2::SockRef::from(&std_stream);
                        if let Err(e) = sock_ref.set_tcp_cork(true) {
                          tracing::error!(handle = accept_loop_handle, fd = std_stream.as_raw_fd(), error = %e, "TcpListener: Failed to set TCP_CORK for IO URing FD. Proceeding without.");
                          // Not making this fatal for the connection, it will proceed without CORK.
                        }
                      }

                      if let Err(e) =
                        apply_tcp_socket_options_to_std(&std_stream, &transport_config_clone)
                      {
                        tracing::error!(
                          "Opt apply failed (std stream) for {}: {}. Dropping.",
                          peer_addr_str,
                          e
                        );
                        setup_successful = false;
                      } else {
                        let raw_fd = std_stream.into_raw_fd();

                        let worker_op_tx =
                          uring::global_state::get_global_uring_worker_op_tx().unwrap();
                        let protocol_config = WorkerProtocolConfig::Zmtp(Arc::new(
                          ZmtpEngineConfig::from(&*socket_options_clone),
                        ));
                        let user_data_for_op = context_clone.inner().next_handle() as u64;
                        let (reply_tx_for_op, reply_rx_for_op) = oneshot();

                        let hwm = socket_options_clone.sndhwm.max(1); // TODO Needs bounded mpsc fibre to respect this
                        let (mpsc_tx_for_conn, mpsc_rx_for_worker) = mpsc::bounded(hwm);

                        let new_conn_iface = Arc::new(UringFdConnection::new(
                          raw_fd,
                          mpsc_tx_for_conn.to_async(),
                          context_clone.clone(),
                        ));

                        let register_fd_req = WorkerUringOpRequest::RegisterExternalFd {
                          user_data: user_data_for_op,
                          fd: raw_fd,
                          protocol_handler_factory_id: "zmtp-uring/3.1".to_string(),
                          protocol_config,
                          is_server_role: true,
                          reply_tx: reply_tx_for_op,
                          mpsc_rx_for_worker: Arc::new(mpsc_rx_for_worker),
                        };

                        if let Err(e) = worker_op_tx.send(register_fd_req).await {
                          tracing::error!(
                            "Send RegisterExternalFd to UringWorker for fd {}: {}",
                            raw_fd,
                            e
                          );
                          unsafe {
                            let _ = libc::close(raw_fd);
                          }
                          setup_successful = false;
                        } else {
                          match reply_rx_for_op.recv().await {
                            Ok(Ok(WorkerUringOpCompletion::RegisterExternalFdSuccess {
                              fd: returned_fd,
                              ..
                            }))
                              if returned_fd == raw_fd =>
                            {
                              info!("Registered accepted FD {} with UringWorker.", raw_fd);
                              connection_iface_for_event = Some(new_conn_iface);
                              interaction_model_for_event =
                                Some(ConnectionInteractionModel::ViaUringFd { fd: raw_fd });
                              // managing_actor_task_id_for_event remains None for UringFd path
                            }
                            Ok(Ok(other_completion)) => {
                              tracing::error!(
                                "UringWorker bad success for RegisterExternalFd (fd {}): {:?}",
                                raw_fd,
                                other_completion
                              );
                              unsafe {
                                let _ = libc::close(raw_fd);
                              }
                              setup_successful = false;
                            }
                            Ok(Err(worker_err)) => {
                              tracing::error!(
                                "Register accepted FD {} with UringWorker failed (worker error): {:?}",
                                raw_fd,
                                worker_err
                              );
                              unsafe {
                                let _ = libc::close(raw_fd);
                              }
                              setup_successful = false;
                            }
                            Err(oneshot_recv_err) => {
                              tracing::error!(
                                "Register accepted FD {} with UringWorker failed (reply channel error): {:?}",
                                raw_fd,
                                oneshot_recv_err
                              );
                              unsafe {
                                let _ = libc::close(raw_fd);
                              }
                              setup_successful = false;
                            }
                          }
                        }
                      }
                    }
                    Err(e) => {
                      tracing::error!(
                        "tokio_tcp_stream to std failed for accepted conn: {}. Dropping.",
                        e
                      );
                      setup_successful = false;
                    }
                  }
                }
                #[cfg(not(feature = "io-uring"))]
                {
                  setup_successful = false;
                  unreachable!("io_uring feature not enabled but use_io_uring_for_session is true");
                }
              } else {
                // Standard path: SessionBase + ZmtpEngineCoreStd
                if let Err(e) =
                  apply_tcp_socket_options_to_tokio(&tokio_tcp_stream, &transport_config_clone)
                {
                  tracing::error!(
                    "Opt apply failed (tokio stream) for {}: {}. Dropping.",
                    peer_addr_str,
                    e
                  );
                  setup_successful = false;
                } else {
                  let sca_handle_id =
                    handle_source_clone.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                  let actor_conf = ActorConfigX {
                    context: context_clone.clone(),
                    monitor_tx: monitor_tx_clone,
                    logical_target_endpoint_uri: logical_uri.clone(), // Was `logical_uri` in your original
                    connected_endpoint_uri: actual_connected_uri.clone(),
                    is_server_role: true,
                  };
                  let engine_conf = Arc::new(ZmtpEngineConfig::from(&*socket_options_clone));

                  let (command_sender_for_sca, command_receiver_for_sca) =
                    mailbox(context_clone.inner().get_actor_mailbox_capacity());

                  // tokio_tcp_stream is moved into SessionConnectionActorX
                  let sca_task_handle = SessionConnectionActorX::create_and_spawn(
                    sca_handle_id,
                    parent_socket_core_id,
                    tokio_tcp_stream,
                    actor_conf,
                    engine_conf,
                    command_receiver_for_sca,
                    socket_logic,
                    Some(max_connection_permit),
                  );

                  interaction_model_for_event = Some(ConnectionInteractionModel::ViaSca {
                    sca_mailbox: command_sender_for_sca,
                    sca_handle_id,
                  });
                  managing_actor_task_id_for_event = Some(sca_task_handle.id());
                  connection_iface_for_event = None; // SocketCore creates ScaConnectionIface
                }
              }

              if setup_successful {
                if let Some(inter_model) = interaction_model_for_event {
                  let event = SystemEvent::NewConnectionEstablished {
                    parent_core_id: parent_socket_core_id,
                    endpoint_uri: actual_connected_uri.clone(),
                    target_endpoint_uri: logical_uri.clone(),
                    connection_iface: connection_iface_for_event,
                    interaction_model: inter_model,
                    managing_actor_task_id: managing_actor_task_id_for_event,
                  };
                  if context_clone.event_bus().publish(event).is_err() {
                    tracing::error!(
                      "Failed to publish NewConnectionEstablished for {}",
                      actual_connected_uri
                    );
                    // If session was spawned, it needs to be aborted
                    if let Some(task_id) = managing_actor_task_id_for_event {
                      // This is tricky, we don't have the JoinHandle here directly if it was session path.
                      // The SessionBase will stop itself if its parent (SocketCore) doesn't attach pipes.
                      // For UringFd, the FD might need explicit close if `connection_iface_for_event` was set.
                      tracing::warn!(
                        "NewConnectionEstablished publish failed, related session/FD for task_id {:?} might need manual cleanup if not handled by its own lifecycle.",
                        task_id
                      );
                    }
                  }
                } else {
                  tracing::error!(
                    "Inconsistent state: setup_successful true but interaction model missing for {}",
                    actual_connected_uri
                  );
                }
              } else {
                tracing::warn!(
                  "Connection setup failed for {}, NewConnectionEstablished not published.",
                  actual_connected_uri
                );
              }
            }
          });
        }
        Err(e) => {
          drop(permit);
          tracing::error!(
            "Error accepting TCP connection (listener {}): {}",
            endpoint_uri,
            e
          );
          if let Some(ref tx) = monitor_tx {
            let _ = tx.try_send(SocketEvent::AcceptFailed {
              endpoint: endpoint_uri.clone(),
              error_msg: e.to_string(),
            });
          }
          if is_fatal_accept_error(&e) {
            loop_error_to_report = Some(ZmqError::from_io_endpoint(e, &endpoint_uri));
            break;
          }
          sleep(Duration::from_millis(100)).await;
        }
      }
    }
    if let Some(err) = loop_error_to_report.take() {
      actor_drop_guard.set_error(err);
    } else {
      actor_drop_guard.waive();
    }
    tracing::info!("TCP Accept loop {} fully stopped.", accept_loop_handle);
  }
}

// --- TcpConnecter Actor ---
type UnifiedConnectOutcome = (
  Option<Arc<dyn ISocketConnection>>,
  ConnectionInteractionModel,
  Option<TaskId>, // managing_actor_task_id
  String,         // actual_peer_uri
);

pub(crate) struct TcpConnecter {
  handle: usize,
  endpoint: String,
  config: TcpTransportConfig,
  socket_options: Arc<SocketOptions>,
  socket_logic: Arc<dyn ISocket>,
  context_handle_source: Arc<std::sync::atomic::AtomicUsize>,
  context: Context,
  parent_socket_id: usize,
  initial_attempts: u32,
}

impl fmt::Debug for TcpConnecter {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("TcpConnecter")
      .field("handle", &self.handle)
      .field("endpoint", &self.endpoint)
      .field("config", &self.config)
      .field("context_options", &self.socket_options)
      .field("socket_logic_present", &true)
      .field("context_present", &true)
      .field("parent_socket_id", &self.parent_socket_id)
      .finish()
  }
}

impl TcpConnecter {
  pub(crate) fn create_and_spawn(
    handle: usize,
    endpoint: String,
    options: Arc<SocketOptions>,
    socket_logic: Arc<dyn ISocket>,
    context_handle_source: Arc<std::sync::atomic::AtomicUsize>,
    monitor_tx: Option<MonitorSender>,
    context: Context,
    parent_socket_id: usize,
    initial_attempts: u32,
  ) -> JoinHandle<()> {
    let transport_config = TcpTransportConfig {
      tcp_nodelay: options.tcp_nodelay,
      keepalive_time: options.tcp_keepalive_idle,
      keepalive_interval: options.tcp_keepalive_interval,
      keepalive_count: options.tcp_keepalive_count,
    };
    let connecter_actor = TcpConnecter {
      handle,
      endpoint: endpoint.clone(),
      config: transport_config,
      socket_options: options,
      socket_logic,
      context_handle_source,
      context: context.clone(),
      parent_socket_id,
      initial_attempts,
    };
    let task_join_handle =
      tokio::spawn(connecter_actor.run_connect_loop(monitor_tx, parent_socket_id));

    task_join_handle
  }

  async fn run_connect_loop(self, monitor_tx: Option<MonitorSender>, parent_socket_id: usize) {
    let connecter_handle = self.handle;
    let actor_type = ActorType::Connecter;
    let endpoint_uri_clone = self.endpoint.clone();
    let mut actor_drop_guard = ActorDropGuard::new(
      self.context.clone(),
      connecter_handle,
      actor_type,
      Some(endpoint_uri_clone.clone()),
      Some(parent_socket_id),
    );

    tracing::info!(handle = connecter_handle, uri = %endpoint_uri_clone, attempt_start = self.initial_attempts, "Long-Lived TCP Connecter actor started.");

    if !endpoint_uri_clone.starts_with("tcp://") {
      let err = ZmqError::InvalidEndpoint(endpoint_uri_clone.clone());
      let _ = self
        .context
        .event_bus()
        .publish(SystemEvent::ConnectionAttemptFailed {
          parent_core_id: self.parent_socket_id,
          target_endpoint_uri: self.endpoint.clone(),
          error: err.clone(),
        });
      actor_drop_guard.set_error(err);
      return;
    }

    let initial_reconnect_ivl = self
      .socket_options
      .reconnect_ivl
      .unwrap_or(Duration::from_millis(DEFAULT_RECONNECT_IVL_MS));
    let no_retry_after_first_connect_fail = self.socket_options.reconnect_ivl
      == Some(Duration::ZERO)
      && (self.socket_options.reconnect_ivl_max == Some(Duration::ZERO)
        || self.socket_options.reconnect_ivl_max.is_none());

    // Initialize backoff state based on inherited attempts
    let reconnect_ivl_max_opt = self.socket_options.reconnect_ivl_max;
    let mut current_retry_delay = initial_reconnect_ivl;

    // Fast-forward delay calculation to current attempt count if we are inheriting state
    if initial_reconnect_ivl > Duration::ZERO {
      if let Some(max_d) = reconnect_ivl_max_opt.filter(|d| *d > Duration::ZERO) {
        // Cap exponent to prevent overflow if initial_attempts is huge
        let iterations = self.initial_attempts.min(31);
        for _ in 0..iterations {
          current_retry_delay = (current_retry_delay * 2).min(max_d);
        }
      }
    }

    let mut attempt_count = self.initial_attempts;
    let mut system_event_rx = self.context.event_bus().subscribe();
    let mut last_connect_attempt_error: Option<ZmqError> = None;

    'connecter_life_loop: loop {
      // Wait condition: Only wait if this is a retry *within* this actor's life.
      // If attempt_count == initial_attempts, it means SocketCore just spawned us
      // after waiting the appropriate delay, so we should try immediately.
      if attempt_count > self.initial_attempts {
        if no_retry_after_first_connect_fail {
          tracing::info!(handle = connecter_handle, uri = %endpoint_uri_clone, "Connecter: Retries disabled. Stopping after first failure.");
          break 'connecter_life_loop;
        }
        match self
          .wait_for_retry_delay_internal(
            &mut system_event_rx,
            current_retry_delay,
            &monitor_tx,
            attempt_count as usize + 1,
          )
          .await
        {
          Ok(true) => {}
          Ok(false) => {
            last_connect_attempt_error = Some(ZmqError::Internal(
              "Connecter shutdown by event retry delay.".into(),
            ));
            break 'connecter_life_loop;
          }
          Err(()) => {
            last_connect_attempt_error = Some(ZmqError::Internal(
              "Connecter shutdown error retry delay.".into(),
            ));
            break 'connecter_life_loop;
          }
        }
        if current_retry_delay > Duration::ZERO
          && reconnect_ivl_max_opt.map_or(true, |max_d| max_d > Duration::ZERO)
        {
          if let Some(max_d) = reconnect_ivl_max_opt {
            current_retry_delay = (current_retry_delay * 2).min(max_d);
          } else {
            current_retry_delay = initial_reconnect_ivl;
          }
        } else if reconnect_ivl_max_opt.map_or(false, |max_d| max_d > Duration::ZERO) {
          current_retry_delay = reconnect_ivl_max_opt.unwrap();
        }
      }
      attempt_count += 1;

      match system_event_rx.try_recv() {
        Ok(SystemEvent::ContextTerminating) => {
          last_connect_attempt_error = Some(ZmqError::Internal(
            "Shutdown by ContextTerminating (pre-connect).".into(),
          ));
          break 'connecter_life_loop;
        }
        Ok(SystemEvent::SocketClosing { socket_id: sid }) if sid == self.parent_socket_id => {
          last_connect_attempt_error = Some(ZmqError::Internal(
            "Shutdown by parent SocketClosing (pre-connect).".into(),
          ));
          break 'connecter_life_loop;
        }
        Err(broadcast::error::TryRecvError::Closed) => {
          last_connect_attempt_error =
            Some(ZmqError::Internal("Event bus closed (pre-connect).".into()));
          break 'connecter_life_loop;
        }
        Err(broadcast::error::TryRecvError::Lagged(_)) => {
          last_connect_attempt_error =
            Some(ZmqError::Internal("Event bus lagged (pre-connect).".into()));
          break 'connecter_life_loop;
        }
        _ => {}
      }

      tracing::debug!(handle = connecter_handle, uri = %endpoint_uri_clone, "Connecter: TCP connect attempt #{}", attempt_count);

      let single_attempt_outcome: Result<UnifiedConnectOutcome, ZmqError> = self
        .try_connect_once(&endpoint_uri_clone, &mut system_event_rx, &monitor_tx)
        .await;

      match single_attempt_outcome {
        Ok((connection_iface_opt, interaction_model, managing_actor_task_id, actual_peer_uri)) => {
          tracing::info!(handle = connecter_handle, uri = %endpoint_uri_clone, actual_peer = %actual_peer_uri, "Connecter: TCP connect successful.");
          let event = SystemEvent::NewConnectionEstablished {
            parent_core_id: self.parent_socket_id,
            endpoint_uri: actual_peer_uri,
            target_endpoint_uri: endpoint_uri_clone.clone(),
            connection_iface: connection_iface_opt,
            interaction_model,
            managing_actor_task_id,
          };
          if self.context.event_bus().publish(event).is_err() {
            tracing::error!(
              "Connecter: Failed to publish NewConnectionEstablished for {}.",
              endpoint_uri_clone
            );
            last_connect_attempt_error = Some(ZmqError::Internal(
              "Failed to publish NewConnectionEstablished".into(),
            ));
          } else {
            last_connect_attempt_error = None;
          }
          break 'connecter_life_loop;
        }
        Err(attempt_failure_error) => {
          last_connect_attempt_error = Some(attempt_failure_error.clone());

          tracing::warn!(handle = connecter_handle, uri = %endpoint_uri_clone, error = %attempt_failure_error, "Connecter: TCP connect attempt #{} failed.", attempt_count);

          if is_fatal_connect_error(&attempt_failure_error)
            || matches!(&attempt_failure_error, ZmqError::Internal(s) if s.contains("shutdown by") || s.contains("event bus error"))
          {
            tracing::error!(handle = connecter_handle, uri = %endpoint_uri_clone, error = %attempt_failure_error, "Connecter: Fatal error. Stopping.");
            break 'connecter_life_loop;
          }

          // If we fail on the very first attempt (freshly spawned) AND retries are disabled, stop.
          if no_retry_after_first_connect_fail && attempt_count == 1 {
            tracing::info!(handle = connecter_handle, uri = %endpoint_uri_clone, "Connecter: No retry, stopping after first fail.");
            break 'connecter_life_loop;
          }

          // Emit ConnectDelayed only once per actor lifecycle/retry-sequence to avoid log spam.
          // Check if it matches initial_attempts + 1.
          if attempt_count == self.initial_attempts + 1 {
            if let Some(ref mon_tx) = monitor_tx {
              let _ = mon_tx.try_send(SocketEvent::ConnectDelayed {
                endpoint: endpoint_uri_clone.clone(),
                error_msg: attempt_failure_error.to_string(),
              });
            }
          }
        }
      }
    }

    if let Some(ref final_err) = last_connect_attempt_error {
      if !matches!(final_err, ZmqError::Internal(s) if s.contains("shutdown by") || s.contains("event bus error"))
      {
        let _ = self
          .context
          .event_bus()
          .publish(SystemEvent::ConnectionAttemptFailed {
            parent_core_id: self.parent_socket_id,
            target_endpoint_uri: endpoint_uri_clone.clone(),
            error: final_err.clone(),
          });
        if let Some(ref mon_tx_final) = monitor_tx {
          let _ = mon_tx_final.try_send(SocketEvent::ConnectFailed {
            endpoint: endpoint_uri_clone.clone(),
            error_msg: final_err.to_string(),
          });
        }
      }
    }

    if let Some(err) = last_connect_attempt_error.take() {
      actor_drop_guard.set_error(err);
    } else {
      actor_drop_guard.waive();
    }
    tracing::info!(handle = connecter_handle, uri = %self.endpoint, "TCP Connecter actor task fully stopped.");
  }

  async fn try_connect_once(
    &self,
    endpoint_uri_original: &str,
    system_event_rx: &mut broadcast::Receiver<SystemEvent>,
    monitor_tx: &Option<MonitorSender>,
  ) -> Result<UnifiedConnectOutcome, ZmqError> {
    let addr_str = endpoint_uri_original
      .strip_prefix("tcp://")
      .unwrap_or(endpoint_uri_original);

    // Perform a fresh, async DNS lookup on each connection attempt.
    let addrs_iter = tokio::net::lookup_host(addr_str).await.map_err(|e| {
      ZmqError::DnsResolutionFailed(format!("Failed to resolve '{}': {}", addr_str, e))
    })?;

    let mut last_error: Option<ZmqError> = None;

    for target_socket_addr in addrs_iter {
      let use_io_uring = self.socket_options.io_uring.session_enabled && cfg!(feature = "io-uring");

      let connect_future = async {
        if use_io_uring {
          #[cfg(feature = "io-uring")]
          {
            let domain = if target_socket_addr.is_ipv4() {
              socket2::Domain::IPV4
            } else {
              socket2::Domain::IPV6
            };
            let socket =
              socket2::Socket::new(domain, socket2::Type::STREAM, None).map_err(ZmqError::from)?;
            apply_socket2_options_pre_connect(&socket, &self.config)?;

            if self.socket_options.tcp_cork {
              tracing::debug!(
                handle = self.handle,
                "TcpConnecter: Applying TCP_CORK to outgoing connection FD before connect for IO URing."
              );
              if let Err(e) = socket.set_tcp_cork(true) {
                tracing::error!(handle = self.handle, error = %e, "TcpConnecter: Failed to set TCP_Cork (socket2) for IO URing FD. Proceeding without.");
              }
            }

            let std_stream: std::net::TcpStream = tokio::task::spawn_blocking({
              let addr_clone = target_socket_addr;
              move || {
                let _ = socket.connect(&addr_clone.into());
                socket.into()
              }
            })
            .await
            .map_err(|je| ZmqError::Internal(format!("Blocking connect join error: {}", je)))?;

            let peer_addr_actual = std_stream.peer_addr().map_err(ZmqError::from)?;

            if let Some(mon_tx) = monitor_tx {
              let _ = mon_tx.try_send(SocketEvent::Connected {
                endpoint: endpoint_uri_original.to_string(),
                peer_addr: format!("tcp://{}", peer_addr_actual),
              });
            }
            apply_tcp_socket_options_to_std(&std_stream, &self.config)?;
            let raw_fd = std_stream.into_raw_fd();
            let worker_op_tx = uring::global_state::get_global_uring_worker_op_tx()?;
            let protocol_config =
              WorkerProtocolConfig::Zmtp(Arc::new(ZmtpEngineConfig::from(&*self.socket_options)));
            let user_data_for_op = self.context.inner().next_handle() as u64;
            let (reply_tx_for_op, reply_rx_for_op) = oneshot();
            let hwm = self.socket_options.sndhwm.max(1);
            let (mpsc_tx_for_conn, mpsc_rx_for_worker) = mpsc::bounded(hwm);
            let new_conn_iface = Arc::new(UringFdConnection::new(
              raw_fd,
              mpsc_tx_for_conn.to_async(),
              self.context.clone(),
            ));
            let register_fd_req = WorkerUringOpRequest::RegisterExternalFd {
              user_data: user_data_for_op,
              fd: raw_fd,
              protocol_handler_factory_id: "zmtp-uring/3.1".to_string(),
              protocol_config,
              is_server_role: false,
              reply_tx: reply_tx_for_op,
              mpsc_rx_for_worker: Arc::new(mpsc_rx_for_worker),
            };
            worker_op_tx.send(register_fd_req).await.map_err(|e| {
              ZmqError::Internal(format!("Send RegisterExternalFd to UringWorker: {}", e))
            })?;
            match reply_rx_for_op.recv().await {
              Ok(Ok(WorkerUringOpCompletion::RegisterExternalFdSuccess {
                fd: returned_fd,
                ..
              }))
                if returned_fd == raw_fd =>
              {
                info!(
                  "Successfully registered connected FD {} with UringWorker.",
                  raw_fd
                );
                let connection_iface: Option<Arc<dyn ISocketConnection>> = Some(new_conn_iface);
                let interaction_model = ConnectionInteractionModel::ViaUringFd { fd: raw_fd };
                Ok((
                  connection_iface,
                  interaction_model,
                  None,
                  format!("tcp://{}", peer_addr_actual),
                ))
              }
              Ok(Ok(other_completion)) => {
                tracing::error!(
                  "UringWorker bad success for RegisterExternalFd (fd {}): {:?}",
                  raw_fd,
                  other_completion
                );
                unsafe {
                  let _ = libc::close(raw_fd);
                }
                Err(ZmqError::Internal(format!(
                  "UringWorker unexpected success: {:?}",
                  other_completion
                )))
              }
              Ok(Err(worker_err)) => {
                tracing::error!(
                  "Register FD {} with UringWorker failed (worker error): {:?}",
                  raw_fd,
                  worker_err
                );
                unsafe {
                  let _ = libc::close(raw_fd);
                }
                Err(worker_err)
              }
              Err(oneshot_recv_err) => {
                tracing::error!(
                  "Register FD {} with UringWorker failed (reply channel error): {:?}",
                  raw_fd,
                  oneshot_recv_err
                );
                unsafe {
                  let _ = libc::close(raw_fd);
                }
                Err(ZmqError::Internal(format!(
                  "Register FD with UringWorker reply error: {:?}",
                  oneshot_recv_err
                )))
              }
            }
          }
          #[cfg(not(feature = "io-uring"))]
          {
            unreachable!();
          }
        } else {
          // Standard path for SessionBase
          let std_tokio_stream = underlying_std_net::TcpStream::connect(target_socket_addr)
            .await
            .map_err(|e| ZmqError::from_io_endpoint(e, endpoint_uri_original))?;

          let peer_addr_actual = std_tokio_stream.peer_addr().map_err(ZmqError::from)?;

          if let Some(mon_tx) = monitor_tx {
            let _ = mon_tx.try_send(SocketEvent::Connected {
              endpoint: endpoint_uri_original.to_string(),
              peer_addr: format!("tcp://{}", peer_addr_actual),
            });
          }

          apply_tcp_socket_options_to_tokio(&std_tokio_stream, &self.config)?;

          let actual_connected_uri = format!("tcp://{}", peer_addr_actual);
          let sca_handle_id = self
            .context_handle_source
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
          let actor_conf = ActorConfigX {
            context: self.context.clone(),
            monitor_tx: monitor_tx.clone(),
            logical_target_endpoint_uri: endpoint_uri_original.to_string(),
            connected_endpoint_uri: actual_connected_uri.clone(),
            is_server_role: false,
          };
          let engine_conf = Arc::new(ZmtpEngineConfig::from(&*self.socket_options));
          let (command_sender_for_sca, command_receiver_for_sca) =
            mailbox(self.context.inner().get_actor_mailbox_capacity());

          let sca_task_handle = SessionConnectionActorX::create_and_spawn(
            sca_handle_id,
            self.parent_socket_id,
            std_tokio_stream,
            actor_conf,
            engine_conf,
            command_receiver_for_sca,
            self.socket_logic.clone(),
            None,
          );

          let interaction_model = ConnectionInteractionModel::ViaSca {
            sca_mailbox: command_sender_for_sca,
            sca_handle_id,
          };

          return Ok((
            None,
            interaction_model,
            Some(sca_task_handle.id()),
            format!("tcp://{}", peer_addr_actual),
          ));
        }
      };

      tokio::select! {
        biased;
        _ = async {
          loop {
            match system_event_rx.recv().await {
              Ok(SystemEvent::ContextTerminating) => break,
              Ok(SystemEvent::SocketClosing { socket_id: sid }) if sid == self.parent_socket_id => break,
              Ok(_) => continue,
              Err(_) => break,
            }
          }
        } => {
          // If the select is aborted by a system event, we stop trying more IPs.
          return Err(ZmqError::Internal("Connect aborted by system event.".into()));
        }
        connect_outcome_result = connect_future => {
          match connect_outcome_result {
            Ok(unified_outcome) => return Ok(unified_outcome), // Success! Return immediately.
            Err(e) => {
              // Connection to this IP failed, store error and let the loop try the next one.
              last_error = Some(e);
            }
          }
        }
      }
    }

    // If the loop finishes without returning, all attempts failed.
    Err(last_error.unwrap_or_else(|| {
      ZmqError::HostUnreachable(format!(
        "No IP addresses found or all attempts failed for {}",
        addr_str
      ))
    }))
  }

  async fn wait_for_retry_delay_internal(
    &self,
    system_event_rx: &mut broadcast::Receiver<SystemEvent>,
    delay: Duration,
    monitor_tx: &Option<MonitorSender>,
    next_attempt_num: usize,
  ) -> Result<bool, ()> {
    if delay.is_zero() {
      match system_event_rx.try_recv() {
        Ok(SystemEvent::ContextTerminating) | Ok(SystemEvent::SocketClosing { .. }) => {
          return Ok(false);
        }
        _ => return Ok(true),
      }
    }
    tracing::debug!(handle = self.handle, uri = %self.endpoint, ?delay, "Connecter waiting before attempt #{}", next_attempt_num);
    if let Some(tx) = monitor_tx {
      let _ = tx.try_send(SocketEvent::ConnectRetried {
        endpoint: self.endpoint.clone(),
        interval: delay,
      });
    }
    tokio::select! {
      biased;
      event_res = system_event_rx.recv() => {
        match event_res {
          Ok(SystemEvent::ContextTerminating) => Ok(false),
          Ok(SystemEvent::SocketClosing { socket_id: s_id }) if s_id == self.parent_socket_id => Ok(false),
          Err(_) => Ok(false),
          Ok(_) => Ok(true),
        }
      }
      _ = tokio::time::sleep(delay) => Ok(true),
    }
  }
}

// --- Helper Functions ---
pub(crate) fn is_fatal_accept_error(e: &io::Error) -> bool {
  matches!(
    e.kind(),
    io::ErrorKind::InvalidInput | io::ErrorKind::BrokenPipe
  )
}

pub(crate) fn is_fatal_connect_error(e: &ZmqError) -> bool {
  match e {
    ZmqError::IoError { kind, .. } => {
      matches!(
        kind,
        // Physical configuration issues are fatal
        io::ErrorKind::AddrNotAvailable
          | io::ErrorKind::AddrInUse
          | io::ErrorKind::InvalidInput
          | io::ErrorKind::PermissionDenied // ConnectionRefused is transient (server down), NOT fatal.
      )
    }
    // Structural issues are fatal
    ZmqError::InvalidEndpoint(_) | ZmqError::UnsupportedTransport(_) => true,

    // DNS might be transient, but often indicates misconfig.
    // ZMQ usually retries DNS, but let's stick to fatal if name doesn't resolve to avoid infinite loops on typos.
    ZmqError::DnsResolutionFailed(_) => true,

    // Protocol/Security errors during handshake should trigger backoff retry, not permanent death.
    // This allows recovery if credentials/keys are fixed on the server side.
    ZmqError::SecurityError(_)
    | ZmqError::AuthenticationFailure(_)
    | ZmqError::ProtocolViolation(_) => false,

    // All others (Timeout, ConnectionClosed, etc.) are transient
    _ => false,
  }
}

#[cfg(feature = "io-uring")]
fn apply_socket2_options_pre_connect(
  socket: &socket2::Socket,
  config: &TcpTransportConfig,
) -> Result<(), ZmqError> {
  socket
    .set_tcp_nodelay(config.tcp_nodelay)
    .map_err(ZmqError::from)?;
  if config.keepalive_time.is_some()
    || config.keepalive_interval.is_some()
    || config.keepalive_count.is_some()
  {
    let mut keepalive = TcpKeepalive::new();
    if let Some(time) = config.keepalive_time {
      keepalive = keepalive.with_time(time);
    }
    #[cfg(any(unix, target_os = "windows"))]
    if let Some(interval) = config.keepalive_interval {
      keepalive = keepalive.with_interval(interval);
    }
    #[cfg(unix)]
    if let Some(count) = config.keepalive_count {
      keepalive = keepalive.with_retries(count);
    }
    socket
      .set_tcp_keepalive(&keepalive)
      .map_err(ZmqError::from)?;
  }
  Ok(())
}

fn apply_tcp_socket_options_to_tokio(
  stream: &tokio::net::TcpStream,
  config: &TcpTransportConfig,
) -> Result<(), ZmqError> {
  let socket_ref = SockRef::from(stream);
  socket_ref.set_tcp_nodelay(config.tcp_nodelay)?;
  if config.keepalive_time.is_some()
    || config.keepalive_interval.is_some()
    || config.keepalive_count.is_some()
  {
    let mut keepalive = TcpKeepalive::new();
    if let Some(time) = config.keepalive_time {
      keepalive = keepalive.with_time(time);
    }
    #[cfg(any(unix, target_os = "windows"))]
    if let Some(interval) = config.keepalive_interval {
      keepalive = keepalive.with_interval(interval);
    }
    #[cfg(unix)]
    if let Some(count) = config.keepalive_count {
      keepalive = keepalive.with_retries(count);
    }
    socket_ref.set_tcp_keepalive(&keepalive)?;
  }
  Ok(())
}

#[cfg(feature = "io-uring")]
fn apply_tcp_socket_options_to_std(
  stream: &std::net::TcpStream,
  config: &TcpTransportConfig,
) -> Result<(), ZmqError> {
  let socket_ref = SockRef::from(stream);
  socket_ref.set_tcp_nodelay(config.tcp_nodelay)?;
  if config.keepalive_time.is_some()
    || config.keepalive_interval.is_some()
    || config.keepalive_count.is_some()
  {
    let mut keepalive = TcpKeepalive::new();
    if let Some(time) = config.keepalive_time {
      keepalive = keepalive.with_time(time);
    }
    #[cfg(any(unix, target_os = "windows"))]
    if let Some(interval) = config.keepalive_interval {
      keepalive = keepalive.with_interval(interval);
    }
    #[cfg(unix)]
    if let Some(count) = config.keepalive_count {
      keepalive = keepalive.with_retries(count);
    }
    socket_ref.set_tcp_keepalive(&keepalive)?;
  }
  Ok(())
}