monocoque-rs-zmtp 0.3.0

Internal ZMTP 3.1 protocol implementation for Monocoque (use 'monocoque-rs' crate for public API)
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
//! Message proxy (broker) implementation for ZeroMQ patterns.
//!
//! A proxy connects frontend and backend sockets, forwarding messages
//! bidirectionally. This enables common patterns like message brokers,
//! load balancers, and forwarders without application logic.
//!
//! # Supported Patterns
//!
//! - **PUB-SUB broker**: XSUB frontend ←→ XPUB backend
//! - **REQ-REP load balancer**: ROUTER frontend ←→ DEALER backend
//! - **PUSH-PULL forwarder**: PULL frontend ←→ PUSH backend
//!
//! # Message Flow
//!
//! ```text
//! Publishers → XSUB (frontend) → XPUB (backend) → Subscribers
//! Clients    → ROUTER (frontend) → DEALER (backend) → Workers
//! ```
//!
//! # Example: PUB-SUB Broker
//!
//! ```rust,ignore
//! use monocoque_zmtp::proxy::{proxy, ProxySocket};
//! use monocoque_zmtp::xsub::XSubSocket;
//! use monocoque_zmtp::xpub::XPubSocket;
//!
//! #[compio::main]
//! async fn main() -> std::io::Result<()> {
//!     // Publishers connect to 5555
//!     let mut frontend = XSubSocket::bind("127.0.0.1:5555").await?;
//!
//!     // Subscribers connect to 5556
//!     let mut backend = XPubSocket::bind("127.0.0.1:5556").await?;
//!
//!     // Forward messages and subscriptions bidirectionally
//!     proxy(&mut frontend, &mut backend, None).await?;
//!     Ok(())
//! }
//! ```
//!
//! # Example: REQ-REP Load Balancer
//!
//! ```rust,ignore
//! use monocoque_zmtp::proxy::{proxy, ProxySocket};
//! use monocoque_zmtp::router::RouterSocket;
//! use monocoque_zmtp::dealer::DealerSocket;
//!
//! #[compio::main]
//! async fn main() -> std::io::Result<()> {
//!     // Clients connect to 5555
//!     let mut frontend = RouterSocket::bind("127.0.0.1:5555").await?;
//!
//!     // Workers connect to 5556
//!     let mut backend = DealerSocket::bind("127.0.0.1:5556").await?;
//!
//!     // Load balance requests across workers
//!     proxy(&mut frontend, &mut backend, None).await?;
//!     Ok(())
//! }
//! ```

use bytes::Bytes;
use std::io;
use tracing::debug;

// Import socket types
use crate::dealer::DealerSocket;
use crate::pair::PairSocket;
use crate::publisher::PubSocket;
use crate::pull::PullSocket;
use crate::push::PushSocket;
use crate::rep::RepSocket;
use crate::req::ReqSocket;
use crate::router::RouterSocket;
use crate::subscriber::SubSocket;
use crate::xpub::XPubSocket;
use crate::xsub::XSubSocket;

/// Whether a forward-side send error is transient (the frame can be dropped and
/// the proxy kept running) or fatal (the peer is gone and the loop should stop).
///
/// Transient: `WouldBlock` (HWM/EAGAIN), `Interrupted`, `TimedOut`. A single
/// such hiccup must not tear down the whole proxy. Everything else (broken pipe,
/// reset, not connected) is treated as fatal and propagates, so a permanently
/// dead peer cannot spin the loop forwarding-and-dropping forever.
fn is_transient_send_error(err: &io::Error) -> bool {
    matches!(
        err.kind(),
        io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted | io::ErrorKind::TimedOut
    )
}

/// Socket types that can participate in a proxy.
///
/// Sockets must implement multipart message send/receive operations
/// to be used in a proxy pattern.
///
/// Note: This trait is designed for single-threaded async runtimes like compio
/// and does not require `Send`.
#[async_trait::async_trait(?Send)]
pub trait ProxySocket {
    /// Receive a multipart message from the socket.
    ///
    /// Returns `None` if no message is available or connection closed.
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>>;

    /// Send a multipart message to the socket.
    ///
    /// # Errors
    ///
    /// Returns an error if the send operation fails.
    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()>;

    /// Get a description of the socket for logging.
    fn socket_desc(&self) -> &'static str;
}

/// Run a bidirectional message proxy between frontend and backend sockets.
///
/// Messages are forwarded in both directions:
/// - Frontend → Backend
/// - Backend → Frontend
///
/// An optional capture socket receives copies of all messages for monitoring.
///
/// # Parameters
///
/// - `frontend`: Socket facing clients/publishers
/// - `backend`: Socket facing workers/subscribers
/// - `capture`: Optional socket to receive message copies
///
/// # Patterns
///
/// - **PUB-SUB**: `XSUB` (frontend) ←→ `XPUB` (backend)
/// - **REQ-REP**: `ROUTER` (frontend) ←→ `DEALER` (backend)
/// - **PUSH-PULL**: `PULL` (frontend) ←→ `PUSH` (backend)
///
/// # Blocking
///
/// This function runs forever, forwarding messages until an error occurs.
///
/// # Errors
///
/// Returns an error if a socket operation fails.
///
/// # Example
///
/// ```rust,ignore
/// use monocoque_zmtp::proxy::{proxy, ProxySocket};
/// use monocoque_zmtp::xsub::XSubSocket;
/// use monocoque_zmtp::xpub::XPubSocket;
///
/// #[compio::main]
/// async fn main() -> std::io::Result<()> {
///     let mut frontend = XSubSocket::bind("127.0.0.1:5555").await?;
///     let mut backend = XPubSocket::bind("127.0.0.1:5556").await?;
///
///     proxy(&mut frontend, &mut backend, None).await
/// }
/// ```
pub async fn proxy<F, B, C>(
    frontend: &mut F,
    backend: &mut B,
    mut capture: Option<&mut C>,
) -> io::Result<()>
where
    F: ProxySocket,
    B: ProxySocket,
    C: ProxySocket,
{
    use futures::{FutureExt, select};

    debug!(
        "Starting proxy: {} ←→ {}",
        frontend.socket_desc(),
        backend.socket_desc()
    );

    loop {
        // Use select! to multiplex between frontend and backend in single-threaded runtime
        select! {
            // Forward frontend → backend
            msg_result = frontend.recv_multipart().fuse() => {
                if let Some(msg) = msg_result? {
                    debug!("Proxy: {} → {}: {} frames",
                           frontend.socket_desc(),
                           backend.socket_desc(),
                           msg.len());

                    // Send copy to capture if present
                    if let Some(ref mut cap) = capture
                        && let Err(e) = cap.send_multipart(msg.clone()).await
                    {
                        debug!("Capture socket send failed: {}", e);
                    }

                    // Forward to backend. A transient error (HWM/EAGAIN) drops
                    // this frame but keeps the proxy alive; a fatal error tears
                    // the loop down.
                    if let Err(e) = backend.send_multipart(msg).await {
                        if is_transient_send_error(&e) {
                            debug!("Proxy: transient send to {}, dropping frame: {}",
                                   backend.socket_desc(), e);
                        } else {
                            return Err(e);
                        }
                    }
                }
            }

            // Forward backend → frontend
            msg_result = backend.recv_multipart().fuse() => {
                if let Some(msg) = msg_result? {
                    debug!("Proxy: {} → {}: {} frames",
                           backend.socket_desc(),
                           frontend.socket_desc(),
                           msg.len());

                    // Send copy to capture if present
                    if let Some(ref mut cap) = capture
                        && let Err(e) = cap.send_multipart(msg.clone()).await
                    {
                        debug!("Capture socket send failed: {}", e);
                    }

                    // Forward to frontend (transient errors keep the proxy up).
                    if let Err(e) = frontend.send_multipart(msg).await {
                        if is_transient_send_error(&e) {
                            debug!("Proxy: transient send to {}, dropping frame: {}",
                                   frontend.socket_desc(), e);
                        } else {
                            return Err(e);
                        }
                    }
                }
            }
        }
    }
}

/// Control commands for steerable proxy.
///
/// Sent as single-frame messages to the control socket.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProxyCommand {
    /// Pause message forwarding (buffering continues)
    Pause,
    /// Resume message forwarding
    Resume,
    /// Terminate the proxy loop
    Terminate,
    /// Report statistics  -  replies with `"messages_forwarded=N"` on the control socket.
    Statistics,
}

impl ProxyCommand {
    /// Parse command from bytes.
    pub const fn from_bytes(data: &[u8]) -> Option<Self> {
        match data {
            b"PAUSE" => Some(Self::Pause),
            b"RESUME" => Some(Self::Resume),
            b"TERMINATE" => Some(Self::Terminate),
            b"STATISTICS" => Some(Self::Statistics),
            _ => None,
        }
    }

    /// Convert command to bytes.
    pub const fn as_bytes(&self) -> &'static [u8] {
        match self {
            Self::Pause => b"PAUSE",
            Self::Resume => b"RESUME",
            Self::Terminate => b"TERMINATE",
            Self::Statistics => b"STATISTICS",
        }
    }
}

/// Run a steerable bidirectional message proxy with control socket.
///
/// Like [`proxy()`] but can be controlled via a control socket that receives commands:
/// - `PAUSE` - Stop forwarding messages (buffering continues)
/// - `RESUME` - Resume forwarding messages
/// - `TERMINATE` - Stop the proxy and return
/// - `STATISTICS` - Future: report proxy statistics
///
/// # Parameters
///
/// - `frontend`: Socket facing clients/publishers
/// - `backend`: Socket facing workers/subscribers
/// - `capture`: Optional socket to receive message copies
/// - `control`: Socket that receives control commands
///
/// # Control Socket Protocol
///
/// Send single-frame messages with command text:
/// ```text
/// PAUSE       - Pause forwarding
/// RESUME      - Resume forwarding
/// TERMINATE   - Stop proxy
/// STATISTICS  - Get stats (future)
/// ```
///
/// # Example
///
/// ```rust,ignore
/// use monocoque_zmtp::proxy::{proxy_steerable, ProxySocket, ProxyCommand};
/// use monocoque_zmtp::router::RouterSocket;
/// use monocoque_zmtp::dealer::DealerSocket;
/// use monocoque_zmtp::pair::PairSocket;
///
/// #[compio::main]
/// async fn main() -> std::io::Result<()> {
///     // Broker sockets
///     let (_, mut frontend) = RouterSocket::bind("127.0.0.1:5555").await?;
///     let (_, mut backend) = DealerSocket::bind("127.0.0.1:5556").await?;
///
///     // Control socket
///     let (_, mut control) = PairSocket::bind("127.0.0.1:5557").await?;
///
///     // Run steerable proxy
///     proxy_steerable(&mut frontend, &mut backend, None, &mut control).await?;
///     Ok(())
/// }
/// ```
///
/// Send control commands from another socket:
/// ```no_run
/// use monocoque_zmtp::pair::PairSocket;
/// use bytes::Bytes;
///
/// # async fn send_control() -> std::io::Result<()> {
/// let mut control_client = PairSocket::connect("127.0.0.1:5557").await?;
///
/// // Pause proxy
/// control_client.send(vec![Bytes::from("PAUSE")]).await?;
///
/// // Resume proxy
/// control_client.send(vec![Bytes::from("RESUME")]).await?;
///
/// // Terminate proxy
/// control_client.send(vec![Bytes::from("TERMINATE")]).await?;
/// # Ok(())
/// # }
/// ```
pub async fn proxy_steerable<F, B, C, Ctrl>(
    frontend: &mut F,
    backend: &mut B,
    mut capture: Option<&mut C>,
    control: &mut Ctrl,
) -> io::Result<()>
where
    F: ProxySocket,
    B: ProxySocket,
    C: ProxySocket,
    Ctrl: ProxySocket,
{
    use futures::{FutureExt, select};

    debug!(
        "Starting steerable proxy: {} ←→ {} (control enabled)",
        frontend.socket_desc(),
        backend.socket_desc()
    );

    let mut paused = false;
    let mut message_count = 0u64;

    loop {
        select! {
            // Check for control commands
            cmd_result = control.recv_multipart().fuse() => {
                if let Some(cmd_msg) = cmd_result?
                    && let Some(cmd_frame) = cmd_msg.first()
                    && let Some(cmd) = ProxyCommand::from_bytes(cmd_frame)
                {
                    debug!("Proxy control command: {:?}", cmd);

                    match cmd {
                        ProxyCommand::Pause => {
                            debug!("Proxy PAUSED");
                            paused = true;
                        }
                        ProxyCommand::Resume => {
                            debug!("Proxy RESUMED");
                            paused = false;
                        }
                        ProxyCommand::Terminate => {
                            debug!("Proxy TERMINATING (forwarded {} messages)", message_count);
                            return Ok(());
                        }
                        ProxyCommand::Statistics => {
                            debug!("Proxy statistics: {} messages forwarded", message_count);
                            let stats = format!("messages_forwarded={}", message_count);
                            let _ = control.send_multipart(vec![bytes::Bytes::from(stats)]).await;
                        }
                    }
                }
            }

            // Forward frontend → backend (if not paused)
            msg_result = frontend.recv_multipart().fuse() => {
                if let Some(msg) = msg_result? {
                    if paused {
                        debug!("Proxy: dropped message (paused)");
                    } else {
                        debug!("Proxy: {} → {}: {} frames",
                               frontend.socket_desc(),
                               backend.socket_desc(),
                               msg.len());

                        // Send copy to capture if present
                        if let Some(ref mut cap) = capture
                            && let Err(e) = cap.send_multipart(msg.clone()).await
                        {
                            debug!("Capture socket send failed: {}", e);
                        }

                        // Forward to backend (transient errors keep the proxy up).
                        match backend.send_multipart(msg).await {
                            Ok(()) => message_count += 1,
                            Err(e) if is_transient_send_error(&e) => {
                                debug!("Proxy: transient send to {}, dropping frame: {}",
                                       backend.socket_desc(), e);
                            }
                            Err(e) => return Err(e),
                        }
                    }
                }
            }

            // Forward backend → frontend (if not paused)
            msg_result = backend.recv_multipart().fuse() => {
                if let Some(msg) = msg_result? {
                    if paused {
                        debug!("Proxy: dropped message (paused)");
                    } else {
                        debug!("Proxy: {} → {}: {} frames",
                               backend.socket_desc(),
                               frontend.socket_desc(),
                               msg.len());

                        // Send copy to capture if present
                        if let Some(ref mut cap) = capture
                            && let Err(e) = cap.send_multipart(msg.clone()).await
                        {
                            debug!("Capture socket send failed: {}", e);
                        }

                        // Forward to frontend (transient errors keep the proxy up).
                        match frontend.send_multipart(msg).await {
                            Ok(()) => message_count += 1,
                            Err(e) if is_transient_send_error(&e) => {
                                debug!("Proxy: transient send to {}, dropping frame: {}",
                                       frontend.socket_desc(), e);
                            }
                            Err(e) => return Err(e),
                        }
                    }
                }
            }
        }
    }
}

// ===== ProxySocket Implementations =====

// XSUB socket (frontend in PUB-SUB broker)
#[async_trait::async_trait(?Send)]
impl ProxySocket for XSubSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        // In a PUB-SUB broker the proxy receives subscription events from XPUB
        // (backend) and must forward them upstream via XSUB so the publisher stops
        // or starts sending the relevant topics.
        //
        // The message format produced by XPubSocket::recv_multipart is:
        //   [b"\x01", topic]  - subscribe
        //   [b"\x00", topic]  - unsubscribe
        //
        // We reconstruct the raw ZMTP subscription frame and dispatch it.
        if msg.is_empty() {
            return Ok(());
        }

        let cmd_frame = &msg[0];
        if cmd_frame.is_empty() {
            return Ok(());
        }

        let cmd_byte = cmd_frame[0];
        // Topic is either in a second frame or appended after the command byte
        // in the same frame, depending on how the message was encoded.
        let topic: Bytes = if msg.len() >= 2 {
            msg[1].clone()
        } else if cmd_frame.len() > 1 {
            cmd_frame.slice(1..)
        } else {
            Bytes::new()
        };

        let event = if cmd_byte == 0x01 {
            monocoque_core::subscription::SubscriptionEvent::Subscribe(topic)
        } else if cmd_byte == 0x00 {
            monocoque_core::subscription::SubscriptionEvent::Unsubscribe(topic)
        } else {
            // Unknown command - ignore
            return Ok(());
        };

        self.send_subscription_event(event).await
    }

    fn socket_desc(&self) -> &'static str {
        "XSUB"
    }
}

// XPUB socket (backend in PUB-SUB broker)
#[async_trait::async_trait(?Send)]
impl ProxySocket for XPubSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        // XPUB receives subscription events, not data
        // Map subscription events to message format
        if let Some(event) = self.recv_subscription().await? {
            let msg = match event {
                monocoque_core::subscription::SubscriptionEvent::Subscribe(topic) => {
                    vec![Bytes::from(&b"\x01"[..]), topic]
                }
                monocoque_core::subscription::SubscriptionEvent::Unsubscribe(topic) => {
                    vec![Bytes::from(&b"\x00"[..]), topic]
                }
            };
            Ok(Some(msg))
        } else {
            Ok(None)
        }
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "XPUB"
    }
}

// DEALER socket (backend in REQ-REP load balancer)
#[async_trait::async_trait(?Send)]
impl ProxySocket for DealerSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "DEALER"
    }
}

// ROUTER socket (frontend in REQ-REP load balancer)
#[async_trait::async_trait(?Send)]
impl ProxySocket for RouterSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "ROUTER"
    }
}

// PULL socket (frontend in PUSH-PULL forwarder)
#[async_trait::async_trait(?Send)]
impl ProxySocket for PullSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, _msg: Vec<Bytes>) -> io::Result<()> {
        // PULL doesn't send
        Ok(())
    }

    fn socket_desc(&self) -> &'static str {
        "PULL"
    }
}

// PUSH socket (backend in PUSH-PULL forwarder)
#[async_trait::async_trait(?Send)]
impl ProxySocket for PushSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        // PUSH doesn't receive
        Ok(None)
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "PUSH"
    }
}

// REQ socket
#[async_trait::async_trait(?Send)]
impl ProxySocket for ReqSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "REQ"
    }
}

// REP socket
#[async_trait::async_trait(?Send)]
impl ProxySocket for RepSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "REP"
    }
}

// PAIR socket
#[async_trait::async_trait(?Send)]
impl ProxySocket for PairSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "PAIR"
    }
}

// PUB socket (typically not used in proxy, but included for completeness)
#[async_trait::async_trait(?Send)]
impl ProxySocket for PubSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        // PUB doesn't receive
        Ok(None)
    }

    async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
        self.send(msg).await
    }

    fn socket_desc(&self) -> &'static str {
        "PUB"
    }
}

// SUB socket (typically not used directly in proxy, XSUB is preferred)
#[async_trait::async_trait(?Send)]
impl ProxySocket for SubSocket {
    async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
        self.recv().await
    }

    async fn send_multipart(&mut self, _msg: Vec<Bytes>) -> io::Result<()> {
        // SUB doesn't send data
        Ok(())
    }

    fn socket_desc(&self) -> &'static str {
        "SUB"
    }
}

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

    #[test]
    fn transient_send_errors_are_classified() {
        // Transient: dropped frame, proxy stays up.
        for kind in [
            io::ErrorKind::WouldBlock,
            io::ErrorKind::Interrupted,
            io::ErrorKind::TimedOut,
        ] {
            assert!(is_transient_send_error(&io::Error::new(kind, "x")));
        }
        // Fatal: proxy tears down.
        for kind in [
            io::ErrorKind::BrokenPipe,
            io::ErrorKind::ConnectionReset,
            io::ErrorKind::NotConnected,
        ] {
            assert!(!is_transient_send_error(&io::Error::new(kind, "x")));
        }
    }

    /// Mock socket for testing proxy logic
    struct MockSocket {
        name: &'static str,
        recv_queue: Vec<Vec<Bytes>>,
        send_queue: Vec<Vec<Bytes>>,
    }

    impl MockSocket {
        fn new(name: &'static str) -> Self {
            Self {
                name,
                recv_queue: Vec::new(),
                send_queue: Vec::new(),
            }
        }

        fn enqueue(&mut self, msg: Vec<Bytes>) {
            self.recv_queue.push(msg);
        }
    }

    #[async_trait::async_trait(?Send)]
    impl ProxySocket for MockSocket {
        async fn recv_multipart(&mut self) -> io::Result<Option<Vec<Bytes>>> {
            Ok(self.recv_queue.pop())
        }

        async fn send_multipart(&mut self, msg: Vec<Bytes>) -> io::Result<()> {
            self.send_queue.push(msg);
            Ok(())
        }

        fn socket_desc(&self) -> &'static str {
            self.name
        }
    }

    #[test]
    fn test_mock_socket() {
        let mut sock = MockSocket::new("test");
        sock.enqueue(vec![Bytes::from("hello")]);
        assert_eq!(sock.recv_queue.len(), 1);
    }

    // TODO: Add integration tests with real sockets
    // - Test XSUB-XPUB broker pattern
    // - Test ROUTER-DEALER load balancer
    // - Test capture socket monitoring
    // - Test error handling when socket fails
}