Skip to main content

monocoque_core/
options.rs

1//! Socket configuration options
2//!
3//! This module provides configuration options for `ZeroMQ` sockets, similar to
4//! libzmq's socket options (`zmq_setsockopt/zmq_getsockopt`).
5
6use std::{fmt, time::Duration};
7
8/// Socket configuration options.
9///
10/// These options control socket behavior including timeouts, buffer sizes,
11/// and reliability features. This struct consolidates all socket configuration
12/// in one place, following the `MongoDB` Rust driver pattern.
13///
14/// # Examples
15///
16/// ```
17/// use monocoque_core::options::SocketOptions;
18/// use std::time::Duration;
19///
20/// // Simple case: use defaults
21/// let opts = SocketOptions::default();
22///
23/// // Customize timeouts and buffers
24/// let opts = SocketOptions::default()
25///     .with_recv_timeout(Duration::from_secs(5))
26///     .with_send_timeout(Duration::from_secs(5))
27///     .with_buffer_sizes(16384, 16384);  // 16KB buffers for high-throughput
28/// ```
29#[derive(Clone)]
30pub struct SocketOptions {
31    /// Read buffer size (bytes)
32    ///
33    /// Size of the read-slab buffer for receiving data.
34    /// - Default: 8192 (8KB) - balanced for most workloads
35    /// - Small (4KB): Low-latency with small messages (< 1KB)
36    /// - Large (16KB): High-throughput with large messages (> 8KB)
37    pub read_buffer_size: usize,
38
39    /// Write buffer size (bytes)
40    ///
41    /// Initial capacity of `BytesMut` buffer for sending data.
42    /// - Default: 8192 (8KB) - balanced for most workloads
43    /// - Small (4KB): Low-latency with small messages
44    /// - Large (16KB): High-throughput with large messages
45    pub write_buffer_size: usize,
46
47    /// Receive timeout (`ZMQ_RCVTIMEO`)
48    ///
49    /// Maximum time to wait for a receive operation.
50    /// - `None`: Block indefinitely (default)
51    /// - `Some(Duration::ZERO)`: Non-blocking (return immediately with EAGAIN)
52    /// - `Some(duration)`: Wait up to duration before returning EAGAIN
53    pub recv_timeout: Option<Duration>,
54
55    /// Send timeout (`ZMQ_SNDTIMEO`)
56    ///
57    /// Maximum time to wait for a send operation.
58    /// - `None`: Block indefinitely (default)
59    /// - `Some(Duration::ZERO)`: Non-blocking (return immediately with EAGAIN)
60    /// - `Some(duration)`: Wait up to duration before returning EAGAIN
61    pub send_timeout: Option<Duration>,
62
63    /// Handshake timeout (`ZMQ_HANDSHAKE_IVL`)
64    ///
65    /// Maximum time to complete ZMTP handshake after connection.
66    /// - Default: 30 seconds
67    /// - Set to `Duration::ZERO` to disable timeout
68    pub handshake_timeout: Duration,
69
70    /// Linger timeout (`ZMQ_LINGER`)
71    ///
72    /// Time to wait for pending messages to be sent before closing socket.
73    /// - `None`: Close immediately, discard pending messages
74    /// - `Some(Duration::ZERO)`: Same as None
75    /// - `Some(duration)`: Wait up to duration for messages to be sent
76    pub linger: Option<Duration>,
77
78    /// Reconnect interval (`ZMQ_RECONNECT_IVL`)
79    ///
80    /// Initial reconnection delay after connection loss.
81    /// - Default: 100ms
82    /// - Use with `reconnect_ivl_max` for exponential backoff
83    pub reconnect_ivl: Duration,
84
85    /// Maximum reconnect interval (`ZMQ_RECONNECT_IVL_MAX`)
86    ///
87    /// Maximum reconnection delay for exponential backoff.
88    /// - Default: 0 (no maximum, use `reconnect_ivl` always)
89    /// - When > 0: Doubles `reconnect_ivl` up to this value
90    pub reconnect_ivl_max: Duration,
91
92    /// Connection timeout (`ZMQ_CONNECT_TIMEOUT`)
93    ///
94    /// Maximum time to wait for TCP connection to complete.
95    /// - Default: 0 (use OS default)
96    pub connect_timeout: Duration,
97
98    /// High water mark for receiving (`ZMQ_RCVHWM`)
99    ///
100    /// Maximum number of messages to queue for receiving.
101    /// When reached, socket will block or drop messages depending on socket type.
102    /// - Default: 1000 messages
103    pub recv_hwm: usize,
104
105    /// High water mark for sending (`ZMQ_SNDHWM`)
106    ///
107    /// Maximum number of messages to queue for sending.
108    /// When reached, socket will block or drop messages depending on socket type.
109    /// - Default: 1000 messages
110    pub send_hwm: usize,
111
112    /// Enable immediate connect mode (`ZMQ_IMMEDIATE`)
113    ///
114    /// - `false` (default): Queue messages while connecting
115    /// - `true`: Report error if no connection established
116    pub immediate: bool,
117
118    /// Maximum message size (`ZMQ_MAXMSGSIZE`)
119    ///
120    /// Maximum size of a single message in bytes.
121    /// - `None`: No limit (default)
122    /// - `Some(size)`: Reject messages larger than size
123    pub max_msg_size: Option<usize>,
124
125    /// Socket identity / routing ID (`ZMQ_ROUTING_ID` / `ZMQ_IDENTITY`)
126    ///
127    /// Identity for ROUTER addressing. If None, a random UUID is generated.
128    /// - Default: None (auto-generate)
129    /// - Custom: Set for stable identity across reconnections
130    pub routing_id: Option<bytes::Bytes>,
131
132    /// Connect routing ID (`ZMQ_CONNECT_ROUTING_ID`)
133    ///
134    /// Identity to assign to the next outgoing connection.
135    /// Used by ROUTER sockets to assign a specific identity to a peer.
136    /// - Default: None (auto-generate)
137    /// - Custom: Assign explicit identity to next connection
138    /// - Consumed after each connect operation
139    pub connect_routing_id: Option<bytes::Bytes>,
140
141    /// ROUTER mandatory mode (`ZMQ_ROUTER_MANDATORY`)
142    ///
143    /// - `false` (default): Silently drop messages to unknown peers
144    /// - `true`: Return error when sending to unknown peer
145    pub router_mandatory: bool,
146
147    /// ROUTER handover mode (`ZMQ_ROUTER_HANDOVER`)
148    ///
149    /// - `false` (default): Disconnect old peer when new peer with same identity connects
150    /// - `true`: Hand over pending messages to new peer with same identity
151    pub router_handover: bool,
152
153    /// Probe ROUTER on connect (`ZMQ_PROBE_ROUTER`)
154    ///
155    /// - `false` (default): Normal operation
156    /// - `true`: Send empty message on connect to probe ROUTER identity
157    pub probe_router: bool,
158
159    /// XPUB verbose mode (`ZMQ_XPUB_VERBOSE`)
160    ///
161    /// - `false` (default): Only report new subscriptions
162    /// - `true`: Report all subscription messages (including duplicates)
163    pub xpub_verbose: bool,
164
165    /// XPUB manual mode (`ZMQ_XPUB_MANUAL`)
166    ///
167    /// - `false` (default): Automatic subscription management
168    /// - `true`: Manual subscription control via `send()`
169    pub xpub_manual: bool,
170
171    /// XPUB welcome message (`ZMQ_XPUB_WELCOME_MSG`)
172    ///
173    /// Message to send to new subscribers on connection.
174    /// Useful for last value cache (LVC) patterns.
175    pub xpub_welcome_msg: Option<bytes::Bytes>,
176
177    /// XSUB verbose unsubscribe (`ZMQ_XSUB_VERBOSE_UNSUBSCRIBE`)
178    ///
179    /// - `false` (default): Don't send explicit unsubscribe messages
180    /// - `true`: Send unsubscribe messages upstream
181    pub xsub_verbose_unsubs: bool,
182
183    /// Conflate messages (`ZMQ_CONFLATE`)
184    ///
185    /// - `false` (default): Queue all messages
186    /// - `true`: Keep only last message (overwrite queue)
187    pub conflate: bool,
188
189    /// TCP keepalive (`ZMQ_TCP_KEEPALIVE`)
190    ///
191    /// - `-1` (default): Use OS default
192    /// - `0`: Disable TCP keepalive
193    /// - `1`: Enable TCP keepalive
194    pub tcp_keepalive: i32,
195
196    /// TCP keepalive count (`ZMQ_TCP_KEEPALIVE_CNT`)
197    ///
198    /// Number of keepalive probes before considering connection dead.
199    /// - `-1` (default): Use OS default
200    /// - `> 0`: Number of probes
201    pub tcp_keepalive_cnt: i32,
202
203    /// TCP keepalive idle (`ZMQ_TCP_KEEPALIVE_IDLE`)
204    ///
205    /// Time in seconds before starting keepalive probes.
206    /// - `-1` (default): Use OS default
207    /// - `> 0`: Idle time in seconds
208    pub tcp_keepalive_idle: i32,
209
210    /// TCP keepalive interval (`ZMQ_TCP_KEEPALIVE_INTVL`)
211    ///
212    /// Time in seconds between keepalive probes.
213    /// - `-1` (default): Use OS default
214    /// - `> 0`: Interval in seconds
215    pub tcp_keepalive_intvl: i32,
216
217    /// REQ correlate mode (`ZMQ_REQ_CORRELATE`)
218    ///
219    /// Match replies to requests using message envelope.
220    /// - `false` (default): Accept any reply
221    /// - `true`: Match reply envelope to request
222    pub req_correlate: bool,
223
224    /// REQ relaxed mode (`ZMQ_REQ_RELAXED`)
225    ///
226    /// Allow multiple outstanding requests without strict alternation.
227    /// - `false` (default): Strict send-recv-send-recv pattern
228    /// - `true`: Allow send-send-recv-recv pattern
229    pub req_relaxed: bool,
230
231    /// Multicast rate in kilobits per second (`ZMQ_RATE`)
232    ///
233    /// Maximum send or receive data rate for multicast transports (PGM/EPGM).
234    /// - Default: 100 kbps
235    pub rate: i32,
236
237    /// Multicast recovery interval (`ZMQ_RECOVERY_IVL`)
238    ///
239    /// Maximum time to recover lost messages on multicast transports.
240    /// - Default: 10 seconds
241    pub recovery_ivl: Duration,
242
243    /// OS-level send buffer size (`ZMQ_SNDBUF`)
244    ///
245    /// Size of kernel send buffer. 0 = OS default.
246    /// - Default: 0 (use OS default)
247    pub sndbuf: i32,
248
249    /// OS-level receive buffer size (`ZMQ_RCVBUF`)
250    ///
251    /// Size of kernel receive buffer. 0 = OS default.
252    /// - Default: 0 (use OS default)
253    pub rcvbuf: i32,
254
255    /// Multicast TTL (`ZMQ_MULTICAST_HOPS`)
256    ///
257    /// Time-to-live for multicast packets.
258    /// - Default: 1 (local network only)
259    pub multicast_hops: i32,
260
261    /// IP Type of Service (`ZMQ_TOS`)
262    ///
263    /// Sets the `ToS` field in IP headers for `QoS`.
264    /// - Default: 0 (normal service)
265    pub tos: i32,
266
267    /// Maximum multicast transmission unit (`ZMQ_MULTICAST_MAXTPDU`)
268    ///
269    /// Maximum transport data unit for multicast.
270    /// - Default: 1500 bytes
271    pub multicast_maxtpdu: i32,
272
273    /// IPv6 support (`ZMQ_IPV6`)
274    ///
275    /// Enable IPv6 on socket.
276    /// - `false` (default): IPv4 only
277    /// - `true`: IPv6 support enabled
278    pub ipv6: bool,
279
280    /// Bind to device (`ZMQ_BINDTODEVICE`)
281    ///
282    /// Bind socket to specific network interface (Linux only).
283    /// - Default: None (bind to all interfaces)
284    pub bind_to_device: Option<String>,
285
286    // --- Security Options ---
287    /// PLAIN server mode (`ZMQ_PLAIN_SERVER`)
288    ///
289    /// Enable PLAIN authentication as server.
290    /// - `false` (default): Client mode
291    /// - `true`: Server mode (validate credentials)
292    pub plain_server: bool,
293
294    /// PLAIN username (`ZMQ_PLAIN_USERNAME`)
295    ///
296    /// Username for PLAIN authentication (client side).
297    /// - Default: None (no authentication)
298    pub plain_username: Option<String>,
299
300    /// PLAIN password (`ZMQ_PLAIN_PASSWORD`)
301    ///
302    /// Password for PLAIN authentication (client side).
303    /// - Default: None (no authentication)
304    pub plain_password: Option<String>,
305
306    /// CURVE server mode (`ZMQ_CURVE_SERVER`)
307    ///
308    /// Enable CURVE encryption as server.
309    /// - `false` (default): Client mode
310    /// - `true`: Server mode (provide server key)
311    pub curve_server: bool,
312
313    /// CURVE public key (`ZMQ_CURVE_PUBLICKEY`)
314    ///
315    /// Local public key for CURVE (32 bytes).
316    /// - Default: None (no encryption)
317    pub curve_publickey: Option<[u8; 32]>,
318
319    /// CURVE secret key (`ZMQ_CURVE_SECRETKEY`)
320    ///
321    /// Local secret key for CURVE (32 bytes).
322    /// - Default: None (no encryption)
323    pub curve_secretkey: Option<[u8; 32]>,
324
325    /// CURVE server key (`ZMQ_CURVE_SERVERKEY`)
326    ///
327    /// Server's public key for CURVE client (32 bytes).
328    /// - Default: None (no encryption)
329    /// - Client must set this to verify server identity
330    pub curve_serverkey: Option<[u8; 32]>,
331
332    /// ZAP domain (`ZMQ_ZAP_DOMAIN`)
333    ///
334    /// Security domain for ZAP authentication.
335    /// - Default: "" (global domain)
336    pub zap_domain: String,
337
338    /// Subscriptions (`ZMQ_SUBSCRIBE`)
339    ///
340    /// Subscription filters for SUB/XSUB sockets.
341    /// - Empty vec: No subscriptions (default) - won't receive any messages
342    /// - vec![b""] or vec![`Bytes::new()`]: Subscribe to all messages
343    /// - vec![b"topic1", b"topic2"]: Subscribe to specific topics
344    ///
345    /// Note: SUB sockets MUST subscribe to at least one topic to receive messages.
346    pub subscriptions: Vec<bytes::Bytes>,
347
348    /// Unsubscriptions (`ZMQ_UNSUBSCRIBE`)
349    ///
350    /// Subscription filters to remove for SUB/XSUB sockets.
351    /// Applied after subscriptions during socket configuration.
352    pub unsubscriptions: Vec<bytes::Bytes>,
353
354    /// Maximum reconnection attempts (`ZMQ_RECONNECT_STOP`)
355    ///
356    /// Maximum number of times to attempt reconnection after a disconnect.
357    /// - `None`: Retry indefinitely (default, matches libzmq behaviour)
358    /// - `Some(n)`: Give up and return `NotConnected` after n attempts
359    pub max_reconnect_attempts: Option<u32>,
360
361    /// ZMTP heartbeat interval (`ZMQ_HEARTBEAT_IVL` = 75)
362    ///
363    /// How often to send PING heartbeat commands on an otherwise idle connection.
364    /// - `None`: Disabled (default)
365    /// - `Some(dur)`: Send PING every `dur` of inactivity
366    pub heartbeat_ivl: Option<Duration>,
367
368    /// ZMTP heartbeat TTL (`ZMQ_HEARTBEAT_TTL` = 76)
369    ///
370    /// Time-to-live for the remote peer's heartbeat (sent in PING command).
371    /// The remote will disconnect if it doesn't receive a heartbeat within this interval.
372    /// - `None`: Use `heartbeat_ivl` (default)
373    /// - `Some(dur)`: Override TTL sent to peer
374    pub heartbeat_ttl: Option<Duration>,
375
376    /// ZMTP heartbeat timeout (`ZMQ_HEARTBEAT_TIMEOUT` = 77)
377    ///
378    /// How long to wait for a PONG reply before considering the connection dead.
379    /// - `None`: Use `heartbeat_ivl` (default)
380    /// - `Some(dur)`: Custom timeout (recommended: 2-5x `heartbeat_ivl`)
381    pub heartbeat_timeout: Option<Duration>,
382
383    /// ROUTER raw mode (`ZMQ_ROUTER_RAW` = 41)
384    ///
385    /// Put ROUTER socket into raw mode (no ZMTP handshake, acts like STREAM).
386    /// - `false` (default): Normal ZMTP routing
387    /// - `true`: Raw TCP bridging mode
388    pub router_raw: bool,
389
390    /// STREAM connect/disconnect notifications (`ZMQ_STREAM_NOTIFY` = 73)
391    ///
392    /// Send empty notification frames on connect and disconnect.
393    /// - `true` (default): Send notification frames
394    /// - `false`: Suppress notification frames
395    pub stream_notify: bool,
396
397    /// XPUB no-drop mode (`ZMQ_XPUB_NODROP` = 69)
398    ///
399    /// - `false` (default): Drop messages silently when HWM is reached
400    /// - `true`: Return error (`EAGAIN`) instead of dropping
401    pub xpub_nodrop: bool,
402
403    /// Invert topic matching (`ZMQ_INVERT_MATCHING` = 74)
404    ///
405    /// Invert the subscription filter logic for PUB/SUB and XPUB/XSUB.
406    /// - `false` (default): Deliver messages matching subscriptions
407    /// - `true`: Deliver messages NOT matching any subscription
408    pub invert_matching: bool,
409
410    /// Write coalescing: batch multiple `send()` calls before writing to the kernel.
411    ///
412    /// When enabled, `send()` accumulates encoded messages in an internal buffer
413    /// and only flushes to the kernel when `write_coalesce_threshold` bytes have
414    /// accumulated or when `flush()` is called explicitly.
415    ///
416    /// - `false` (default): each `send()` writes immediately (lowest latency)
417    /// - `true`: messages are batched (higher throughput for small messages)
418    ///
419    /// Always call `flush()` after the last `send()` in a burst to ensure
420    /// all buffered data reaches the peer.
421    pub write_coalescing: bool,
422
423    /// Byte threshold at which the coalesce buffer is flushed automatically.
424    ///
425    /// Only relevant when `write_coalescing` is enabled. The internal send
426    /// buffer is written to the kernel as a single syscall once it reaches
427    /// this many bytes.
428    ///
429    /// - Default: 65536 (64 KB) - one typical TCP segment on loopback
430    pub write_coalesce_threshold: usize,
431
432    /// Frame-body size at or above which the send path switches to a vectored
433    /// write (`writev`) instead of copying the body into the userspace send
434    /// buffer.
435    ///
436    /// For large frames the body copy into the coalescing buffer is the
437    /// dominant per-byte cost on the core. Above this threshold the frame header
438    /// and the refcounted `Bytes` body are written as an iovec, so the body is
439    /// handed straight to the kernel with no intermediate copy. Small frames
440    /// stay on the copy path, where a single `write` of one contiguous buffer
441    /// beats the per-iovec bookkeeping.
442    ///
443    /// Only applies in eager mode (write coalescing disabled) and when the
444    /// connection is not CURVE-encrypted (encryption must transform the body
445    /// into a fresh buffer regardless).
446    ///
447    /// - Default: 32768 (32 KB) - the measured crossover on loopback below which
448    ///   copying the body into one contiguous buffer beats a two-segment
449    ///   `writev`; tune for your hardware and message sizes
450    pub vectored_write_threshold: usize,
451}
452
453impl fmt::Debug for SocketOptions {
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        f.debug_struct("SocketOptions")
456            .field("read_buffer_size", &self.read_buffer_size())
457            .field("write_buffer_size", &self.write_buffer_size)
458            .field("recv_timeout", &self.recv_timeout)
459            .field("send_timeout", &self.send_timeout)
460            .field("handshake_timeout", &self.handshake_timeout)
461            .field("linger", &self.linger)
462            .field("reconnect_ivl", &self.reconnect_ivl)
463            .field("reconnect_ivl_max", &self.reconnect_ivl_max)
464            .field("connect_timeout", &self.connect_timeout)
465            .field("recv_hwm", &self.recv_hwm)
466            .field("send_hwm", &self.send_hwm)
467            .field("immediate", &self.immediate)
468            .field("max_msg_size", &self.max_msg_size)
469            .field("routing_id", &self.routing_id)
470            .field("connect_routing_id", &self.connect_routing_id)
471            .field("router_mandatory", &self.router_mandatory)
472            .field("router_handover", &self.router_handover)
473            .field("probe_router", &self.probe_router)
474            .field("xpub_verbose", &self.xpub_verbose)
475            .field("xpub_manual", &self.xpub_manual)
476            .field("xpub_welcome_msg", &self.xpub_welcome_msg)
477            .field("xsub_verbose_unsubs", &self.xsub_verbose_unsubs)
478            .field("conflate", &self.conflate)
479            .field("tcp_keepalive", &self.tcp_keepalive)
480            .field("tcp_keepalive_cnt", &self.tcp_keepalive_cnt)
481            .field("tcp_keepalive_idle", &self.tcp_keepalive_idle)
482            .field("tcp_keepalive_intvl", &self.tcp_keepalive_intvl)
483            .field("req_correlate", &self.req_correlate)
484            .field("req_relaxed", &self.req_relaxed)
485            .field("rate", &self.rate)
486            .field("recovery_ivl", &self.recovery_ivl)
487            .field("sndbuf", &self.sndbuf)
488            .field("rcvbuf", &self.rcvbuf)
489            .field("multicast_hops", &self.multicast_hops)
490            .field("tos", &self.tos)
491            .field("multicast_maxtpdu", &self.multicast_maxtpdu)
492            .field("ipv6", &self.ipv6)
493            .field("bind_to_device", &self.bind_to_device)
494            .field("plain_server", &self.plain_server)
495            .field("plain_username", &self.plain_username)
496            .field(
497                "plain_password",
498                &self.plain_password.as_ref().map(|_| "[REDACTED]"),
499            )
500            .field("curve_server", &self.curve_server)
501            .field("curve_publickey", &self.curve_publickey)
502            .field(
503                "curve_secretkey",
504                &self.curve_secretkey.as_ref().map(|_| "[REDACTED]"),
505            )
506            .field("curve_serverkey", &self.curve_serverkey)
507            .field("zap_domain", &self.zap_domain)
508            .field("subscriptions", &self.subscriptions)
509            .field("unsubscriptions", &self.unsubscriptions)
510            .field("max_reconnect_attempts", &self.max_reconnect_attempts)
511            .field("heartbeat_ivl", &self.heartbeat_ivl)
512            .field("heartbeat_ttl", &self.heartbeat_ttl)
513            .field("heartbeat_timeout", &self.heartbeat_timeout)
514            .field("router_raw", &self.router_raw)
515            .field("stream_notify", &self.stream_notify)
516            .field("xpub_nodrop", &self.xpub_nodrop)
517            .field("invert_matching", &self.invert_matching)
518            .field("write_coalescing", &self.write_coalescing)
519            .field("write_coalesce_threshold", &self.write_coalesce_threshold)
520            .field("vectored_write_threshold", &self.vectored_write_threshold)
521            .finish()
522    }
523}
524
525impl Default for SocketOptions {
526    fn default() -> Self {
527        Self {
528            recv_timeout: None, // Block indefinitely
529            send_timeout: None, // Block indefinitely
530            handshake_timeout: Duration::from_secs(30),
531            linger: Some(Duration::from_secs(30)), // Wait 30s for pending messages
532            reconnect_ivl: Duration::from_millis(100),
533            reconnect_ivl_max: Duration::ZERO, // No maximum
534            connect_timeout: Duration::ZERO,   // Use OS default
535            recv_hwm: 1000,
536            send_hwm: 1000,
537            immediate: false,
538            max_msg_size: None,      // No limit
539            read_buffer_size: 8192,  // 8KB - balanced default
540            write_buffer_size: 8192, // 8KB - balanced default
541            routing_id: None,
542            connect_routing_id: None,
543            router_mandatory: false,
544            router_handover: false,
545            probe_router: false,
546            xpub_verbose: false,
547            xpub_manual: false,
548            xpub_welcome_msg: None,
549            xsub_verbose_unsubs: false,
550            conflate: false,
551            tcp_keepalive: -1,       // OS default
552            tcp_keepalive_cnt: -1,   // OS default
553            tcp_keepalive_idle: -1,  // OS default
554            tcp_keepalive_intvl: -1, // OS default
555            req_correlate: false,
556            req_relaxed: false,
557            rate: 100, // 100 kbps
558            recovery_ivl: Duration::from_secs(10),
559            sndbuf: 0,               // OS default
560            rcvbuf: 0,               // OS default
561            multicast_hops: 1,       // Local network only
562            tos: 0,                  // Normal service
563            multicast_maxtpdu: 1500, // Standard MTU
564            ipv6: false,             // IPv4 only
565            bind_to_device: None,    // All interfaces
566            // Security
567            plain_server: false,
568            plain_username: None,
569            plain_password: None,
570            curve_server: false,
571            curve_publickey: None,
572            curve_secretkey: None,
573            curve_serverkey: None,
574            zap_domain: String::new(),    // Global domain
575            subscriptions: Vec::new(),    // No subscriptions
576            unsubscriptions: Vec::new(),  // No unsubscriptions
577            max_reconnect_attempts: None, // Retry indefinitely
578            heartbeat_ivl: None,
579            heartbeat_ttl: None,
580            heartbeat_timeout: None,
581            router_raw: false,
582            stream_notify: true,
583            xpub_nodrop: false,
584            invert_matching: false,
585            write_coalescing: false,
586            write_coalesce_threshold: 65536,
587            vectored_write_threshold: 32768,
588        }
589    }
590}
591
592impl SocketOptions {
593    /// Create new socket options with default values (8KB buffers).
594    #[must_use]
595    pub fn new() -> Self {
596        Self::default()
597    }
598
599    /// Create socket options optimized for small messages (< 1KB).
600    ///
601    /// Sets 4KB buffers, suitable for low-latency request-reply patterns.
602    ///
603    /// # Examples
604    ///
605    /// ```
606    /// use monocoque_core::options::SocketOptions;
607    ///
608    /// let opts = SocketOptions::small();  // 4KB buffers for REQ/REP
609    /// ```
610    #[must_use]
611    pub fn small() -> Self {
612        Self {
613            read_buffer_size: 4096,
614            write_buffer_size: 4096,
615            ..Self::default()
616        }
617    }
618
619    /// Create socket options optimized for large messages (> 8KB).
620    ///
621    /// Sets 16KB buffers, suitable for high-throughput async patterns.
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// use monocoque_core::options::SocketOptions;
627    ///
628    /// let opts = SocketOptions::large();  // 16KB buffers for DEALER/ROUTER
629    /// ```
630    #[must_use]
631    pub fn large() -> Self {
632        Self {
633            read_buffer_size: 16384,
634            write_buffer_size: 16384,
635            ..Self::default()
636        }
637    }
638
639    /// Set receive timeout.
640    ///
641    /// # Examples
642    ///
643    /// ```
644    /// use monocoque_core::options::SocketOptions;
645    /// use std::time::Duration;
646    ///
647    /// // Non-blocking receive
648    /// let opts = SocketOptions::new().with_recv_timeout(Duration::ZERO);
649    ///
650    /// // 5 second timeout
651    /// let opts = SocketOptions::new().with_recv_timeout(Duration::from_secs(5));
652    /// ```
653    pub const fn with_recv_timeout(mut self, timeout: Duration) -> Self {
654        self.recv_timeout = Some(timeout);
655        self
656    }
657
658    /// Set send timeout.
659    pub const fn with_send_timeout(mut self, timeout: Duration) -> Self {
660        self.send_timeout = Some(timeout);
661        self
662    }
663
664    /// Set handshake timeout.
665    pub const fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
666        self.handshake_timeout = timeout;
667        self
668    }
669
670    /// Set linger timeout.
671    pub const fn with_linger(mut self, linger: Option<Duration>) -> Self {
672        self.linger = linger;
673        self
674    }
675
676    /// Set reconnection interval.
677    pub const fn with_reconnect_ivl(mut self, ivl: Duration) -> Self {
678        self.reconnect_ivl = ivl;
679        self
680    }
681
682    /// Set maximum reconnection interval for exponential backoff.
683    pub const fn with_reconnect_ivl_max(mut self, max: Duration) -> Self {
684        self.reconnect_ivl_max = max;
685        self
686    }
687
688    /// Set maximum number of reconnection attempts.
689    ///
690    /// `None` retries indefinitely (default); `Some(n)` gives up after n attempts.
691    pub const fn with_max_reconnect_attempts(mut self, max: Option<u32>) -> Self {
692        self.max_reconnect_attempts = max;
693        self
694    }
695
696    /// Set connection timeout.
697    pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
698        self.connect_timeout = timeout;
699        self
700    }
701
702    /// Set heartbeat interval (`ZMQ_HEARTBEAT_IVL`).
703    pub const fn with_heartbeat_ivl(mut self, ivl: Duration) -> Self {
704        self.heartbeat_ivl = Some(ivl);
705        self
706    }
707
708    /// Set heartbeat TTL (`ZMQ_HEARTBEAT_TTL`).
709    pub const fn with_heartbeat_ttl(mut self, ttl: Duration) -> Self {
710        self.heartbeat_ttl = Some(ttl);
711        self
712    }
713
714    /// Set heartbeat timeout (`ZMQ_HEARTBEAT_TIMEOUT`).
715    pub const fn with_heartbeat_timeout(mut self, timeout: Duration) -> Self {
716        self.heartbeat_timeout = Some(timeout);
717        self
718    }
719
720    /// Enable or disable ROUTER raw mode (`ZMQ_ROUTER_RAW`).
721    pub const fn with_router_raw(mut self, raw: bool) -> Self {
722        self.router_raw = raw;
723        self
724    }
725
726    /// Enable or disable STREAM connect/disconnect notifications (`ZMQ_STREAM_NOTIFY`).
727    pub const fn with_stream_notify(mut self, notify: bool) -> Self {
728        self.stream_notify = notify;
729        self
730    }
731
732    /// Enable XPUB no-drop mode (`ZMQ_XPUB_NODROP`).
733    pub const fn with_xpub_nodrop(mut self, nodrop: bool) -> Self {
734        self.xpub_nodrop = nodrop;
735        self
736    }
737
738    /// Enable inverted topic matching (`ZMQ_INVERT_MATCHING`).
739    pub const fn with_invert_matching(mut self, invert: bool) -> Self {
740        self.invert_matching = invert;
741        self
742    }
743
744    /// Enable or disable write coalescing.
745    ///
746    /// When enabled, consecutive `send()` calls accumulate in an internal buffer
747    /// and are written to the kernel in one syscall, reducing per-message overhead
748    /// for small-message workloads.  Call `flush()` after the last send in a burst.
749    pub const fn with_write_coalescing(mut self, enabled: bool) -> Self {
750        self.write_coalescing = enabled;
751        self
752    }
753
754    /// Set the byte threshold at which the coalesce buffer flushes automatically.
755    pub const fn with_write_coalesce_threshold(mut self, threshold: usize) -> Self {
756        self.write_coalesce_threshold = threshold;
757        self
758    }
759
760    /// Set the frame-body size at or above which the eager send path uses a
761    /// vectored write (`writev`) instead of copying the body into the send
762    /// buffer. See [`SocketOptions::vectored_write_threshold`]. Set to
763    /// `usize::MAX` to disable vectored writes entirely.
764    pub const fn with_vectored_write_threshold(mut self, threshold: usize) -> Self {
765        self.vectored_write_threshold = threshold;
766        self
767    }
768
769    /// Get the configured PLAIN password, if any.
770    pub fn plain_password(&self) -> Option<&str> {
771        self.plain_password.as_deref()
772    }
773
774    /// Get the configured CURVE secret key, if any.
775    pub const fn curve_secretkey(&self) -> Option<&[u8; 32]> {
776        self.curve_secretkey.as_ref()
777    }
778
779    /// Get the configured read buffer size after applying the read-slab cap.
780    pub const fn read_buffer_size(&self) -> usize {
781        if self.read_buffer_size > crate::io::READ_SLAB_SIZE {
782            crate::io::READ_SLAB_SIZE
783        } else {
784            self.read_buffer_size
785        }
786    }
787
788    /// Set receive high water mark.
789    pub const fn with_recv_hwm(mut self, hwm: usize) -> Self {
790        self.recv_hwm = hwm;
791        self
792    }
793
794    /// Set send high water mark.
795    pub const fn with_send_hwm(mut self, hwm: usize) -> Self {
796        self.send_hwm = hwm;
797        self
798    }
799
800    /// Enable or disable immediate mode.
801    pub const fn with_immediate(mut self, immediate: bool) -> Self {
802        self.immediate = immediate;
803        self
804    }
805
806    /// Set maximum message size.
807    pub const fn with_max_msg_size(mut self, size: Option<usize>) -> Self {
808        self.max_msg_size = size;
809        self
810    }
811
812    /// Set read buffer size.
813    ///
814    /// # Examples
815    ///
816    /// ```
817    /// use monocoque_core::options::SocketOptions;
818    ///
819    /// // Small buffers for low latency
820    /// let opts = SocketOptions::new().with_read_buffer_size(4096);
821    ///
822    /// // Large buffers for throughput
823    /// let opts = SocketOptions::new().with_read_buffer_size(16384);
824    /// ```
825    pub const fn with_read_buffer_size(mut self, size: usize) -> Self {
826        self.read_buffer_size = if size > crate::io::READ_SLAB_SIZE {
827            crate::io::READ_SLAB_SIZE
828        } else {
829            size
830        };
831        self
832    }
833
834    /// Set write buffer size.
835    pub const fn with_write_buffer_size(mut self, size: usize) -> Self {
836        self.write_buffer_size = size;
837        self
838    }
839
840    /// Set both read and write buffer sizes (convenience method).
841    ///
842    /// # Examples
843    ///
844    /// ```
845    /// use monocoque_core::options::SocketOptions;
846    ///
847    /// // Small buffers for both
848    /// let opts = SocketOptions::new().with_buffer_sizes(4096, 4096);
849    /// ```
850    pub const fn with_buffer_sizes(mut self, read_size: usize, write_size: usize) -> Self {
851        self.read_buffer_size = if read_size > crate::io::READ_SLAB_SIZE {
852            crate::io::READ_SLAB_SIZE
853        } else {
854            read_size
855        };
856        self.write_buffer_size = write_size;
857        self
858    }
859
860    /// Set socket routing ID / identity.
861    ///
862    /// # Examples
863    ///
864    /// ```
865    /// use monocoque_core::options::SocketOptions;
866    /// use bytes::Bytes;
867    ///
868    /// let opts = SocketOptions::new()
869    ///     .with_routing_id(Bytes::from_static(b"worker-01"));
870    /// ```
871    pub fn with_routing_id(mut self, id: bytes::Bytes) -> Self {
872        self.routing_id = Some(id);
873        self
874    }
875
876    /// Set connect routing ID for the next connection.
877    ///
878    /// This option is consumed after each connect operation and must be set
879    /// again for subsequent connections.
880    ///
881    /// # Examples
882    ///
883    /// ```
884    /// use monocoque_core::options::SocketOptions;
885    /// use bytes::Bytes;
886    ///
887    /// let opts = SocketOptions::new()
888    ///     .with_connect_routing_id(Bytes::from_static(b"client-001"));
889    /// ```
890    pub fn with_connect_routing_id(mut self, id: bytes::Bytes) -> Self {
891        self.connect_routing_id = Some(id);
892        self
893    }
894
895    /// Enable ROUTER mandatory mode.
896    pub const fn with_router_mandatory(mut self, enabled: bool) -> Self {
897        self.router_mandatory = enabled;
898        self
899    }
900
901    /// Enable ROUTER handover mode.
902    pub const fn with_router_handover(mut self, enabled: bool) -> Self {
903        self.router_handover = enabled;
904        self
905    }
906
907    /// Enable ROUTER probe on connect.
908    pub const fn with_probe_router(mut self, enabled: bool) -> Self {
909        self.probe_router = enabled;
910        self
911    }
912
913    /// Enable XPUB verbose mode.
914    pub const fn with_xpub_verbose(mut self, enabled: bool) -> Self {
915        self.xpub_verbose = enabled;
916        self
917    }
918
919    /// Enable XPUB manual mode.
920    pub const fn with_xpub_manual(mut self, enabled: bool) -> Self {
921        self.xpub_manual = enabled;
922        self
923    }
924
925    /// Set XPUB welcome message.
926    pub fn with_xpub_welcome_msg(mut self, msg: bytes::Bytes) -> Self {
927        self.xpub_welcome_msg = Some(msg);
928        self
929    }
930
931    /// Enable XSUB verbose unsubscribe.
932    pub const fn with_xsub_verbose_unsubs(mut self, enabled: bool) -> Self {
933        self.xsub_verbose_unsubs = enabled;
934        self
935    }
936
937    /// Enable message conflation (keep only last message).
938    pub const fn with_conflate(mut self, enabled: bool) -> Self {
939        self.conflate = enabled;
940        self
941    }
942
943    /// Set TCP keepalive mode.
944    ///
945    /// # Arguments
946    ///
947    /// * `mode` - `-1` for OS default, `0` to disable, `1` to enable
948    pub const fn with_tcp_keepalive(mut self, mode: i32) -> Self {
949        self.tcp_keepalive = mode;
950        self
951    }
952
953    /// Set TCP keepalive count (number of probes before timeout).
954    ///
955    /// # Arguments
956    ///
957    /// * `count` - `-1` for OS default, `> 0` for specific count
958    pub const fn with_tcp_keepalive_cnt(mut self, count: i32) -> Self {
959        self.tcp_keepalive_cnt = count;
960        self
961    }
962
963    /// Set TCP keepalive idle time (seconds before first probe).
964    ///
965    /// # Arguments
966    ///
967    /// * `seconds` - `-1` for OS default, `> 0` for specific idle time
968    pub const fn with_tcp_keepalive_idle(mut self, seconds: i32) -> Self {
969        self.tcp_keepalive_idle = seconds;
970        self
971    }
972
973    /// Set TCP keepalive interval (seconds between probes).
974    ///
975    /// # Arguments
976    ///
977    /// * `seconds` - `-1` for OS default, `> 0` for specific interval
978    pub const fn with_tcp_keepalive_intvl(mut self, seconds: i32) -> Self {
979        self.tcp_keepalive_intvl = seconds;
980        self
981    }
982
983    /// Enable REQ correlation mode (match replies to requests).
984    pub const fn with_req_correlate(mut self, enabled: bool) -> Self {
985        self.req_correlate = enabled;
986        self
987    }
988
989    /// Enable REQ relaxed mode (allow multiple outstanding requests).
990    pub const fn with_req_relaxed(mut self, enabled: bool) -> Self {
991        self.req_relaxed = enabled;
992        self
993    }
994
995    /// Set multicast rate (`ZMQ_RATE`).
996    pub const fn with_rate(mut self, rate: i32) -> Self {
997        self.rate = rate;
998        self
999    }
1000
1001    /// Set multicast recovery interval (`ZMQ_RECOVERY_IVL`).
1002    pub const fn with_recovery_ivl(mut self, interval: Duration) -> Self {
1003        self.recovery_ivl = interval;
1004        self
1005    }
1006
1007    /// Set OS send buffer size (`ZMQ_SNDBUF`).
1008    pub const fn with_sndbuf(mut self, size: i32) -> Self {
1009        self.sndbuf = size;
1010        self
1011    }
1012
1013    /// Set OS receive buffer size (`ZMQ_RCVBUF`).
1014    pub const fn with_rcvbuf(mut self, size: i32) -> Self {
1015        self.rcvbuf = size;
1016        self
1017    }
1018
1019    /// Set multicast TTL/hops (`ZMQ_MULTICAST_HOPS`).
1020    pub const fn with_multicast_hops(mut self, hops: i32) -> Self {
1021        self.multicast_hops = hops;
1022        self
1023    }
1024
1025    /// Set IP Type of Service (`ZMQ_TOS`).
1026    pub const fn with_tos(mut self, tos: i32) -> Self {
1027        self.tos = tos;
1028        self
1029    }
1030
1031    /// Set multicast maximum TPU (`ZMQ_MULTICAST_MAXTPDU`).
1032    pub const fn with_multicast_maxtpdu(mut self, mtu: i32) -> Self {
1033        self.multicast_maxtpdu = mtu;
1034        self
1035    }
1036
1037    /// Enable IPv6 support (`ZMQ_IPV6`).
1038    pub const fn with_ipv6(mut self, enabled: bool) -> Self {
1039        self.ipv6 = enabled;
1040        self
1041    }
1042
1043    /// Bind to specific device (`ZMQ_BINDTODEVICE`) - Linux only.
1044    pub fn with_bind_to_device(mut self, device: impl Into<String>) -> Self {
1045        self.bind_to_device = Some(device.into());
1046        self
1047    }
1048
1049    // --- Security Options ---
1050
1051    /// Enable PLAIN server mode.
1052    ///
1053    /// # Examples
1054    ///
1055    /// ```
1056    /// use monocoque_core::options::SocketOptions;
1057    ///
1058    /// let opts = SocketOptions::new().with_plain_server(true);
1059    /// ```
1060    pub const fn with_plain_server(mut self, enabled: bool) -> Self {
1061        self.plain_server = enabled;
1062        self
1063    }
1064
1065    /// Set PLAIN client credentials.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// use monocoque_core::options::SocketOptions;
1071    ///
1072    /// let opts = SocketOptions::new()
1073    ///     .with_plain_credentials("admin", "secret123");
1074    /// ```
1075    pub fn with_plain_credentials(
1076        mut self,
1077        username: impl Into<String>,
1078        password: impl Into<String>,
1079    ) -> Self {
1080        self.plain_username = Some(username.into());
1081        self.plain_password = Some(password.into());
1082        self
1083    }
1084
1085    /// Enable CURVE server mode.
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// use monocoque_core::options::SocketOptions;
1091    ///
1092    /// let opts = SocketOptions::new().with_curve_server(true);
1093    /// ```
1094    pub const fn with_curve_server(mut self, enabled: bool) -> Self {
1095        self.curve_server = enabled;
1096        self
1097    }
1098
1099    /// Set CURVE client keys (public + secret).
1100    ///
1101    /// # Examples
1102    ///
1103    /// ```
1104    /// use monocoque_core::options::SocketOptions;
1105    ///
1106    /// let public = [0u8; 32];  // Replace with actual key
1107    /// let secret = [0u8; 32];  // Replace with actual key
1108    /// let opts = SocketOptions::new().with_curve_keypair(public, secret);
1109    /// ```
1110    pub const fn with_curve_keypair(mut self, publickey: [u8; 32], secretkey: [u8; 32]) -> Self {
1111        self.curve_publickey = Some(publickey);
1112        self.curve_secretkey = Some(secretkey);
1113        self
1114    }
1115
1116    /// Set CURVE server public key (for client).
1117    ///
1118    /// # Examples
1119    ///
1120    /// ```
1121    /// use monocoque_core::options::SocketOptions;
1122    ///
1123    /// let server_key = [0u8; 32];  // Server's public key
1124    /// let opts = SocketOptions::new().with_curve_serverkey(server_key);
1125    /// ```
1126    pub const fn with_curve_serverkey(mut self, serverkey: [u8; 32]) -> Self {
1127        self.curve_serverkey = Some(serverkey);
1128        self
1129    }
1130
1131    /// Set ZAP domain for authentication.
1132    ///
1133    /// # Examples
1134    ///
1135    /// ```
1136    /// use monocoque_core::options::SocketOptions;
1137    ///
1138    /// let opts = SocketOptions::new().with_zap_domain("production");
1139    /// ```
1140    pub fn with_zap_domain(mut self, domain: impl Into<String>) -> Self {
1141        self.zap_domain = domain.into();
1142        self
1143    }
1144
1145    /// Add a subscription filter for SUB/XSUB sockets (`ZMQ_SUBSCRIBE`).
1146    ///
1147    /// SUB sockets MUST subscribe to at least one topic to receive messages.
1148    /// An empty filter (b"" or `Bytes::new()`) subscribes to all messages.
1149    ///
1150    /// # Examples
1151    ///
1152    /// ```
1153    /// use monocoque_core::options::SocketOptions;
1154    /// use bytes::Bytes;
1155    ///
1156    /// // Subscribe to all messages
1157    /// let opts = SocketOptions::new().with_subscribe(Bytes::new());
1158    ///
1159    /// // Subscribe to specific topics
1160    /// let opts = SocketOptions::new()
1161    ///     .with_subscribe(Bytes::from("weather."))
1162    ///     .with_subscribe(Bytes::from("stocks."));
1163    /// ```
1164    pub fn with_subscribe(mut self, filter: bytes::Bytes) -> Self {
1165        self.subscriptions.push(filter);
1166        self
1167    }
1168
1169    /// Add multiple subscription filters for SUB/XSUB sockets.
1170    ///
1171    /// Convenience method to subscribe to multiple topics at once.
1172    ///
1173    /// # Examples
1174    ///
1175    /// ```
1176    /// use monocoque_core::options::SocketOptions;
1177    /// use bytes::Bytes;
1178    ///
1179    /// let opts = SocketOptions::new()
1180    ///     .with_subscriptions(vec![
1181    ///         Bytes::from("weather."),
1182    ///         Bytes::from("stocks."),
1183    ///     ]);
1184    /// ```
1185    pub fn with_subscriptions(mut self, filters: Vec<bytes::Bytes>) -> Self {
1186        self.subscriptions.extend(filters);
1187        self
1188    }
1189
1190    /// Add an unsubscription filter for SUB/XSUB sockets (`ZMQ_UNSUBSCRIBE`).
1191    ///
1192    /// Removes a previously added subscription filter.
1193    ///
1194    /// # Examples
1195    ///
1196    /// ```
1197    /// use monocoque_core::options::SocketOptions;
1198    /// use bytes::Bytes;
1199    ///
1200    /// let opts = SocketOptions::new()
1201    ///     .with_subscribe(Bytes::new())  // Subscribe to all
1202    ///     .with_unsubscribe(Bytes::from("admin.")); // Except admin topics
1203    /// ```
1204    pub fn with_unsubscribe(mut self, filter: bytes::Bytes) -> Self {
1205        self.unsubscriptions.push(filter);
1206        self
1207    }
1208
1209    // --- Query Methods ---
1210
1211    /// Check if receive operation should be non-blocking.
1212    pub const fn is_recv_nonblocking(&self) -> bool {
1213        matches!(self.recv_timeout, Some(d) if d.is_zero())
1214    }
1215
1216    /// Check if send operation should be non-blocking.
1217    pub const fn is_send_nonblocking(&self) -> bool {
1218        matches!(self.send_timeout, Some(d) if d.is_zero())
1219    }
1220
1221    /// Validate routing ID for use with ROUTER sockets.
1222    ///
1223    /// ROUTER socket identities must:
1224    /// - Be 1-255 bytes long
1225    /// - Not start with null byte (0x00) which is reserved for auto-generated IDs
1226    pub fn validate_router_identity(id: &[u8]) -> std::io::Result<()> {
1227        if id.is_empty() {
1228            return Err(std::io::Error::new(
1229                std::io::ErrorKind::InvalidInput,
1230                "routing ID cannot be empty",
1231            ));
1232        }
1233
1234        if id.len() > 255 {
1235            return Err(std::io::Error::new(
1236                std::io::ErrorKind::InvalidInput,
1237                format!("routing ID cannot exceed 255 bytes (got {})", id.len()),
1238            ));
1239        }
1240
1241        if id[0] == 0x00 {
1242            return Err(std::io::Error::new(
1243                std::io::ErrorKind::InvalidInput,
1244                "routing ID cannot start with null byte (reserved for auto-generated IDs)",
1245            ));
1246        }
1247
1248        Ok(())
1249    }
1250
1251    /// Validate general routing ID (for DEALER, REQ, REP).
1252    ///
1253    /// Less strict than ROUTER identities - allows null prefix.
1254    pub fn validate_routing_id(id: &[u8]) -> std::io::Result<()> {
1255        if id.len() > 255 {
1256            return Err(std::io::Error::new(
1257                std::io::ErrorKind::InvalidInput,
1258                format!("routing ID cannot exceed 255 bytes (got {})", id.len()),
1259            ));
1260        }
1261        Ok(())
1262    }
1263
1264    /// Get the current reconnection interval with exponential backoff.
1265    ///
1266    /// Returns the interval to use, considering exponential backoff
1267    /// and the maximum interval setting.
1268    pub fn next_reconnect_ivl(&self, attempt: u32) -> Duration {
1269        if self.reconnect_ivl_max.is_zero() {
1270            // No exponential backoff, always use base interval
1271            return self.reconnect_ivl;
1272        }
1273
1274        // Calculate exponential backoff: base * 2^attempt
1275        let backoff = self
1276            .reconnect_ivl
1277            .saturating_mul(2u32.saturating_pow(attempt));
1278
1279        // Cap at maximum interval
1280        backoff.min(self.reconnect_ivl_max)
1281    }
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286    use super::*;
1287
1288    #[test]
1289    fn test_default_options() {
1290        let opts = SocketOptions::default();
1291        assert!(opts.recv_timeout.is_none());
1292        assert!(opts.send_timeout.is_none());
1293        assert_eq!(opts.handshake_timeout, Duration::from_secs(30));
1294        assert_eq!(opts.reconnect_ivl, Duration::from_millis(100));
1295        assert_eq!(opts.recv_hwm, 1000);
1296        assert_eq!(opts.send_hwm, 1000);
1297    }
1298
1299    #[test]
1300    fn test_builder_pattern() {
1301        let opts = SocketOptions::new()
1302            .with_recv_timeout(Duration::from_secs(5))
1303            .with_send_timeout(Duration::from_secs(10))
1304            .with_recv_hwm(2000);
1305
1306        assert_eq!(opts.recv_timeout, Some(Duration::from_secs(5)));
1307        assert_eq!(opts.send_timeout, Some(Duration::from_secs(10)));
1308        assert_eq!(opts.recv_hwm, 2000);
1309    }
1310
1311    #[test]
1312    fn test_nonblocking_checks() {
1313        let blocking = SocketOptions::new();
1314        assert!(!blocking.is_recv_nonblocking());
1315        assert!(!blocking.is_send_nonblocking());
1316
1317        let nonblocking = SocketOptions::new()
1318            .with_recv_timeout(Duration::ZERO)
1319            .with_send_timeout(Duration::ZERO);
1320        assert!(nonblocking.is_recv_nonblocking());
1321        assert!(nonblocking.is_send_nonblocking());
1322    }
1323
1324    #[test]
1325    fn test_exponential_backoff() {
1326        let opts = SocketOptions::new()
1327            .with_reconnect_ivl(Duration::from_millis(100))
1328            .with_reconnect_ivl_max(Duration::from_secs(10));
1329
1330        // First attempt: 100ms
1331        assert_eq!(opts.next_reconnect_ivl(0), Duration::from_millis(100));
1332
1333        // Second attempt: 200ms
1334        assert_eq!(opts.next_reconnect_ivl(1), Duration::from_millis(200));
1335
1336        // Third attempt: 400ms
1337        assert_eq!(opts.next_reconnect_ivl(2), Duration::from_millis(400));
1338
1339        // Eventually caps at 10s
1340        assert_eq!(opts.next_reconnect_ivl(10), Duration::from_secs(10));
1341    }
1342
1343    #[test]
1344    fn test_no_exponential_backoff() {
1345        let opts = SocketOptions::new().with_reconnect_ivl(Duration::from_millis(100));
1346        // reconnect_ivl_max is 0 by default
1347
1348        // Always returns base interval
1349        assert_eq!(opts.next_reconnect_ivl(0), Duration::from_millis(100));
1350        assert_eq!(opts.next_reconnect_ivl(1), Duration::from_millis(100));
1351        assert_eq!(opts.next_reconnect_ivl(10), Duration::from_millis(100));
1352    }
1353
1354    #[test]
1355    fn test_routing_id_validation() {
1356        // Valid ROUTER identities
1357        assert!(SocketOptions::validate_router_identity(b"client-001").is_ok());
1358        assert!(SocketOptions::validate_router_identity(&[0x01; 255]).is_ok());
1359
1360        // Invalid: empty
1361        assert!(SocketOptions::validate_router_identity(b"").is_err());
1362
1363        // Invalid: too long
1364        assert!(SocketOptions::validate_router_identity(&[0x01; 256]).is_err());
1365
1366        // Invalid: starts with null byte
1367        assert!(SocketOptions::validate_router_identity(b"\x00client").is_err());
1368    }
1369
1370    #[test]
1371    fn test_general_routing_id_validation() {
1372        // Valid
1373        assert!(SocketOptions::validate_routing_id(b"").is_ok()); // Empty allowed
1374        assert!(SocketOptions::validate_routing_id(b"\x00client").is_ok()); // Null prefix allowed
1375        assert!(SocketOptions::validate_routing_id(&[0x00; 255]).is_ok());
1376
1377        // Invalid: too long
1378        assert!(SocketOptions::validate_routing_id(&[0x01; 256]).is_err());
1379    }
1380
1381    #[test]
1382    fn test_connect_routing_id() {
1383        let opts =
1384            SocketOptions::new().with_connect_routing_id(bytes::Bytes::from_static(b"peer-123"));
1385
1386        assert_eq!(
1387            opts.connect_routing_id,
1388            Some(bytes::Bytes::from_static(b"peer-123"))
1389        );
1390    }
1391
1392    #[test]
1393    fn debug_output_redacts_security_options() {
1394        let opts = SocketOptions::new()
1395            .with_plain_credentials("alice", "super-secret-password")
1396            .with_curve_keypair([1u8; 32], [7u8; 32]);
1397
1398        let debug = format!("{opts:?}");
1399
1400        assert!(
1401            !debug.contains("super-secret-password"),
1402            "SocketOptions Debug output exposes the PLAIN password"
1403        );
1404        assert!(
1405            !debug.contains("curve_secretkey: Some([7, 7, 7"),
1406            "SocketOptions Debug output exposes the CURVE secret key"
1407        );
1408    }
1409
1410    #[test]
1411    fn read_buffer_size_cannot_exceed_read_slab_size() {
1412        let opts = SocketOptions::new().with_read_buffer_size(crate::io::READ_SLAB_SIZE + 1);
1413
1414        assert!(
1415            opts.read_buffer_size <= crate::io::READ_SLAB_SIZE,
1416            "SocketOptions allowed a read buffer size larger than the read slab"
1417        );
1418    }
1419
1420    #[test]
1421    fn test_router_options() {
1422        let opts = SocketOptions::new()
1423            .with_router_mandatory(true)
1424            .with_router_handover(true);
1425
1426        assert!(opts.router_mandatory);
1427        assert!(opts.router_handover);
1428    }
1429
1430    #[test]
1431    fn test_subscription_options() {
1432        // Test with_subscribe
1433        let opts = SocketOptions::new()
1434            .with_subscribe(bytes::Bytes::new()) // Subscribe to all
1435            .with_subscribe(bytes::Bytes::from("weather."))
1436            .with_subscribe(bytes::Bytes::from("stocks."));
1437
1438        assert_eq!(opts.subscriptions.len(), 3);
1439        assert_eq!(opts.subscriptions[0], bytes::Bytes::new());
1440        assert_eq!(opts.subscriptions[1], bytes::Bytes::from("weather."));
1441        assert_eq!(opts.subscriptions[2], bytes::Bytes::from("stocks."));
1442
1443        // Test with_subscriptions
1444        let opts2 = SocketOptions::new().with_subscriptions(vec![
1445            bytes::Bytes::from("topic1"),
1446            bytes::Bytes::from("topic2"),
1447        ]);
1448
1449        assert_eq!(opts2.subscriptions.len(), 2);
1450
1451        // Test with_unsubscribe
1452        let opts3 = opts.with_unsubscribe(bytes::Bytes::from("admin."));
1453        assert_eq!(opts3.unsubscriptions.len(), 1);
1454        assert_eq!(opts3.unsubscriptions[0], bytes::Bytes::from("admin."));
1455    }
1456}