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::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(Debug, Clone)]
30pub struct SocketOptions {
31 /// Read buffer size (bytes)
32 ///
33 /// Size of arena-allocated 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–5× 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
433impl Default for SocketOptions {
434 fn default() -> Self {
435 Self {
436 recv_timeout: None, // Block indefinitely
437 send_timeout: None, // Block indefinitely
438 handshake_timeout: Duration::from_secs(30),
439 linger: Some(Duration::from_secs(30)), // Wait 30s for pending messages
440 reconnect_ivl: Duration::from_millis(100),
441 reconnect_ivl_max: Duration::ZERO, // No maximum
442 connect_timeout: Duration::ZERO, // Use OS default
443 recv_hwm: 1000,
444 send_hwm: 1000,
445 immediate: false,
446 max_msg_size: None, // No limit
447 read_buffer_size: 8192, // 8KB - balanced default
448 write_buffer_size: 8192, // 8KB - balanced default
449 routing_id: None,
450 connect_routing_id: None,
451 router_mandatory: false,
452 router_handover: false,
453 probe_router: false,
454 xpub_verbose: false,
455 xpub_manual: false,
456 xpub_welcome_msg: None,
457 xsub_verbose_unsubs: false,
458 conflate: false,
459 tcp_keepalive: -1, // OS default
460 tcp_keepalive_cnt: -1, // OS default
461 tcp_keepalive_idle: -1, // OS default
462 tcp_keepalive_intvl: -1, // OS default
463 req_correlate: false,
464 req_relaxed: false,
465 rate: 100, // 100 kbps
466 recovery_ivl: Duration::from_secs(10),
467 sndbuf: 0, // OS default
468 rcvbuf: 0, // OS default
469 multicast_hops: 1, // Local network only
470 tos: 0, // Normal service
471 multicast_maxtpdu: 1500, // Standard MTU
472 ipv6: false, // IPv4 only
473 bind_to_device: None, // All interfaces
474 // Security
475 plain_server: false,
476 plain_username: None,
477 plain_password: None,
478 curve_server: false,
479 curve_publickey: None,
480 curve_secretkey: None,
481 curve_serverkey: None,
482 zap_domain: String::new(), // Global domain
483 subscriptions: Vec::new(), // No subscriptions
484 unsubscriptions: Vec::new(), // No unsubscriptions
485 max_reconnect_attempts: None, // Retry indefinitely
486 heartbeat_ivl: None,
487 heartbeat_ttl: None,
488 heartbeat_timeout: None,
489 router_raw: false,
490 stream_notify: true,
491 xpub_nodrop: false,
492 invert_matching: false,
493 write_coalescing: false,
494 write_coalesce_threshold: 65536,
495 }
496 }
497}
498
499impl SocketOptions {
500 /// Create new socket options with default values (8KB buffers).
501 #[must_use]
502 pub fn new() -> Self {
503 Self::default()
504 }
505
506 /// Create socket options optimized for small messages (< 1KB).
507 ///
508 /// Sets 4KB buffers, suitable for low-latency request-reply patterns.
509 ///
510 /// # Examples
511 ///
512 /// ```
513 /// use monocoque_core::options::SocketOptions;
514 ///
515 /// let opts = SocketOptions::small(); // 4KB buffers for REQ/REP
516 /// ```
517 #[must_use]
518 pub fn small() -> Self {
519 Self {
520 read_buffer_size: 4096,
521 write_buffer_size: 4096,
522 ..Self::default()
523 }
524 }
525
526 /// Create socket options optimized for large messages (> 8KB).
527 ///
528 /// Sets 16KB buffers, suitable for high-throughput async patterns.
529 ///
530 /// # Examples
531 ///
532 /// ```
533 /// use monocoque_core::options::SocketOptions;
534 ///
535 /// let opts = SocketOptions::large(); // 16KB buffers for DEALER/ROUTER
536 /// ```
537 #[must_use]
538 pub fn large() -> Self {
539 Self {
540 read_buffer_size: 16384,
541 write_buffer_size: 16384,
542 ..Self::default()
543 }
544 }
545
546 /// Set receive timeout.
547 ///
548 /// # Examples
549 ///
550 /// ```
551 /// use monocoque_core::options::SocketOptions;
552 /// use std::time::Duration;
553 ///
554 /// // Non-blocking receive
555 /// let opts = SocketOptions::new().with_recv_timeout(Duration::ZERO);
556 ///
557 /// // 5 second timeout
558 /// let opts = SocketOptions::new().with_recv_timeout(Duration::from_secs(5));
559 /// ```
560 pub const fn with_recv_timeout(mut self, timeout: Duration) -> Self {
561 self.recv_timeout = Some(timeout);
562 self
563 }
564
565 /// Set send timeout.
566 pub const fn with_send_timeout(mut self, timeout: Duration) -> Self {
567 self.send_timeout = Some(timeout);
568 self
569 }
570
571 /// Set handshake timeout.
572 pub const fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
573 self.handshake_timeout = timeout;
574 self
575 }
576
577 /// Set linger timeout.
578 pub const fn with_linger(mut self, linger: Option<Duration>) -> Self {
579 self.linger = linger;
580 self
581 }
582
583 /// Set reconnection interval.
584 pub const fn with_reconnect_ivl(mut self, ivl: Duration) -> Self {
585 self.reconnect_ivl = ivl;
586 self
587 }
588
589 /// Set maximum reconnection interval for exponential backoff.
590 pub const fn with_reconnect_ivl_max(mut self, max: Duration) -> Self {
591 self.reconnect_ivl_max = max;
592 self
593 }
594
595 /// Set maximum number of reconnection attempts.
596 ///
597 /// `None` retries indefinitely (default); `Some(n)` gives up after n attempts.
598 pub const fn with_max_reconnect_attempts(mut self, max: Option<u32>) -> Self {
599 self.max_reconnect_attempts = max;
600 self
601 }
602
603 /// Set connection timeout.
604 pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
605 self.connect_timeout = timeout;
606 self
607 }
608
609 /// Set heartbeat interval (`ZMQ_HEARTBEAT_IVL`).
610 pub const fn with_heartbeat_ivl(mut self, ivl: Duration) -> Self {
611 self.heartbeat_ivl = Some(ivl);
612 self
613 }
614
615 /// Set heartbeat TTL (`ZMQ_HEARTBEAT_TTL`).
616 pub const fn with_heartbeat_ttl(mut self, ttl: Duration) -> Self {
617 self.heartbeat_ttl = Some(ttl);
618 self
619 }
620
621 /// Set heartbeat timeout (`ZMQ_HEARTBEAT_TIMEOUT`).
622 pub const fn with_heartbeat_timeout(mut self, timeout: Duration) -> Self {
623 self.heartbeat_timeout = Some(timeout);
624 self
625 }
626
627 /// Enable or disable ROUTER raw mode (`ZMQ_ROUTER_RAW`).
628 pub const fn with_router_raw(mut self, raw: bool) -> Self {
629 self.router_raw = raw;
630 self
631 }
632
633 /// Enable or disable STREAM connect/disconnect notifications (`ZMQ_STREAM_NOTIFY`).
634 pub const fn with_stream_notify(mut self, notify: bool) -> Self {
635 self.stream_notify = notify;
636 self
637 }
638
639 /// Enable XPUB no-drop mode (`ZMQ_XPUB_NODROP`).
640 pub const fn with_xpub_nodrop(mut self, nodrop: bool) -> Self {
641 self.xpub_nodrop = nodrop;
642 self
643 }
644
645 /// Enable inverted topic matching (`ZMQ_INVERT_MATCHING`).
646 pub const fn with_invert_matching(mut self, invert: bool) -> Self {
647 self.invert_matching = invert;
648 self
649 }
650
651 /// Enable or disable write coalescing.
652 ///
653 /// When enabled, consecutive `send()` calls accumulate in an internal buffer
654 /// and are written to the kernel in one syscall, reducing per-message overhead
655 /// for small-message workloads. Call `flush()` after the last send in a burst.
656 pub const fn with_write_coalescing(mut self, enabled: bool) -> Self {
657 self.write_coalescing = enabled;
658 self
659 }
660
661 /// Set the byte threshold at which the coalesce buffer flushes automatically.
662 pub const fn with_write_coalesce_threshold(mut self, threshold: usize) -> Self {
663 self.write_coalesce_threshold = threshold;
664 self
665 }
666
667 /// Set receive high water mark.
668 pub const fn with_recv_hwm(mut self, hwm: usize) -> Self {
669 self.recv_hwm = hwm;
670 self
671 }
672
673 /// Set send high water mark.
674 pub const fn with_send_hwm(mut self, hwm: usize) -> Self {
675 self.send_hwm = hwm;
676 self
677 }
678
679 /// Enable or disable immediate mode.
680 pub const fn with_immediate(mut self, immediate: bool) -> Self {
681 self.immediate = immediate;
682 self
683 }
684
685 /// Set maximum message size.
686 pub const fn with_max_msg_size(mut self, size: Option<usize>) -> Self {
687 self.max_msg_size = size;
688 self
689 }
690
691 /// Set read buffer size.
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// use monocoque_core::options::SocketOptions;
697 ///
698 /// // Small buffers for low latency
699 /// let opts = SocketOptions::new().with_read_buffer_size(4096);
700 ///
701 /// // Large buffers for throughput
702 /// let opts = SocketOptions::new().with_read_buffer_size(16384);
703 /// ```
704 pub const fn with_read_buffer_size(mut self, size: usize) -> Self {
705 self.read_buffer_size = size;
706 self
707 }
708
709 /// Set write buffer size.
710 pub const fn with_write_buffer_size(mut self, size: usize) -> Self {
711 self.write_buffer_size = size;
712 self
713 }
714
715 /// Set both read and write buffer sizes (convenience method).
716 ///
717 /// # Examples
718 ///
719 /// ```
720 /// use monocoque_core::options::SocketOptions;
721 ///
722 /// // Small buffers for both
723 /// let opts = SocketOptions::new().with_buffer_sizes(4096, 4096);
724 /// ```
725 pub const fn with_buffer_sizes(mut self, read_size: usize, write_size: usize) -> Self {
726 self.read_buffer_size = read_size;
727 self.write_buffer_size = write_size;
728 self
729 }
730
731 /// Set socket routing ID / identity.
732 ///
733 /// # Examples
734 ///
735 /// ```
736 /// use monocoque_core::options::SocketOptions;
737 /// use bytes::Bytes;
738 ///
739 /// let opts = SocketOptions::new()
740 /// .with_routing_id(Bytes::from_static(b"worker-01"));
741 /// ```
742 pub fn with_routing_id(mut self, id: bytes::Bytes) -> Self {
743 self.routing_id = Some(id);
744 self
745 }
746
747 /// Set connect routing ID for the next connection.
748 ///
749 /// This option is consumed after each connect operation and must be set
750 /// again for subsequent connections.
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// use monocoque_core::options::SocketOptions;
756 /// use bytes::Bytes;
757 ///
758 /// let opts = SocketOptions::new()
759 /// .with_connect_routing_id(Bytes::from_static(b"client-001"));
760 /// ```
761 pub fn with_connect_routing_id(mut self, id: bytes::Bytes) -> Self {
762 self.connect_routing_id = Some(id);
763 self
764 }
765
766 /// Enable ROUTER mandatory mode.
767 pub const fn with_router_mandatory(mut self, enabled: bool) -> Self {
768 self.router_mandatory = enabled;
769 self
770 }
771
772 /// Enable ROUTER handover mode.
773 pub const fn with_router_handover(mut self, enabled: bool) -> Self {
774 self.router_handover = enabled;
775 self
776 }
777
778 /// Enable ROUTER probe on connect.
779 pub const fn with_probe_router(mut self, enabled: bool) -> Self {
780 self.probe_router = enabled;
781 self
782 }
783
784 /// Enable XPUB verbose mode.
785 pub const fn with_xpub_verbose(mut self, enabled: bool) -> Self {
786 self.xpub_verbose = enabled;
787 self
788 }
789
790 /// Enable XPUB manual mode.
791 pub const fn with_xpub_manual(mut self, enabled: bool) -> Self {
792 self.xpub_manual = enabled;
793 self
794 }
795
796 /// Set XPUB welcome message.
797 pub fn with_xpub_welcome_msg(mut self, msg: bytes::Bytes) -> Self {
798 self.xpub_welcome_msg = Some(msg);
799 self
800 }
801
802 /// Enable XSUB verbose unsubscribe.
803 pub const fn with_xsub_verbose_unsubs(mut self, enabled: bool) -> Self {
804 self.xsub_verbose_unsubs = enabled;
805 self
806 }
807
808 /// Enable message conflation (keep only last message).
809 pub const fn with_conflate(mut self, enabled: bool) -> Self {
810 self.conflate = enabled;
811 self
812 }
813
814 /// Set TCP keepalive mode.
815 ///
816 /// # Arguments
817 ///
818 /// * `mode` - `-1` for OS default, `0` to disable, `1` to enable
819 pub const fn with_tcp_keepalive(mut self, mode: i32) -> Self {
820 self.tcp_keepalive = mode;
821 self
822 }
823
824 /// Set TCP keepalive count (number of probes before timeout).
825 ///
826 /// # Arguments
827 ///
828 /// * `count` - `-1` for OS default, `> 0` for specific count
829 pub const fn with_tcp_keepalive_cnt(mut self, count: i32) -> Self {
830 self.tcp_keepalive_cnt = count;
831 self
832 }
833
834 /// Set TCP keepalive idle time (seconds before first probe).
835 ///
836 /// # Arguments
837 ///
838 /// * `seconds` - `-1` for OS default, `> 0` for specific idle time
839 pub const fn with_tcp_keepalive_idle(mut self, seconds: i32) -> Self {
840 self.tcp_keepalive_idle = seconds;
841 self
842 }
843
844 /// Set TCP keepalive interval (seconds between probes).
845 ///
846 /// # Arguments
847 ///
848 /// * `seconds` - `-1` for OS default, `> 0` for specific interval
849 pub const fn with_tcp_keepalive_intvl(mut self, seconds: i32) -> Self {
850 self.tcp_keepalive_intvl = seconds;
851 self
852 }
853
854 /// Enable REQ correlation mode (match replies to requests).
855 pub const fn with_req_correlate(mut self, enabled: bool) -> Self {
856 self.req_correlate = enabled;
857 self
858 }
859
860 /// Enable REQ relaxed mode (allow multiple outstanding requests).
861 pub const fn with_req_relaxed(mut self, enabled: bool) -> Self {
862 self.req_relaxed = enabled;
863 self
864 }
865
866 /// Set multicast rate (`ZMQ_RATE`).
867 pub const fn with_rate(mut self, rate: i32) -> Self {
868 self.rate = rate;
869 self
870 }
871
872 /// Set multicast recovery interval (`ZMQ_RECOVERY_IVL`).
873 pub const fn with_recovery_ivl(mut self, interval: Duration) -> Self {
874 self.recovery_ivl = interval;
875 self
876 }
877
878 /// Set OS send buffer size (`ZMQ_SNDBUF`).
879 pub const fn with_sndbuf(mut self, size: i32) -> Self {
880 self.sndbuf = size;
881 self
882 }
883
884 /// Set OS receive buffer size (`ZMQ_RCVBUF`).
885 pub const fn with_rcvbuf(mut self, size: i32) -> Self {
886 self.rcvbuf = size;
887 self
888 }
889
890 /// Set multicast TTL/hops (`ZMQ_MULTICAST_HOPS`).
891 pub const fn with_multicast_hops(mut self, hops: i32) -> Self {
892 self.multicast_hops = hops;
893 self
894 }
895
896 /// Set IP Type of Service (`ZMQ_TOS`).
897 pub const fn with_tos(mut self, tos: i32) -> Self {
898 self.tos = tos;
899 self
900 }
901
902 /// Set multicast maximum TPU (`ZMQ_MULTICAST_MAXTPDU`).
903 pub const fn with_multicast_maxtpdu(mut self, mtu: i32) -> Self {
904 self.multicast_maxtpdu = mtu;
905 self
906 }
907
908 /// Enable IPv6 support (`ZMQ_IPV6`).
909 pub const fn with_ipv6(mut self, enabled: bool) -> Self {
910 self.ipv6 = enabled;
911 self
912 }
913
914 /// Bind to specific device (`ZMQ_BINDTODEVICE`) - Linux only.
915 pub fn with_bind_to_device(mut self, device: impl Into<String>) -> Self {
916 self.bind_to_device = Some(device.into());
917 self
918 }
919
920 // --- Security Options ---
921
922 /// Enable PLAIN server mode.
923 ///
924 /// # Examples
925 ///
926 /// ```
927 /// use monocoque_core::options::SocketOptions;
928 ///
929 /// let opts = SocketOptions::new().with_plain_server(true);
930 /// ```
931 pub const fn with_plain_server(mut self, enabled: bool) -> Self {
932 self.plain_server = enabled;
933 self
934 }
935
936 /// Set PLAIN client credentials.
937 ///
938 /// # Examples
939 ///
940 /// ```
941 /// use monocoque_core::options::SocketOptions;
942 ///
943 /// let opts = SocketOptions::new()
944 /// .with_plain_credentials("admin", "secret123");
945 /// ```
946 pub fn with_plain_credentials(
947 mut self,
948 username: impl Into<String>,
949 password: impl Into<String>,
950 ) -> Self {
951 self.plain_username = Some(username.into());
952 self.plain_password = Some(password.into());
953 self
954 }
955
956 /// Enable CURVE server mode.
957 ///
958 /// # Examples
959 ///
960 /// ```
961 /// use monocoque_core::options::SocketOptions;
962 ///
963 /// let opts = SocketOptions::new().with_curve_server(true);
964 /// ```
965 pub const fn with_curve_server(mut self, enabled: bool) -> Self {
966 self.curve_server = enabled;
967 self
968 }
969
970 /// Set CURVE client keys (public + secret).
971 ///
972 /// # Examples
973 ///
974 /// ```
975 /// use monocoque_core::options::SocketOptions;
976 ///
977 /// let public = [0u8; 32]; // Replace with actual key
978 /// let secret = [0u8; 32]; // Replace with actual key
979 /// let opts = SocketOptions::new().with_curve_keypair(public, secret);
980 /// ```
981 pub const fn with_curve_keypair(mut self, publickey: [u8; 32], secretkey: [u8; 32]) -> Self {
982 self.curve_publickey = Some(publickey);
983 self.curve_secretkey = Some(secretkey);
984 self
985 }
986
987 /// Set CURVE server public key (for client).
988 ///
989 /// # Examples
990 ///
991 /// ```
992 /// use monocoque_core::options::SocketOptions;
993 ///
994 /// let server_key = [0u8; 32]; // Server's public key
995 /// let opts = SocketOptions::new().with_curve_serverkey(server_key);
996 /// ```
997 pub const fn with_curve_serverkey(mut self, serverkey: [u8; 32]) -> Self {
998 self.curve_serverkey = Some(serverkey);
999 self
1000 }
1001
1002 /// Set ZAP domain for authentication.
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// use monocoque_core::options::SocketOptions;
1008 ///
1009 /// let opts = SocketOptions::new().with_zap_domain("production");
1010 /// ```
1011 pub fn with_zap_domain(mut self, domain: impl Into<String>) -> Self {
1012 self.zap_domain = domain.into();
1013 self
1014 }
1015
1016 /// Add a subscription filter for SUB/XSUB sockets (`ZMQ_SUBSCRIBE`).
1017 ///
1018 /// SUB sockets MUST subscribe to at least one topic to receive messages.
1019 /// An empty filter (b"" or `Bytes::new()`) subscribes to all messages.
1020 ///
1021 /// # Examples
1022 ///
1023 /// ```
1024 /// use monocoque_core::options::SocketOptions;
1025 /// use bytes::Bytes;
1026 ///
1027 /// // Subscribe to all messages
1028 /// let opts = SocketOptions::new().with_subscribe(Bytes::new());
1029 ///
1030 /// // Subscribe to specific topics
1031 /// let opts = SocketOptions::new()
1032 /// .with_subscribe(Bytes::from("weather."))
1033 /// .with_subscribe(Bytes::from("stocks."));
1034 /// ```
1035 pub fn with_subscribe(mut self, filter: bytes::Bytes) -> Self {
1036 self.subscriptions.push(filter);
1037 self
1038 }
1039
1040 /// Add multiple subscription filters for SUB/XSUB sockets.
1041 ///
1042 /// Convenience method to subscribe to multiple topics at once.
1043 ///
1044 /// # Examples
1045 ///
1046 /// ```
1047 /// use monocoque_core::options::SocketOptions;
1048 /// use bytes::Bytes;
1049 ///
1050 /// let opts = SocketOptions::new()
1051 /// .with_subscriptions(vec![
1052 /// Bytes::from("weather."),
1053 /// Bytes::from("stocks."),
1054 /// ]);
1055 /// ```
1056 pub fn with_subscriptions(mut self, filters: Vec<bytes::Bytes>) -> Self {
1057 self.subscriptions.extend(filters);
1058 self
1059 }
1060
1061 /// Add an unsubscription filter for SUB/XSUB sockets (`ZMQ_UNSUBSCRIBE`).
1062 ///
1063 /// Removes a previously added subscription filter.
1064 ///
1065 /// # Examples
1066 ///
1067 /// ```
1068 /// use monocoque_core::options::SocketOptions;
1069 /// use bytes::Bytes;
1070 ///
1071 /// let opts = SocketOptions::new()
1072 /// .with_subscribe(Bytes::new()) // Subscribe to all
1073 /// .with_unsubscribe(Bytes::from("admin.")); // Except admin topics
1074 /// ```
1075 pub fn with_unsubscribe(mut self, filter: bytes::Bytes) -> Self {
1076 self.unsubscriptions.push(filter);
1077 self
1078 }
1079
1080 // --- Query Methods ---
1081
1082 /// Check if receive operation should be non-blocking.
1083 pub const fn is_recv_nonblocking(&self) -> bool {
1084 matches!(self.recv_timeout, Some(d) if d.is_zero())
1085 }
1086
1087 /// Check if send operation should be non-blocking.
1088 pub const fn is_send_nonblocking(&self) -> bool {
1089 matches!(self.send_timeout, Some(d) if d.is_zero())
1090 }
1091
1092 /// Validate routing ID for use with ROUTER sockets.
1093 ///
1094 /// ROUTER socket identities must:
1095 /// - Be 1-255 bytes long
1096 /// - Not start with null byte (0x00) which is reserved for auto-generated IDs
1097 pub fn validate_router_identity(id: &[u8]) -> std::io::Result<()> {
1098 if id.is_empty() {
1099 return Err(std::io::Error::new(
1100 std::io::ErrorKind::InvalidInput,
1101 "routing ID cannot be empty",
1102 ));
1103 }
1104
1105 if id.len() > 255 {
1106 return Err(std::io::Error::new(
1107 std::io::ErrorKind::InvalidInput,
1108 format!("routing ID cannot exceed 255 bytes (got {})", id.len()),
1109 ));
1110 }
1111
1112 if id[0] == 0x00 {
1113 return Err(std::io::Error::new(
1114 std::io::ErrorKind::InvalidInput,
1115 "routing ID cannot start with null byte (reserved for auto-generated IDs)",
1116 ));
1117 }
1118
1119 Ok(())
1120 }
1121
1122 /// Validate general routing ID (for DEALER, REQ, REP).
1123 ///
1124 /// Less strict than ROUTER identities - allows null prefix.
1125 pub fn validate_routing_id(id: &[u8]) -> std::io::Result<()> {
1126 if id.len() > 255 {
1127 return Err(std::io::Error::new(
1128 std::io::ErrorKind::InvalidInput,
1129 format!("routing ID cannot exceed 255 bytes (got {})", id.len()),
1130 ));
1131 }
1132 Ok(())
1133 }
1134
1135 /// Get the current reconnection interval with exponential backoff.
1136 ///
1137 /// Returns the interval to use, considering exponential backoff
1138 /// and the maximum interval setting.
1139 pub fn next_reconnect_ivl(&self, attempt: u32) -> Duration {
1140 if self.reconnect_ivl_max.is_zero() {
1141 // No exponential backoff, always use base interval
1142 return self.reconnect_ivl;
1143 }
1144
1145 // Calculate exponential backoff: base * 2^attempt
1146 let backoff = self
1147 .reconnect_ivl
1148 .saturating_mul(2u32.saturating_pow(attempt));
1149
1150 // Cap at maximum interval
1151 backoff.min(self.reconnect_ivl_max)
1152 }
1153}
1154
1155#[cfg(test)]
1156mod tests {
1157 use super::*;
1158
1159 #[test]
1160 fn test_default_options() {
1161 let opts = SocketOptions::default();
1162 assert!(opts.recv_timeout.is_none());
1163 assert!(opts.send_timeout.is_none());
1164 assert_eq!(opts.handshake_timeout, Duration::from_secs(30));
1165 assert_eq!(opts.reconnect_ivl, Duration::from_millis(100));
1166 assert_eq!(opts.recv_hwm, 1000);
1167 assert_eq!(opts.send_hwm, 1000);
1168 }
1169
1170 #[test]
1171 fn test_builder_pattern() {
1172 let opts = SocketOptions::new()
1173 .with_recv_timeout(Duration::from_secs(5))
1174 .with_send_timeout(Duration::from_secs(10))
1175 .with_recv_hwm(2000);
1176
1177 assert_eq!(opts.recv_timeout, Some(Duration::from_secs(5)));
1178 assert_eq!(opts.send_timeout, Some(Duration::from_secs(10)));
1179 assert_eq!(opts.recv_hwm, 2000);
1180 }
1181
1182 #[test]
1183 fn test_nonblocking_checks() {
1184 let blocking = SocketOptions::new();
1185 assert!(!blocking.is_recv_nonblocking());
1186 assert!(!blocking.is_send_nonblocking());
1187
1188 let nonblocking = SocketOptions::new()
1189 .with_recv_timeout(Duration::ZERO)
1190 .with_send_timeout(Duration::ZERO);
1191 assert!(nonblocking.is_recv_nonblocking());
1192 assert!(nonblocking.is_send_nonblocking());
1193 }
1194
1195 #[test]
1196 fn test_exponential_backoff() {
1197 let opts = SocketOptions::new()
1198 .with_reconnect_ivl(Duration::from_millis(100))
1199 .with_reconnect_ivl_max(Duration::from_secs(10));
1200
1201 // First attempt: 100ms
1202 assert_eq!(opts.next_reconnect_ivl(0), Duration::from_millis(100));
1203
1204 // Second attempt: 200ms
1205 assert_eq!(opts.next_reconnect_ivl(1), Duration::from_millis(200));
1206
1207 // Third attempt: 400ms
1208 assert_eq!(opts.next_reconnect_ivl(2), Duration::from_millis(400));
1209
1210 // Eventually caps at 10s
1211 assert_eq!(opts.next_reconnect_ivl(10), Duration::from_secs(10));
1212 }
1213
1214 #[test]
1215 fn test_no_exponential_backoff() {
1216 let opts = SocketOptions::new().with_reconnect_ivl(Duration::from_millis(100));
1217 // reconnect_ivl_max is 0 by default
1218
1219 // Always returns base interval
1220 assert_eq!(opts.next_reconnect_ivl(0), Duration::from_millis(100));
1221 assert_eq!(opts.next_reconnect_ivl(1), Duration::from_millis(100));
1222 assert_eq!(opts.next_reconnect_ivl(10), Duration::from_millis(100));
1223 }
1224
1225 #[test]
1226 fn test_routing_id_validation() {
1227 // Valid ROUTER identities
1228 assert!(SocketOptions::validate_router_identity(b"client-001").is_ok());
1229 assert!(SocketOptions::validate_router_identity(&[0x01; 255]).is_ok());
1230
1231 // Invalid: empty
1232 assert!(SocketOptions::validate_router_identity(b"").is_err());
1233
1234 // Invalid: too long
1235 assert!(SocketOptions::validate_router_identity(&[0x01; 256]).is_err());
1236
1237 // Invalid: starts with null byte
1238 assert!(SocketOptions::validate_router_identity(b"\x00client").is_err());
1239 }
1240
1241 #[test]
1242 fn test_general_routing_id_validation() {
1243 // Valid
1244 assert!(SocketOptions::validate_routing_id(b"").is_ok()); // Empty allowed
1245 assert!(SocketOptions::validate_routing_id(b"\x00client").is_ok()); // Null prefix allowed
1246 assert!(SocketOptions::validate_routing_id(&[0x00; 255]).is_ok());
1247
1248 // Invalid: too long
1249 assert!(SocketOptions::validate_routing_id(&[0x01; 256]).is_err());
1250 }
1251
1252 #[test]
1253 fn test_connect_routing_id() {
1254 let opts =
1255 SocketOptions::new().with_connect_routing_id(bytes::Bytes::from_static(b"peer-123"));
1256
1257 assert_eq!(
1258 opts.connect_routing_id,
1259 Some(bytes::Bytes::from_static(b"peer-123"))
1260 );
1261 }
1262
1263 #[test]
1264 fn test_router_options() {
1265 let opts = SocketOptions::new()
1266 .with_router_mandatory(true)
1267 .with_router_handover(true);
1268
1269 assert!(opts.router_mandatory);
1270 assert!(opts.router_handover);
1271 }
1272
1273 #[test]
1274 fn test_subscription_options() {
1275 // Test with_subscribe
1276 let opts = SocketOptions::new()
1277 .with_subscribe(bytes::Bytes::new()) // Subscribe to all
1278 .with_subscribe(bytes::Bytes::from("weather."))
1279 .with_subscribe(bytes::Bytes::from("stocks."));
1280
1281 assert_eq!(opts.subscriptions.len(), 3);
1282 assert_eq!(opts.subscriptions[0], bytes::Bytes::new());
1283 assert_eq!(opts.subscriptions[1], bytes::Bytes::from("weather."));
1284 assert_eq!(opts.subscriptions[2], bytes::Bytes::from("stocks."));
1285
1286 // Test with_subscriptions
1287 let opts2 = SocketOptions::new().with_subscriptions(vec![
1288 bytes::Bytes::from("topic1"),
1289 bytes::Bytes::from("topic2"),
1290 ]);
1291
1292 assert_eq!(opts2.subscriptions.len(), 2);
1293
1294 // Test with_unsubscribe
1295 let opts3 = opts.with_unsubscribe(bytes::Bytes::from("admin."));
1296 assert_eq!(opts3.unsubscriptions.len(), 1);
1297 assert_eq!(opts3.unsubscriptions[0], bytes::Bytes::from("admin."));
1298 }
1299}