rzmq 0.5.18

High performance, CPU and memory efficient, 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
#![cfg(feature = "ipc")]

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::events::{MonitorSender, SocketEvent};
use crate::socket::options::SocketOptions;
use crate::socket::{ISocket, ZmtpEngineConfig};

use core::fmt;
use std::io;
use std::os::fd::AsRawFd;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use socket2::SockRef;
use tokio::net::{UnixListener as TokioUnixListener, UnixStream};
use tokio::sync::{Semaphore, broadcast};
use tokio::task::{Id as TaskId, JoinHandle};
use tokio::time::sleep;

#[cfg(feature = "io-uring")]
use {
  crate::io_uring_backend::byte_handler::EgressChunk,
  crate::io_uring_backend::ops::UringOpRequest as WorkerUringOpRequest,
  crate::transport::uring_stream::UringStream,
  crate::uring,
  fibre::oneshot::oneshot as fibre_oneshot,
  std::os::unix::io::IntoRawFd,
  std::sync::atomic::Ordering as AtomicOrdering,
};

// --- IpcListener Actor ---
pub(crate) struct IpcListener {
  handle: usize,
  endpoint: String,
  path: PathBuf,
  mailbox_receiver: GenericMailboxReceiver,
  listener_handle: Option<JoinHandle<()>>, // Option to allow taking it in run_command_loop
  context: Context,
  parent_socket_id: usize,
  socket_logic: Arc<dyn ISocket>,
}

impl fmt::Debug for IpcListener {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("IpcListener")
      .field("handle", &self.handle)
      .field("endpoint", &self.endpoint)
      .field("path", &self.path)
      .field(
        "mailbox_receiver_is_closed",
        &self.mailbox_receiver.is_closed(),
      )
      .field("listener_handle_is_some", &self.listener_handle.is_some())
      .field("context_present", &true) // Avoid printing full context
      .field("parent_socket_id", &self.parent_socket_id)
      .field("socket_logic_present", &true) // Placeholder for Arc<dyn ISocket>
      .finish()
  }
}

impl IpcListener {
  pub(crate) fn create_and_spawn(
    handle: usize,
    endpoint_uri: String, // User-provided URI
    path: PathBuf,        // Parsed path from URI
    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);

    match std::fs::remove_file(&path) {
      Ok(_) => {
        tracing::debug!(listener_handle = handle, path = ?path, "Removed existing IPC socket file.")
      }
      Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
      Err(e) => {
        tracing::warn!(listener_handle = handle, path = ?path, error = %e, "Failed to remove existing IPC socket file.")
      }
    }

    let listener =
      TokioUnixListener::bind(&path).map_err(|e| ZmqError::from_io_endpoint(e, &endpoint_uri))?;
    let resolved_uri = endpoint_uri.clone();
    tracing::info!(listener_handle = handle, path = ?path, uri = %resolved_uri, "IPC Listener bound successfully");

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

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

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

    let listener_actor = IpcListener {
      handle,
      endpoint: resolved_uri.clone(),
      path,
      mailbox_receiver: rx,
      listener_handle: Some(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_handle_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();
    let listener_abort_handle = self.listener_handle.take();

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

    tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC Listener command loop started");
    let mut final_error_for_actor_stopping: Option<ZmqError> = None;

    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, "IPC Listener received ContextTerminating, stopping accept loop.");
                if let Some(h) = &listener_abort_handle { h.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, "IPC Listener received SocketClosing for parent, stopping accept loop.");
                if let Some(h) = &listener_abort_handle { h.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 for IPC Listener command loop!");
                if let Some(h) = &listener_abort_handle { h.abort(); }
                final_error_for_actor_stopping = Some(ZmqError::Internal("Listener event bus lagged (IPC)".into())); break;
              }
              Err(broadcast::error::RecvError::Closed) => {
                tracing::error!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "System event bus closed unexpectedly for IPC Listener command loop!");
                if let Some(h) = &listener_abort_handle { h.abort(); }
                final_error_for_actor_stopping = Some(ZmqError::Internal("Listener event bus closed (IPC)".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, "IPC Listener received Stop command");
                if let Some(h) = &listener_abort_handle { h.abort(); } break;
              }
              Ok(other_cmd) => tracing::warn!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC Listener received unhandled command: {:?}", other_cmd.variant_name()),
              Err(_) => {
                tracing::info!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC Listener command mailbox closed, stopping accept loop.");
                if let Some(h) = &listener_abort_handle { h.abort(); }
                if final_error_for_actor_stopping.is_none() { final_error_for_actor_stopping = Some(ZmqError::Internal("Listener command mailbox closed by peer (IPC)".into())); }
                break;
              }
            }
          }
        }
      }
      Ok(())
    }.await;

    tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC Listener command loop finished, awaiting accept loop task.");
    if let Some(listener_join_handle) = listener_abort_handle {
      if let Err(e) = listener_join_handle.await {
        if !e.is_cancelled() {
          tracing::error!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC 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 (IPC): {:?}",
              e
            )));
          }
        } else {
          tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC Listener accept loop task cancelled.");
        }
      } else {
        tracing::debug!(handle = listener_cmd_loop_handle, uri = %endpoint_uri_clone_log, "IPC Listener accept loop task joined cleanly.");
      }
    }

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

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

  async fn run_accept_loop(
    accept_loop_handle: usize,
    _listener_cmd_loop_handle: usize,
    endpoint_uri: String, // Resolved listener URI
    listener: Arc<TokioUnixListener>,
    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>,
  ) {
    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, "IPC Accept loop started.");
    let mut loop_error_to_report: Option<ZmqError>;

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

      match listener.accept().await {
        Ok((unix_stream, _ipc_peer_addr_os_specific)) => {
          let _permit_guard = permit;
          let peer_addr_str = format!("ipc-peer-fd-{}", unix_stream.as_raw_fd());
          tracing::info!(
            "Accepted new IPC connection (peer: {}) 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 socket_ref = SockRef::from(&unix_stream);
            if let Some(size) = socket_options.sndbuf {
              let _ = socket_ref.set_send_buffer_size(size);
            }
            if let Some(size) = socket_options.rcvbuf {
              let _ = socket_ref.set_recv_buffer_size(size);
            }
          }

          let connection_specific_uri = format!("ipc://{}", peer_addr_str);

          #[cfg(feature = "io-uring")]
          let use_io_uring = socket_options.io_uring.session_enabled
            && uring::URING_BACKEND_INITIALIZED.load(AtomicOrdering::SeqCst);
          #[cfg(not(feature = "io-uring"))]
          let use_io_uring = false;

          tokio::spawn({
            let context_clone = context.clone();
            let socket_options_clone = socket_options.clone();
            let monitor_tx_clone = monitor_tx.clone();
            let handle_source_clone = handle_source.clone();
            let actual_connected_uri = connection_specific_uri.clone();
            let logical_uri = endpoint_uri.clone();
            let socket_logic = socket_logic.clone();

            async move {
              let mut permit_opt = Some(_permit_guard);
              let mut interaction_model_for_event: Option<ConnectionInteractionModel> = None;
              let mut managing_actor_task_id_for_event: Option<TaskId> = None;
              let mut setup_successful = false;
              // Wrap so either path can consume it without confusing the borrow checker.
              let mut unix_stream_opt = Some(unix_stream);

              // --- io_uring path ---
              #[cfg(feature = "io-uring")]
              if use_io_uring {
                let stream = unix_stream_opt.take().unwrap();
                match stream.into_std() {
                  Ok(std_stream) => {
                    let raw_fd = std_stream.into_raw_fd();
                    let rcvhwm = socket_options_clone.rcvhwm.max(1);
                    let sndhwm = socket_options_clone.sndhwm.max(1);
                    let (raw_inbound_tx, raw_inbound_rx_sync) =
                      fibre::mpsc::bounded::<bytes::Bytes>(rcvhwm);
                    let (raw_egress_sync_tx, raw_egress_rx) =
                      fibre::mpsc::bounded::<EgressChunk>(sndhwm);

                    match uring::global_state::get_global_uring_worker_op_tx() {
                      Ok(worker_op_tx) => {
                        let user_data = context_clone.inner().next_handle() as u64;
                        let (reply_tx, reply_rx) = fibre_oneshot();
                        let reg_ok = worker_op_tx.send(WorkerUringOpRequest::RegisterExternalByteFd {
                          user_data,
                          fd: raw_fd,
                          socket_mailbox: socket_logic.mailbox().to_sync(),
                          reply_tx,
                          raw_inbound_tx,
                          raw_egress_rx,
                          use_recv_multishot: socket_options_clone.io_uring.recv_multishot,
                        }).await.is_ok();

                        if reg_ok {
                          match reply_rx.recv().await {
                            Ok(Ok(_)) => {
                              let event_fd = worker_op_tx.clone_event_fd();
                              let worker_asleep = worker_op_tx.clone_worker_asleep();
                              let send_pool = worker_op_tx.clone_send_buffer_pool();
                              let uring_stream = UringStream::new(
                                raw_fd,
                                raw_inbound_rx_sync.to_async(),
                                raw_egress_sync_tx,
                                worker_asleep,
                                event_fd,
                                send_pool,
                                rcvhwm,
                              );
                              let sca_handle_id = handle_source_clone
                                .fetch_add(1, AtomicOrdering::Relaxed);
                              let actor_conf = ActorConfigX {
                                context: context_clone.clone(),
                                monitor_tx: monitor_tx_clone.clone(),
                                logical_target_endpoint_uri: logical_uri.clone(),
                                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());
                              let sca_task_handle = SessionConnectionActorX::create_and_spawn(
                                sca_handle_id,
                                parent_socket_core_id,
                                uring_stream,
                                actor_conf,
                                engine_conf,
                                command_receiver_for_sca,
                                socket_logic.clone(),
                                permit_opt.take(),
                              );
                              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());
                              setup_successful = true;
                            }
                            _ => tracing::error!("IPC accept: RegisterExternalByteFd failed"),
                          }
                        }
                      }
                      Err(e) => tracing::error!("IPC accept: no uring worker: {}", e),
                    }
                  }
                  Err(e) => tracing::error!("IPC accept: into_std failed: {}", e),
                }
              }

              // --- Standard path (non-uring or not yet set up) ---
              if let Some(unix_stream) = unix_stream_opt {
                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(),
                  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());
                let sca_task_handle = SessionConnectionActorX::create_and_spawn(
                  sca_handle_id,
                  parent_socket_core_id,
                  unix_stream,
                  actor_conf,
                  engine_conf,
                  command_receiver_for_sca,
                  socket_logic.clone(),
                  permit_opt.take(),
                );
                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());
                setup_successful = true;
              }

              if setup_successful {
                if let Some(inter_model) = interaction_model_for_event {
                  let cmd = Command::NewConnectionEstablished {
                    endpoint_uri: actual_connected_uri.clone(),
                    target_endpoint_uri: logical_uri.clone(),
                    connection_iface: None,
                    interaction_model: inter_model,
                    managing_actor_task_id: managing_actor_task_id_for_event,
                  };
                  if socket_logic.mailbox().send(cmd).await.is_err() {
                    tracing::error!(
                      "Failed to send NewConnectionEstablished to socket mailbox for IPC {}",
                      actual_connected_uri
                    );
                  }
                }
              } else {
                tracing::warn!(
                  "IPC Connection setup failed for {}, NewConnectionEstablished not sent.",
                  actual_connected_uri
                );
              }
            }
          });
        }
        Err(e) => {
          drop(permit);
          tracing::error!(
            "Error accepting IPC 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_ipc_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 {
      actor_drop_guard.set_error(err);
    } else {
      actor_drop_guard.waive();
    }

    tracing::info!("IPC Accept loop {} fully stopped.", accept_loop_handle);
  }
}

impl Drop for IpcListener {
  fn drop(&mut self) {
    tracing::debug!(listener_handle = self.handle, path = ?self.path, "Dropping IpcListener, cleaning up IPC socket file");
    if let Some(listener_join_handle) = self.listener_handle.take() {
      if !listener_join_handle.is_finished() {
        listener_join_handle.abort();
        tracing::debug!(listener_handle = self.handle, path = ?self.path, "Aborted accept loop task in IpcListener Drop.");
      }
    }
    match std::fs::remove_file(&self.path) {
      Ok(_) => {
        tracing::debug!(listener_handle = self.handle, path = ?self.path, "Removed IPC socket file.")
      }
      Err(e) if e.kind() == io::ErrorKind::NotFound => {
        tracing::trace!(listener_handle = self.handle, path = ?self.path, "IPC socket file not found during drop.")
      }
      Err(e) => {
        tracing::warn!(listener_handle = self.handle, path = ?self.path, error = %e, "Failed to remove IPC socket file during drop.")
      }
    }
  }
}

// --- IpcConnecter Actor ---
pub(crate) struct IpcConnecter {
  handle: usize,
  endpoint_uri: String,
  path: PathBuf,
  context_options: Arc<SocketOptions>,
  socket_logic: Arc<dyn ISocket>,
  context_handle_source: Arc<std::sync::atomic::AtomicUsize>,
  context: Context,
  parent_socket_id: usize,
}

impl fmt::Debug for IpcConnecter {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("IpcConnecter")
      .field("handle", &self.handle)
      .field("endpoint_uri", &self.endpoint_uri)
      .field("path", &self.path)
      .field("context_options", &self.context_options) // SocketOptions is Debug
      .field("socket_logic_present", &true) // Placeholder
      .field("context_present", &true)
      .field("parent_socket_id", &self.parent_socket_id)
      .finish()
  }
}

impl IpcConnecter {
  pub(crate) fn create_and_spawn(
    handle: usize,
    endpoint_uri: String,
    path: PathBuf,
    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,
  ) -> JoinHandle<()> {
    let connecter_actor = IpcConnecter {
      handle,
      endpoint_uri: endpoint_uri.clone(),
      path,
      context_options: options,
      context_handle_source,
      context: context.clone(),
      parent_socket_id,
      socket_logic,
    };
    let task_join_handle =
      tokio::spawn(connecter_actor.run_connect_attempt(monitor_tx, parent_socket_id));
    task_join_handle
  }

  async fn run_connect_attempt(
    self,
    monitor_tx: Option<MonitorSender>,
    _parent_socket_id_unused: usize,
  ) {
    let connecter_handle = self.handle;
    let endpoint_uri_original = self.endpoint_uri.clone(); // User's target URI

    let mut actor_drop_guard = ActorDropGuard::new(
      self.context.clone(),
      connecter_handle,
      ActorType::Connecter,
      Some(endpoint_uri_original.clone()),
      Some(self.parent_socket_id),
    );
    tracing::info!(handle = connecter_handle, uri = %endpoint_uri_original, path = ?self.path, "IPC Connecter actor started.");

    // Variables to hold the outcome of the connection attempt
    let connection_outcome: Result<
      (
        ConnectionInteractionModel,
        Option<TaskId>,
        String, /* actual_uri */
      ),
      ZmqError,
    >;

    // For IPC, we typically attempt to connect once with a timeout.
    // More complex retry logic like TCP's isn't standard for local IPC paths.
    // Use handshake_ivl as a connect timeout, or a default.
    let connect_timeout = self
      .context_options
      .handshake_ivl
      .unwrap_or_else(|| Duration::from_secs(5));
    let mut system_event_rx = self.context.event_bus().subscribe(); // For early abort

    let connect_future = UnixStream::connect(&self.path);

    tokio::select! {
      biased;
      _ = async { // Early abort if context/socket is closing
        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, // Channel closed or lagged
          }
        }
      } => {
          connection_outcome = Err(ZmqError::Internal("IPC Connect aborted by system event.".into()));
      }
      connect_result = tokio::time::timeout(connect_timeout, connect_future) => {
        match connect_result {
          Ok(Ok(unix_stream)) => { // Successfully connected within timeout
            #[cfg(unix)]
            let peer_id_str = format!("ipc-fd-{}", unix_stream.as_raw_fd());
            #[cfg(not(unix))] // Fallback if AsRawFd is not available/not unix
            let peer_id_str = format!("ipc-conn-{}", self.context_handle_source.fetch_add(1, std::sync::atomic::Ordering::Relaxed));

            let actual_connected_uri = format!("ipc://{}", peer_id_str);
            tracing::info!(handle = connecter_handle, uri = %endpoint_uri_original, actual = %actual_connected_uri, "IPC Connect successful");

            if let Some(ref tx) = monitor_tx {
            let _ = tx.try_send(SocketEvent::Connected {
              endpoint: endpoint_uri_original.clone(),
              peer_addr: actual_connected_uri.clone(),
            });
            }

            #[cfg(feature = "io-uring")]
            let connect_use_io_uring = self.context_options.io_uring.session_enabled
              && uring::URING_BACKEND_INITIALIZED.load(AtomicOrdering::SeqCst);
            #[cfg(not(feature = "io-uring"))]
            let connect_use_io_uring = false;

            let mut unix_stream_opt = Some(unix_stream);
            let mut connect_interaction: Option<ConnectionInteractionModel> = None;
            let mut connect_task_id: Option<TaskId> = None;

            // --- io_uring connect path ---
            #[cfg(feature = "io-uring")]
            if connect_use_io_uring {
              let stream = unix_stream_opt.take().unwrap();
              match stream.into_std() {
                Ok(std_stream) => {
                  let raw_fd = std_stream.into_raw_fd();
                  let rcvhwm = self.context_options.rcvhwm.max(1);
                  let sndhwm = self.context_options.sndhwm.max(1);
                  let (raw_inbound_tx, raw_inbound_rx_sync) =
                    fibre::mpsc::bounded::<bytes::Bytes>(rcvhwm);
                  let (raw_egress_sync_tx, raw_egress_rx) =
                    fibre::mpsc::bounded::<EgressChunk>(sndhwm);

                  match uring::global_state::get_global_uring_worker_op_tx() {
                    Ok(worker_op_tx) => {
                      let user_data = self.context.inner().next_handle() as u64;
                      let (reply_tx, reply_rx) = fibre_oneshot();
                      let reg_ok = worker_op_tx.send(WorkerUringOpRequest::RegisterExternalByteFd {
                        user_data,
                        fd: raw_fd,
                        socket_mailbox: self.socket_logic.mailbox().to_sync(),
                        reply_tx,
                        raw_inbound_tx,
                        raw_egress_rx,
                        use_recv_multishot: self.context_options.io_uring.recv_multishot,
                      }).await.is_ok();

                      if reg_ok {
                        match reply_rx.recv().await {
                          Ok(Ok(_)) => {
                            let event_fd = worker_op_tx.clone_event_fd();
                            let worker_asleep = worker_op_tx.clone_worker_asleep();
                            let send_pool = worker_op_tx.clone_send_buffer_pool();
                            let uring_stream = UringStream::new(
                              raw_fd,
                              raw_inbound_rx_sync.to_async(),
                              raw_egress_sync_tx,
                              worker_asleep,
                              event_fd,
                              send_pool,
                              rcvhwm,
                            );
                            let sca_handle_id = self.context_handle_source
                              .fetch_add(1, AtomicOrdering::Relaxed);
                            let actor_conf = ActorConfigX {
                              context: self.context.clone(),
                              monitor_tx: monitor_tx.clone(),
                              logical_target_endpoint_uri: endpoint_uri_original.clone(),
                              connected_endpoint_uri: actual_connected_uri.clone(),
                              is_server_role: false,
                            };
                            let engine_conf =
                              Arc::new(ZmtpEngineConfig::from(&*self.context_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,
                              uring_stream,
                              actor_conf,
                              engine_conf,
                              command_receiver_for_sca,
                              self.socket_logic.clone(),
                              None,
                            );
                            connect_interaction = Some(ConnectionInteractionModel::ViaSca {
                              sca_mailbox: command_sender_for_sca,
                              sca_handle_id,
                            });
                            connect_task_id = Some(sca_task_handle.id());
                          }
                          _ => tracing::error!("IPC connect: RegisterExternalByteFd failed"),
                        }
                      }
                    }
                    Err(e) => tracing::error!("IPC connect: no uring worker: {}", e),
                  }
                }
                Err(e) => tracing::error!("IPC connect: into_std failed: {}", e),
              }
            }

            // --- Standard connect path ---
            if let Some(unix_stream) = unix_stream_opt {
              {
                let socket_ref = SockRef::from(&unix_stream);
                if let Some(size) = self.context_options.sndbuf {
                  let _ = socket_ref.set_send_buffer_size(size);
                }
                if let Some(size) = self.context_options.rcvbuf {
                  let _ = socket_ref.set_recv_buffer_size(size);
                }
              }
              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.clone(),
                connected_endpoint_uri: actual_connected_uri.clone(),
                is_server_role: false,
              };
              let engine_conf = Arc::new(ZmtpEngineConfig::from(&*self.context_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,
                unix_stream,
                actor_conf,
                engine_conf,
                command_receiver_for_sca,
                self.socket_logic.clone(),
                None,
              );
              connect_interaction = Some(ConnectionInteractionModel::ViaSca {
                sca_mailbox: command_sender_for_sca,
                sca_handle_id,
              });
              connect_task_id = Some(sca_task_handle.id());
            }

            if let Some(interaction_model) = connect_interaction {
              let interaction_model = interaction_model;
              connection_outcome = Ok((interaction_model, connect_task_id, actual_connected_uri));
            } else {
              connection_outcome = Err(ZmqError::Internal(
                "IPC connect: failed to establish connection".into(),
              ));
            }
          }
          Ok(Err(e)) => { // Connect failed (not timeout related to tokio::time::timeout itself)
            connection_outcome = Err(ZmqError::from_io_endpoint(e, &endpoint_uri_original));
          }
          Err(_timeout_elapsed) => { // Timeout from tokio::time::timeout
            connection_outcome = Err(ZmqError::Timeout);
          }
        }
      }
    }

    // Process the connection_outcome
    match connection_outcome {
      Ok((interaction_model, managing_actor_task_id, actual_uri)) => {
        let cmd = Command::NewConnectionEstablished {
          endpoint_uri: actual_uri,
          target_endpoint_uri: endpoint_uri_original.clone(),
          connection_iface: None,
          interaction_model,
          managing_actor_task_id,
        };
        if self.socket_logic.mailbox().send(cmd).await.is_err() {
          tracing::error!(
            "IPC Connecter: Failed to send NewConnectionEstablished to socket mailbox for {}.",
            endpoint_uri_original
          );
          actor_drop_guard.set_error(ZmqError::Internal(
            "IPC: Socket mailbox closed during NewConnectionEstablished".into(),
          ));
        } else {
          actor_drop_guard.waive();
        }
      }
      Err(err) => {
        tracing::error!(handle = connecter_handle, uri = %endpoint_uri_original, error = %err, "IPC Connect final failure");
        if let Some(ref tx) = monitor_tx {
          let _ = tx.try_send(SocketEvent::ConnectFailed {
            endpoint: endpoint_uri_original.clone(),
            error_msg: err.to_string(),
          });
        }
        // Only publish ConnectionAttemptFailed if it wasn't an internal abort
        if !matches!(&err, ZmqError::Internal(s) if s.contains("aborted by system event")) {
          let _ = self
            .context
            .event_bus()
            .publish(SystemEvent::ConnectionAttemptFailed {
              parent_core_id: self.parent_socket_id,
              target_endpoint_uri: endpoint_uri_original.clone(),
              error: err.clone(),
            });
        }
        actor_drop_guard.set_error(err);
      }
    }

    tracing::info!(handle = connecter_handle, uri = %self.endpoint_uri, "IPC Connecter actor fully stopped.");
  }
}

fn is_fatal_ipc_accept_error(e: &io::Error) -> bool {
  matches!(
    e.kind(),
    io::ErrorKind::InvalidInput | io::ErrorKind::BrokenPipe
  )
}