omq 0.29.1 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +181 -0
  3. data/README.md +3 -3
  4. data/lib/omq/constants.rb +9 -1
  5. data/lib/omq/drop_queue.rb +17 -0
  6. data/lib/omq/engine/connection_lifecycle.rb +34 -6
  7. data/lib/omq/engine/endpoints.rb +107 -0
  8. data/lib/omq/engine/heartbeat.rb +157 -15
  9. data/lib/omq/engine/monitoring.rb +95 -0
  10. data/lib/omq/engine/pump_tasks.rb +102 -0
  11. data/lib/omq/engine/reconnect.rb +10 -9
  12. data/lib/omq/engine/recv_pump.rb +18 -4
  13. data/lib/omq/engine/socket_lifecycle.rb +18 -4
  14. data/lib/omq/engine.rb +255 -304
  15. data/lib/omq/monitor_queue.rb +74 -0
  16. data/lib/omq/options.rb +78 -6
  17. data/lib/omq/routing/channel.rb +11 -5
  18. data/lib/omq/routing/client.rb +3 -1
  19. data/lib/omq/routing/closable_queues.rb +28 -0
  20. data/lib/omq/routing/conn_send_pump.rb +11 -9
  21. data/lib/omq/routing/dealer.rb +1 -0
  22. data/lib/omq/routing/dish.rb +5 -3
  23. data/lib/omq/routing/fan_out.rb +29 -21
  24. data/lib/omq/routing/gather.rb +4 -1
  25. data/lib/omq/routing/identity_routing.rb +136 -0
  26. data/lib/omq/routing/pair.rb +21 -12
  27. data/lib/omq/routing/peer.rb +30 -30
  28. data/lib/omq/routing/prefix_set.rb +239 -0
  29. data/lib/omq/routing/pub.rb +2 -1
  30. data/lib/omq/routing/pull.rb +2 -0
  31. data/lib/omq/routing/push.rb +1 -0
  32. data/lib/omq/routing/radio.rb +65 -54
  33. data/lib/omq/routing/rep.rb +4 -2
  34. data/lib/omq/routing/req.rb +8 -0
  35. data/lib/omq/routing/round_robin.rb +22 -17
  36. data/lib/omq/routing/router.rb +46 -28
  37. data/lib/omq/routing/scatter.rb +1 -0
  38. data/lib/omq/routing/server.rb +21 -25
  39. data/lib/omq/routing/sub.rb +26 -7
  40. data/lib/omq/routing/xpub.rb +25 -2
  41. data/lib/omq/routing/xsub.rb +78 -29
  42. data/lib/omq/routing.rb +52 -2
  43. data/lib/omq/socket.rb +4 -1
  44. data/lib/omq/transport/accept_loop.rb +60 -0
  45. data/lib/omq/transport/compressed_connection.rb +6 -0
  46. data/lib/omq/transport/inproc/pipe.rb +7 -0
  47. data/lib/omq/transport/inproc.rb +27 -33
  48. data/lib/omq/transport/ipc.rb +105 -7
  49. data/lib/omq/transport/tcp.rb +8 -5
  50. data/lib/omq/transport/udp.rb +92 -17
  51. data/lib/omq/version.rb +1 -1
  52. data/lib/omq.rb +2 -0
  53. metadata +11 -9
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fe841618ce840c58a2a0963628554b1db2cabe41ce95f8cf63b334d36f7948a1
4
- data.tar.gz: 330f86ac05ea02761189c383a048ac7b77422eccef097352835afe696299ebd7
3
+ metadata.gz: cbb4225bd58846cc3ec28c008f11a4da2a3d0073be24ced5d6f4e99873b9cf91
4
+ data.tar.gz: 7e11730e874f7c24e4207d661c7e4efceb117b68c31b823b4cabdb5367cbd787
5
5
  SHA512:
6
- metadata.gz: '08d804787d4d805f9bf37e7849141a9ebfe5e523c558117fe4dc4669d0007162fcb4f1254100a62c39689824308d2e7cc7dfc700b117d7e32dade2dcce996c2f'
7
- data.tar.gz: fbbd7d80028d12ad5a457acaec0a0a59436bddc1bf11177f2f39f2003597ad626ac90648b9073f92c3b366405053c7587bb1759254b1c06bcfe66fa7c947124d
6
+ metadata.gz: e27866ec7266e32cee10ed0b70a651d9466018a9900b1754b32697962b845bb6abda645d36c307133739bee41536d99ac1cbf5f7156b02a32122b86b2e484b8a
7
+ data.tar.gz: 72970544ae442b3bf35e4ad95800d3d199ec6e72d376ce5fd8f573317e7e10bda51b2154bb68777c50a52e2df8e170756e1ff07e9b1e20cbe84012937b616956
data/CHANGELOG.md CHANGED
@@ -2,6 +2,187 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.30.1] - 2026-11-27
6
+
7
+ ### Added
8
+
9
+ - `Engine.endpoint_uri(endpoint)`: the URI `#bind` and `#connect` return,
10
+ built by the transport when it has `.endpoint_uri`. The native backends use
11
+ it for the endpoints they resolve.
12
+
13
+ ### Fixed
14
+
15
+ - `#bind` and `#connect` return a URI that keeps the @ of an abstract IPC
16
+ name. They returned `ipc://name` for `ipc://@name`, because `URI.parse`
17
+ reads the @ as the end of an empty userinfo, and connecting to that dialed
18
+ a relative file path. Abstract names `URI.parse` rejects, such as ones with
19
+ spaces, no longer raise after the bind.
20
+ - `#bind` and `#connect` no longer raise for an IPC file path `URI.parse`
21
+ rejects, such as one with a space. They raised once the socket was already
22
+ bound or dialing.
23
+
24
+ ## [0.30.0] - 2026-11-26
25
+
26
+ ### Added
27
+
28
+ - Added `max_message_parts` (default 1024, like omq.rs; `nil` = unlimited). A
29
+ peer that sends a message with more frames is disconnected. `max_message_size`
30
+ is per frame, so a peer could send hundreds of thousands of empty frames in
31
+ one message and cost about 20 bytes of heap per wire byte.
32
+ - Added `max_peer_subscriptions` (default 65536, like omq.rs; `nil` =
33
+ unlimited): a peer that holds more subscription prefixes (PUB, XPUB) or groups
34
+ (RADIO) is disconnected. A peer could grow these sets without bound, and every
35
+ message is matched against them.
36
+ - Accepted libzmq's wildcard port in TCP binds: `tcp://host:*`, `tcp://*:*` and
37
+ `tcp://[::1]:*` bind any free port, like `:0`.
38
+
39
+ ### Changed
40
+
41
+ - In-process connects to an unbound endpoint retry through the regular reconnect
42
+ loop: they honor `reconnect_interval` backoff and emit `:connect_delayed` and
43
+ `:connect_retried`.
44
+ - ROUTER without `router_mandatory` drops a message whose peer is at HWM, like
45
+ libzmq, instead of blocking the sender. With `router_mandatory` it still
46
+ blocks.
47
+ - REQ accepts a new request once the peer holding the unanswered one
48
+ disconnects, so a lazy pirate retry works without recreating the socket.
49
+ libzmq needs `ZMQ_REQ_RELAXED` for this.
50
+ - PINGs advertise no TTL unless `heartbeat_ttl` is set, like libzmq and omq.rs.
51
+ The TTL used to default to `heartbeat_interval`, which made TTL-honoring peers
52
+ drop the connection whenever a PING ran late.
53
+ - `doc/DESIGN.md` is now `doc/ARCHITECTURE.md`, trimmed to the current
54
+ components, task tree and data flow.
55
+ - ROUTER, SERVER and PEER keep a dialed peer's send queue and routing id across
56
+ reconnects, like libzmq's pipes. Sends while the peer is down queue up to
57
+ `send_hwm` and go out after the redial, and replies keep reaching a peer that
58
+ reconnects without an explicit identity. With `router_mandatory`, sending to a
59
+ dialed peer that is down no longer raises. `#disconnect` drops the queue;
60
+ `#close` waits up to `linger` for the redial. Accepted peers still lose their
61
+ queue with the connection.
62
+ - `#close` no longer polls the send queues every millisecond while it lingers.
63
+ It sleeps until a send pump finishes a batch or a peer's queue goes away.
64
+
65
+ ### Fixed
66
+
67
+ - Applied `sndbuf` and `rcvbuf` to TCP and IPC connections instead of killing
68
+ the socket with `NameError` (`Socket` resolved to `OMQ::Socket`).
69
+ - Validated `reconnect_interval`. Zero, negative, non-finite and beginless
70
+ values raised later or busy-looped; an endless Range (`0.1..`) killed TCP
71
+ sockets with `ArgumentError` and now backs off without a cap.
72
+ - Treated `heartbeat_interval = 0` as disabled, like libzmq. It sent PINGs in a
73
+ tight loop and closed every connection right after the handshake.
74
+ - Iterated snapshots of peers and subscriptions in PUB, XPUB, XSUB, SUB, RADIO
75
+ and DISH. A peer joining while a send or subscribe was blocked raised
76
+ `RuntimeError` inside `#connection_added`, so the new peer never registered.
77
+ - Kept a ROUTER identity routable after a second peer took it over and the first
78
+ one left. The departing connection deleted the route that now pointed at the
79
+ new peer.
80
+ - Applied `max_message_size` to the plaintext of CURVE frames, so a message
81
+ exactly at the limit no longer drops the connection (protocol-zmtp).
82
+ - Dropped multipart messages from peers of single-frame sockets (CLIENT, SERVER,
83
+ GATHER, CHANNEL, PEER) instead of delivering them.
84
+ - Kept TCP and IPC listeners accepting after transient `accept(2)` errors. One
85
+ `EMFILE` ended the accept loop for good and left the endpoint bound but deaf.
86
+ Listeners now emit `:accept_failed`, back off on resource exhaustion and drop
87
+ clients that fail during setup.
88
+ - Stopped reconnecting after `#disconnect`. TCP, IPC and in-process dialers kept
89
+ retrying and connected once a peer appeared; connect, disconnect, connect gave
90
+ two connections. `#disconnect` now also stops a handshake in progress, and
91
+ `#close` stops reconnect loops immediately.
92
+ - Kept retrying an in-process connect after an incompatible socket bound the
93
+ endpoint first. The retry task died with an unhandled `Protocol::ZMTP::Error`,
94
+ so a compatible binder later never got the connection. `:connect_retried`
95
+ events now carry the `:error`.
96
+ - Woke fibers blocked in `#receive` (they get `nil`) or `#send` (they raise the
97
+ new `OMQ::SocketClosedError`) when the socket closes. They stayed blocked
98
+ forever. Sending, binding or connecting after `#close` raises
99
+ `SocketClosedError`, and receiving returns `nil`, like a closed
100
+ `Thread::Queue`. `#close` on a socket that never bound or connected now closes
101
+ it.
102
+ - Kept an in-process sender alive when its peer closes between two sends.
103
+ Writing into the closed peer now counts as a lost connection instead of
104
+ killing the socket, and the single-peer bypass re-queues the message for the
105
+ next peer.
106
+ - Released senders blocked on the full queue of a peer that disconnects (ROUTER,
107
+ REP, SERVER, PEER, XSUB, and PUB/XPUB with `on_mute: :block`). The queue was
108
+ dropped but never closed, so the sender hung forever; the message is now
109
+ dropped.
110
+ - Delivered in-process PAIR messages sent while there was no peer. They stayed
111
+ in the send queue because inproc PAIR links had no send pump.
112
+ - Refused a second PAIR or CHANNEL peer cleanly. The refusal raised inside the
113
+ connection setup after the peer was half registered: inproc `#connect` raised
114
+ and left ghost connections behind, and a refused TCP endpoint was never
115
+ redialed. The extra peer is now disconnected and redialed if this side dialed,
116
+ so it takes over once the first peer leaves.
117
+ - Let `#unbind` take the endpoint string passed to `#bind`.
118
+ `unbind("tcp://localhost:5555")` was a silent no-op because the listener is
119
+ stored under its resolved endpoint (`tcp://[::1]:5555`).
120
+ - Made IPC bind replace only a stale socket file. It deleted whatever was at the
121
+ path, a regular file included, even when the bind then failed, and stole the
122
+ path from a live listener. Binding over a live socket or a non-socket file now
123
+ raises `Errno::EADDRINUSE`. Closing a listener removes its socket file only if
124
+ it is still the one it created, by absolute path, so a later `chdir` or a
125
+ newer listener on the path is safe.
126
+ - Stopped a slow `#monitor` block from stalling the socket. Events went through
127
+ a 64-slot blocking queue, so accept loops, handshakes and teardown waited on
128
+ the monitor. Lifecycle events no longer block; verbose message events still
129
+ wait for the monitor to catch up.
130
+ - Dropped RADIO messages too large for one UDP datagram instead of killing the
131
+ socket with `Errno::EMSGSIZE`. The UDP send buffer now fits a maximum-size
132
+ datagram (macOS defaults to 9216 bytes), or uses `sndbuf` when set.
133
+ - Released the socket of a connection whose send was blocked on a peer that
134
+ stopped reading. A zero-linger `#close` returned, but the fd and its send pump
135
+ stayed alive forever (protocol-zmtp).
136
+ - Measured heartbeat expiry from the oldest unanswered PING, like libzmq. The
137
+ check ran right after sending a PING and compared the last receive time with
138
+ the timeout, so an idle healthy connection with the default
139
+ `heartbeat_timeout` (the interval) flapped. A zero `heartbeat_timeout` now
140
+ means the interval.
141
+ - Expired a silent peer while a send to it was blocked. The heartbeat queued its
142
+ PING behind the stuck write and never got to the expiry check, so a peer that
143
+ stopped reading stayed connected forever.
144
+ - Kept a live peer connected while the application doesn't read. With a full
145
+ receive queue the receive pump stops reading, so PONGs went unread and the
146
+ heartbeat dropped the connection, losing buffered data; it reconnected and
147
+ repeated.
148
+ - Honored the TTL a peer puts in its PINGs: the connection closes when nothing
149
+ arrives for that long, even without a local heartbeat. The TTL was parsed and
150
+ ignored.
151
+ - Counted SUB subscriptions like libzmq: subscribing to a prefix twice and
152
+ unsubscribing once keeps the subscription, and peers get the CANCEL only when
153
+ the last one goes. `#subscribe` and `#unsubscribe` no longer raise when a peer
154
+ is disconnecting.
155
+ - Recorded XSUB subscriptions and replayed them to every publisher that connects
156
+ or reconnects, like libzmq. Subscriptions sent before the first handshake were
157
+ dropped, and a restarted publisher never got them back. A cancel goes out only
158
+ when the last subscription to its prefix is gone.
159
+ - Reported an XPUB cancel for each subscription of a subscriber that
160
+ disconnects, like libzmq, so forwarders drop it upstream instead of keeping it
161
+ forever.
162
+ - Failed the handshake for a peer that sends a handshake frame over 64 KiB, more
163
+ than 256 properties, an identity over 255 bytes or an invalid as-server flag
164
+ (protocol-zmtp).
165
+ - Reserved ROUTER identities that start with a zero byte, as libzmq does: a peer
166
+ that claims one gets a generated identity, and generated identities are a zero
167
+ byte plus a 32-bit counter, so they can no longer collide with peer-chosen
168
+ ones.
169
+ - Rejected small-order CURVE keys from peers, which gave an all-zero shared
170
+ secret with the nuckle backend (protocol-zmtp).
171
+ - Yielded to other fibers while a DISH skips malformed datagrams or datagrams
172
+ for groups it didn't join. A flood on its UDP port kept the receive loop
173
+ spinning without letting anything else run.
174
+ - Stopped sending heartbeat PINGs to ZMTP 3.0 peers, which have no PING command.
175
+ - Made `udp://` work over IPv6 (`udp://[::1]:5555`) and resolve the RADIO
176
+ destination once at connect instead of on every datagram. DISH on a multicast
177
+ address now joins the group, and several DISH sockets can bind the same group
178
+ and port.
179
+ - PUB and XPUB match subscriptions with a radix trie instead of trying every
180
+ prefix. A subscriber at `max_peer_subscriptions` cost the publisher about 7 ms
181
+ per message; matching now takes well under a microsecond at any count.
182
+ - A frozen UTF-8 topic no longer raises `Encoding::CompatibilityError` in the
183
+ fan-out send pump against a non-ASCII subscription prefix, so the subscriber
184
+ gets the message. Matching compares bytes.
185
+
5
186
  ## [0.29.1] - 2026-11-26
6
187
 
7
188
  ### Fixed
data/README.md CHANGED
@@ -46,7 +46,7 @@ walkthrough of every major pattern with working code.
46
46
  connect, peers come and go. ZeroMQ reconnects automatically and queued
47
47
  messages drain when peers arrive
48
48
 
49
- For architecture internals, see [DESIGN.md](doc/DESIGN.md).
49
+ For architecture internals, see [ARCHITECTURE.md](doc/ARCHITECTURE.md).
50
50
  If you're interested in the steps taken to reach the current performance, read [PERFORMANCE.md](doc/PERFORMANCE.md).
51
51
 
52
52
  ## Install
@@ -193,8 +193,8 @@ you need to mutate it.
193
193
  > **Work-stealing, not round-robin.** Outbound load balancing uses one shared
194
194
  > send queue per socket drained by N racing pump fibers, so a slow peer can't
195
195
  > stall the pipeline. Under tight bursts on small `n`, distribution isn't
196
- > strict RR. See [DESIGN.md](doc/DESIGN.md#per-socket-hwm-not-per-connection) and
197
- > [Libzmq quirks](doc/DESIGN.md#libzmq-quirks-omq-avoids) for the reasoning.
196
+ > strict RR. See [Send queues and HWM](doc/ARCHITECTURE.md#send-queues-and-hwm) and
197
+ > [Differences from libzmq](doc/ARCHITECTURE.md#differences-from-libzmq).
198
198
 
199
199
  #### Draft (single-frame only)
200
200
 
data/lib/omq/constants.rb CHANGED
@@ -16,6 +16,14 @@ module OMQ
16
16
  end
17
17
 
18
18
 
19
+ # Raised when sending on, binding or connecting a closed socket, and
20
+ # in fibers blocked in a send when the socket closes. Receiving on a
21
+ # closed socket returns +nil+ instead, like +Thread::Queue#pop+.
22
+ #
23
+ class SocketClosedError < IOError
24
+ end
25
+
26
+
19
27
  # Lifecycle event emitted by {Socket#monitor}.
20
28
  #
21
29
  # @!attribute [r] type
@@ -43,7 +51,7 @@ module OMQ
43
51
  IO::Stream::ConnectionResetError,
44
52
  ]
45
53
 
46
- RESOLUTION_ERROR = defined?(Socket::ResolutionError) ? Socket::ResolutionError : SocketError
54
+ RESOLUTION_ERROR = defined?(::Socket::ResolutionError) ? ::Socket::ResolutionError : ::SocketError
47
55
 
48
56
  # Errors raised when a peer cannot be reached.
49
57
  CONNECTION_FAILED = [
@@ -48,6 +48,23 @@ module OMQ
48
48
  end
49
49
 
50
50
 
51
+ # Closes the queue. Blocked and later dequeues return +nil+ once it
52
+ # is empty; enqueues raise +ClosedQueueError+.
53
+ #
54
+ # @return [void]
55
+ #
56
+ def close
57
+ @queue.close
58
+ end
59
+
60
+
61
+ # @return [Boolean]
62
+ #
63
+ def closed?
64
+ @queue.closed?
65
+ end
66
+
67
+
51
68
  # @return [Boolean]
52
69
  #
53
70
  def empty?
@@ -71,12 +71,14 @@ module OMQ
71
71
  # substitute their own ZMTP-shaped connection class. Falls back to
72
72
  # {Protocol::ZMTP::Connection} when nil or when the transport
73
73
  # doesn't define +connection_class+.
74
+ # @param dialed [Boolean] true if this socket dialed +endpoint+
74
75
  #
75
- def initialize(engine, endpoint: nil, done: nil, transport: nil)
76
+ def initialize(engine, endpoint: nil, done: nil, transport: nil, dialed: false)
76
77
  @engine = engine
77
78
  @endpoint = endpoint
78
79
  @done = done
79
80
  @transport = transport
81
+ @dialed = dialed
80
82
  @state = :new
81
83
  @conn = nil
82
84
 
@@ -88,6 +90,13 @@ module OMQ
88
90
  end
89
91
 
90
92
 
93
+ # @return [Boolean] true if this socket dialed the connection
94
+ #
95
+ def dialed?
96
+ @dialed
97
+ end
98
+
99
+
91
100
  # Performs the ZMTP handshake and transitions to :ready.
92
101
  #
93
102
  # @param io [#read, #write, #close]
@@ -104,6 +113,10 @@ module OMQ
104
113
  mechanism: @engine.options.mechanism&.dup,
105
114
  max_message_size: @engine.options.max_message_size
106
115
 
116
+ if conn.respond_to?(:max_message_parts=)
117
+ conn.max_message_parts = @engine.options.max_message_parts
118
+ end
119
+
107
120
  Async::Task.current.with_timeout(handshake_timeout) do
108
121
  conn.handshake!
109
122
  end
@@ -131,6 +144,7 @@ module OMQ
131
144
  # No handshake — inproc Pipe bypasses ZMTP entirely.
132
145
  #
133
146
  # @param pipe [Transport::Inproc::Pipe]
147
+ # @return [Boolean] false if the routing strategy refused the peer
134
148
  #
135
149
  def ready_direct!(pipe)
136
150
  if pipe.is_a?(Transport::Inproc::Pipe) && pipe.peer
@@ -186,7 +200,16 @@ module OMQ
186
200
  @conn = conn
187
201
  @engine.connections[@conn] = self
188
202
  @engine.emit_monitor_event(:handshake_succeeded, endpoint: @endpoint)
189
- @engine.routing.connection_added(@conn)
203
+
204
+ begin
205
+ @engine.routing.connection_added(@conn)
206
+ rescue Routing::PeerRefusedError => error
207
+ # E.g. a second PAIR peer: drop it, and redial later if we
208
+ # dialed, so it can take over once the current peer leaves.
209
+ tear_down!(reconnect: true, reason: error)
210
+ return false
211
+ end
212
+
190
213
  @engine.peer_connected.resolve(@conn)
191
214
  transition!(:ready)
192
215
 
@@ -194,6 +217,7 @@ module OMQ
194
217
  # Waiting on an empty barrier returns immediately and would
195
218
  # tear the connection down right after registering.
196
219
  start_supervisor unless @barrier.empty?
220
+ true
197
221
  end
198
222
 
199
223
 
@@ -228,12 +252,18 @@ module OMQ
228
252
  transition!(:closed)
229
253
  @engine.connections.delete(@conn)
230
254
  @engine.routing.connection_removed(@conn) if @conn
255
+ @engine.wake_drain
231
256
  @conn&.close rescue nil
232
257
  detail = reason ? { error: reason, reason: reason.message } : nil
233
258
  @engine.emit_monitor_event(:disconnected, endpoint: @endpoint, detail: detail)
234
259
  @done&.resolve(true)
235
260
  @engine.maybe_resolve_all_peers_gone
236
- @engine.maybe_reconnect(@endpoint) if reconnect
261
+
262
+ if reconnect
263
+ @engine.maybe_reconnect(@endpoint)
264
+ elsif @dialed
265
+ @engine.drop_route(@endpoint) # no redial will deliver its queue
266
+ end
237
267
 
238
268
  # Cancel every sibling pump of this connection. The caller is
239
269
  # the supervisor task, which is NOT in the barrier — so there
@@ -248,9 +278,7 @@ module OMQ
248
278
  # (e.g. a non-ZMQ service on the same port).
249
279
  #
250
280
  def handshake_timeout
251
- ri = @engine.options.reconnect_interval
252
- ri = ri.end if ri.is_a?(Range)
253
- [ri, 0.5].max
281
+ @engine.options.attempt_timeout
254
282
  end
255
283
 
256
284
 
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OMQ
4
+ class Engine
5
+ # Endpoint parsing and transport lookup.
6
+ #
7
+ module Endpoints
8
+ # Returns the transport object (Dialer or Listener) for an endpoint.
9
+ # Used by {ConnectionLifecycle#ready!} to call +#wrap_connection+.
10
+ #
11
+ # @param endpoint [String]
12
+ # @return [Dialer, Listener, nil]
13
+ #
14
+ def transport_object_for(endpoint)
15
+ @dialers[endpoint] || @listeners[endpoint]
16
+ end
17
+
18
+
19
+ # Looks up the transport module for an endpoint URI.
20
+ #
21
+ # @param endpoint [String] endpoint URI (e.g. "tcp://...", "ruby://...")
22
+ # @return [Module] the transport module
23
+ # @raise [ArgumentError] if the scheme is not registered
24
+ #
25
+ def transport_for(endpoint)
26
+ scheme = scheme_for(endpoint)
27
+ transport = registered_transport(scheme)
28
+
29
+ unless transport
30
+ raise ArgumentError, "unsupported transport: #{endpoint}"
31
+ end
32
+
33
+ transport
34
+ end
35
+
36
+
37
+ private
38
+
39
+
40
+ # Delegates endpoint validation to the transport if it defines one.
41
+ # Called from {#connect} so a bad URI fails fast instead of landing
42
+ # in a reconnect loop.
43
+ #
44
+ # @param endpoint [String]
45
+ # @raise [ArgumentError] if the transport rejects the endpoint
46
+ #
47
+ def validate_endpoint!(endpoint, transport)
48
+ if transport.respond_to?(:validate_endpoint!)
49
+ transport.validate_endpoint!(endpoint)
50
+ end
51
+ end
52
+
53
+
54
+ # Resolves transport aliases before the endpoint is stored in
55
+ # listener, dialer, or connection maps.
56
+ #
57
+ # @param endpoint [String]
58
+ # @return [Array(String, Module)]
59
+ #
60
+ def resolve_endpoint(endpoint)
61
+ transport = transport_for(endpoint)
62
+ if transport.respond_to?(:canonical_endpoint)
63
+ endpoint = transport.canonical_endpoint(endpoint)
64
+ end
65
+
66
+ [endpoint, transport]
67
+ end
68
+
69
+
70
+ # Best-effort normalization for disconnect/unbind. Unknown schemes
71
+ # stay as-is so those calls remain no-ops instead of raising.
72
+ #
73
+ # @param endpoint [String]
74
+ # @return [String]
75
+ #
76
+ def canonical_endpoint(endpoint)
77
+ transport = registered_transport(scheme_for(endpoint))
78
+ return endpoint unless transport&.respond_to?(:canonical_endpoint)
79
+
80
+ transport.canonical_endpoint(endpoint)
81
+ end
82
+
83
+
84
+ # Looks up a registered transport. If no real inproc transport is
85
+ # registered, inproc:// falls back to the Ruby in-process transport.
86
+ #
87
+ # @param scheme [String, nil]
88
+ # @return [Module, nil]
89
+ #
90
+ def registered_transport(scheme)
91
+ self.class.transports[scheme] ||
92
+ (scheme == "inproc" ? self.class.transports["ruby"] : nil)
93
+ end
94
+
95
+
96
+ # Extracts the URI scheme from an endpoint.
97
+ #
98
+ # @param endpoint [String]
99
+ # @return [String, nil]
100
+ #
101
+ def scheme_for(endpoint)
102
+ endpoint[/\A([^:]+):\/\//, 1]
103
+ end
104
+
105
+ end
106
+ end
107
+ end
@@ -2,38 +2,180 @@
2
2
 
3
3
  module OMQ
4
4
  class Engine
5
- # Spawns a heartbeat task for a connection.
5
+ # ZMTP 3.1 heartbeat for one connection.
6
6
  #
7
- # Sends PING frames at +interval+ seconds and closes the connection
8
- # if no traffic is seen within +timeout+ seconds.
7
+ # With +heartbeat_interval+ set, sends a PING every interval. The
8
+ # connection expires when nothing arrived within +heartbeat_timeout+
9
+ # of the oldest PING still unanswered, like libzmq's
10
+ # ZMQ_HEARTBEAT_TIMEOUT: any traffic from the peer counts as an
11
+ # answer.
9
12
  #
10
- module Heartbeat
13
+ # Independently, a peer may put a TTL in its PINGs. The connection
14
+ # then expires when nothing arrives for that long, even without a
15
+ # local heartbeat (libzmq's ZMQ_HEARTBEAT_TTL on the other side).
16
+ #
17
+ class Heartbeat
18
+ # Shortest sleep between checks, so a deadline in the past doesn't
19
+ # spin the loop.
20
+ MIN_SLEEP = 0.001
21
+
22
+
11
23
  # @param parent [Async::Task, Async::Barrier] parent to spawn under
12
24
  # @param conn [Protocol::ZMTP::Connection]
13
25
  # @param options [Options]
26
+ # @return [Async::Task, nil]
14
27
  #
15
28
  def self.start(parent, conn, options)
29
+ # ZMTP 3.0 has no PING/PONG; a 3.0 peer would see a bad command.
30
+ return if conn.respond_to?(:peer_minor) && conn.peer_minor.to_i < 1
31
+
16
32
  interval = options.heartbeat_interval
17
- return unless interval
33
+ interval = nil unless interval&.positive?
34
+ timeout = options.heartbeat_timeout
35
+ timeout = interval unless timeout&.positive?
18
36
 
19
- ttl = options.heartbeat_ttl || interval
20
- timeout = options.heartbeat_timeout || interval
21
37
  conn.touch_heartbeat
38
+ heartbeat = new(conn, interval: interval, ttl: advertised_ttl(options), timeout: timeout)
39
+
40
+ if interval
41
+ heartbeat.spawn(parent)
42
+ elsif conn.respond_to?(:on_peer_ttl=)
43
+ # No local heartbeat: watch only once the peer asks for it.
44
+ conn.on_peer_ttl = -> { heartbeat.spawn(parent) }
45
+ nil
46
+ end
47
+ end
48
+
22
49
 
50
+ # TTL to put in our PINGs. Like libzmq and omq.rs, none unless
51
+ # +heartbeat_ttl+ is set: a TTL equal to the interval would make
52
+ # peers that honor it drop us whenever a PING runs late.
53
+ #
54
+ # @param options [Options]
55
+ # @return [Numeric] seconds, 0 = no TTL
56
+ #
57
+ def self.advertised_ttl(options)
58
+ options.heartbeat_ttl || 0
59
+ end
60
+
61
+
62
+ # @param conn [Protocol::ZMTP::Connection]
63
+ # @param interval [Numeric, nil] seconds between PINGs, nil = don't send
64
+ # @param ttl [Numeric] TTL advertised in each PING
65
+ # @param timeout [Numeric, nil] seconds a PING may stay unanswered
66
+ #
67
+ def initialize(conn, interval:, ttl:, timeout:)
68
+ @conn = conn
69
+ @interval = interval
70
+ @ping = Protocol::ZMTP::Codec::Command.ping(ttl: ttl)
71
+ @timeout = timeout
72
+ @pending = nil # monotonic time of the oldest unanswered PING
73
+ @sending = false # a PING is still waiting to be written
74
+ @next_ping = interval && Async::Clock.now + interval
75
+ end
76
+
77
+
78
+ # @param parent [Async::Task, Async::Barrier]
79
+ # @return [Async::Task]
80
+ #
81
+ def spawn(parent)
23
82
  parent.async(transient: true, annotation: "heartbeat") do
24
- loop do
25
- sleep interval
26
- conn.send_command(Protocol::ZMTP::Codec::Command.ping(ttl: ttl))
27
- if conn.heartbeat_expired?(timeout)
28
- conn.close
29
- break
30
- end
31
- end
83
+ run
32
84
  rescue Async::Stop, Async::Cancel
33
85
  rescue *CONNECTION_LOST
34
86
  # connection closed
35
87
  end
36
88
  end
89
+
90
+
91
+ # Runs until the connection expires (and is closed) or the task
92
+ # is stopped.
93
+ #
94
+ # @return [void]
95
+ #
96
+ def run
97
+ loop do
98
+ sleep wake_in(Async::Clock.now)
99
+
100
+ now = Async::Clock.now
101
+
102
+ if expired?(now)
103
+ @conn.close
104
+ break
105
+ end
106
+
107
+ ping(now) if @next_ping && now >= @next_ping
108
+ end
109
+ end
110
+
111
+
112
+ private
113
+
114
+
115
+ def wake_in(now)
116
+ wake = [@next_ping, ttl_deadline].compact.min
117
+ [wake - now, MIN_SLEEP].max
118
+ end
119
+
120
+
121
+ # @return [Float, nil] when the peer's TTL runs out without traffic
122
+ #
123
+ def ttl_deadline
124
+ ttl = @conn.respond_to?(:peer_ttl) && @conn.peer_ttl
125
+ last = @conn.last_received_at
126
+ return unless ttl && last
127
+
128
+ last + ttl
129
+ end
130
+
131
+
132
+ def expired?(now)
133
+ # We stopped reading (full receive queue), not the peer.
134
+ return false if @conn.respond_to?(:reading_paused?) && @conn.reading_paused?
135
+
136
+ deadline = ttl_deadline
137
+ return true if deadline && now >= deadline
138
+
139
+ pending_expired?(now)
140
+ end
141
+
142
+
143
+ def pending_expired?(now)
144
+ return false unless @pending
145
+
146
+ last = @conn.last_received_at
147
+
148
+ if last && last >= @pending
149
+ @pending = nil
150
+ return false
151
+ end
152
+
153
+ now - @pending >= @timeout
154
+ end
155
+
156
+
157
+ # Sends the PING from a child fiber of the heartbeat task: the
158
+ # write may wait behind a send that is stuck on a peer that
159
+ # stopped reading, and the expiry check must keep running
160
+ # meanwhile. (Not on the connection barrier, where a finished
161
+ # task means a dead pump.)
162
+ #
163
+ def ping(now)
164
+ @next_ping = now + @interval
165
+ @pending ||= now
166
+ return if @sending
167
+
168
+ @sending = true
169
+
170
+ Async::Task.current.async(transient: true, annotation: "heartbeat ping") do
171
+ @conn.send_command(@ping)
172
+ rescue Async::Stop, Async::Cancel, *CONNECTION_LOST
173
+ # connection closing
174
+ ensure
175
+ @sending = false
176
+ end
177
+ end
178
+
37
179
  end
38
180
  end
39
181
  end