omq 0.29.0 → 0.30.0

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 +171 -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 +239 -301
  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 +59 -21
  48. data/lib/omq/transport/ipc.rb +69 -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: 0c36b1596063dc355a2c30ad2ee00d5b5646574fbd39aaf7185334f9d2edeacf
4
- data.tar.gz: 9fec0824a06493d620b59c808f59864ea43e7f57c0e1a86ef7d0bbcb5a3c0c68
3
+ metadata.gz: c307ca5bbfb86b9b0b8641808900e6a4ebd20d850b71debd7a9bb93a481793f1
4
+ data.tar.gz: 56ba1b9a6598847a0fc409fb7689ade3a6acc551b95c893a5e32f0f0900d2783
5
5
  SHA512:
6
- metadata.gz: dcc0b56ab0ee65f8e537ecefb3599802f25053bd70ee25acc307a02e34124eafe50ca651010565ec15c3e9b5b8032da480ef458f35b94bd93e3114c444ab435a
7
- data.tar.gz: fd213cabc8e6cb194640a474ce1fd4d255a8c959b9110ced374c17c8d2a983f4ed1fd76b0bdb0b5fcb964eb7b654b58c3f6437ac039b0af6e382ebbf7b7bddf3
6
+ metadata.gz: 104203f451e68f6e7847a2c8c5b51651ae307b7442224c955f42241ebcbee38cfe1eb5fccfb04ba695c0f17ad9945e806e6e51436607c231b68592f2057c09a3
7
+ data.tar.gz: 5e1667fecd724027ec2deb01e9df31bab619a8f03d00bfda9ef579054871d060516c46192be83c5ab1aa517c7b2edd0839883a73f3eff972bda92af6ac66acc7
data/CHANGELOG.md CHANGED
@@ -2,6 +2,177 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.30.0] - 2026-11-26
6
+
7
+ ### Added
8
+
9
+ - Added `max_message_parts` (default 1024, like omq.rs; `nil` = unlimited). A
10
+ peer that sends a message with more frames is disconnected. `max_message_size`
11
+ is per frame, so a peer could send hundreds of thousands of empty frames in
12
+ one message and cost about 20 bytes of heap per wire byte.
13
+ - Added `max_peer_subscriptions` (default 65536, like omq.rs; `nil` =
14
+ unlimited): a peer that holds more subscription prefixes (PUB, XPUB) or groups
15
+ (RADIO) is disconnected. A peer could grow these sets without bound, and every
16
+ message is matched against them.
17
+ - Accepted libzmq's wildcard port in TCP binds: `tcp://host:*`, `tcp://*:*` and
18
+ `tcp://[::1]:*` bind any free port, like `:0`.
19
+
20
+ ### Changed
21
+
22
+ - In-process connects to an unbound endpoint retry through the regular reconnect
23
+ loop: they honor `reconnect_interval` backoff and emit `:connect_delayed` and
24
+ `:connect_retried`.
25
+ - ROUTER without `router_mandatory` drops a message whose peer is at HWM, like
26
+ libzmq, instead of blocking the sender. With `router_mandatory` it still
27
+ blocks.
28
+ - REQ accepts a new request once the peer holding the unanswered one
29
+ disconnects, so a lazy pirate retry works without recreating the socket.
30
+ libzmq needs `ZMQ_REQ_RELAXED` for this.
31
+ - PINGs advertise no TTL unless `heartbeat_ttl` is set, like libzmq and omq.rs.
32
+ The TTL used to default to `heartbeat_interval`, which made TTL-honoring peers
33
+ drop the connection whenever a PING ran late.
34
+ - `doc/DESIGN.md` is now `doc/ARCHITECTURE.md`, trimmed to the current
35
+ components, task tree and data flow.
36
+ - ROUTER, SERVER and PEER keep a dialed peer's send queue and routing id across
37
+ reconnects, like libzmq's pipes. Sends while the peer is down queue up to
38
+ `send_hwm` and go out after the redial, and replies keep reaching a peer that
39
+ reconnects without an explicit identity. With `router_mandatory`, sending to a
40
+ dialed peer that is down no longer raises. `#disconnect` drops the queue;
41
+ `#close` waits up to `linger` for the redial. Accepted peers still lose their
42
+ queue with the connection.
43
+ - `#close` no longer polls the send queues every millisecond while it lingers.
44
+ It sleeps until a send pump finishes a batch or a peer's queue goes away.
45
+
46
+ ### Fixed
47
+
48
+ - Applied `sndbuf` and `rcvbuf` to TCP and IPC connections instead of killing
49
+ the socket with `NameError` (`Socket` resolved to `OMQ::Socket`).
50
+ - Validated `reconnect_interval`. Zero, negative, non-finite and beginless
51
+ values raised later or busy-looped; an endless Range (`0.1..`) killed TCP
52
+ sockets with `ArgumentError` and now backs off without a cap.
53
+ - Treated `heartbeat_interval = 0` as disabled, like libzmq. It sent PINGs in a
54
+ tight loop and closed every connection right after the handshake.
55
+ - Iterated snapshots of peers and subscriptions in PUB, XPUB, XSUB, SUB, RADIO
56
+ and DISH. A peer joining while a send or subscribe was blocked raised
57
+ `RuntimeError` inside `#connection_added`, so the new peer never registered.
58
+ - Kept a ROUTER identity routable after a second peer took it over and the first
59
+ one left. The departing connection deleted the route that now pointed at the
60
+ new peer.
61
+ - Applied `max_message_size` to the plaintext of CURVE frames, so a message
62
+ exactly at the limit no longer drops the connection (protocol-zmtp).
63
+ - Dropped multipart messages from peers of single-frame sockets (CLIENT, SERVER,
64
+ GATHER, CHANNEL, PEER) instead of delivering them.
65
+ - Kept TCP and IPC listeners accepting after transient `accept(2)` errors. One
66
+ `EMFILE` ended the accept loop for good and left the endpoint bound but deaf.
67
+ Listeners now emit `:accept_failed`, back off on resource exhaustion and drop
68
+ clients that fail during setup.
69
+ - Stopped reconnecting after `#disconnect`. TCP, IPC and in-process dialers kept
70
+ retrying and connected once a peer appeared; connect, disconnect, connect gave
71
+ two connections. `#disconnect` now also stops a handshake in progress, and
72
+ `#close` stops reconnect loops immediately.
73
+ - Kept retrying an in-process connect after an incompatible socket bound the
74
+ endpoint first. The retry task died with an unhandled `Protocol::ZMTP::Error`,
75
+ so a compatible binder later never got the connection. `:connect_retried`
76
+ events now carry the `:error`.
77
+ - Woke fibers blocked in `#receive` (they get `nil`) or `#send` (they raise the
78
+ new `OMQ::SocketClosedError`) when the socket closes. They stayed blocked
79
+ forever. Sending, binding or connecting after `#close` raises
80
+ `SocketClosedError`, and receiving returns `nil`, like a closed
81
+ `Thread::Queue`. `#close` on a socket that never bound or connected now closes
82
+ it.
83
+ - Kept an in-process sender alive when its peer closes between two sends.
84
+ Writing into the closed peer now counts as a lost connection instead of
85
+ killing the socket, and the single-peer bypass re-queues the message for the
86
+ next peer.
87
+ - Released senders blocked on the full queue of a peer that disconnects (ROUTER,
88
+ REP, SERVER, PEER, XSUB, and PUB/XPUB with `on_mute: :block`). The queue was
89
+ dropped but never closed, so the sender hung forever; the message is now
90
+ dropped.
91
+ - Delivered in-process PAIR messages sent while there was no peer. They stayed
92
+ in the send queue because inproc PAIR links had no send pump.
93
+ - Refused a second PAIR or CHANNEL peer cleanly. The refusal raised inside the
94
+ connection setup after the peer was half registered: inproc `#connect` raised
95
+ and left ghost connections behind, and a refused TCP endpoint was never
96
+ redialed. The extra peer is now disconnected and redialed if this side dialed,
97
+ so it takes over once the first peer leaves.
98
+ - Let `#unbind` take the endpoint string passed to `#bind`.
99
+ `unbind("tcp://localhost:5555")` was a silent no-op because the listener is
100
+ stored under its resolved endpoint (`tcp://[::1]:5555`).
101
+ - Made IPC bind replace only a stale socket file. It deleted whatever was at the
102
+ path, a regular file included, even when the bind then failed, and stole the
103
+ path from a live listener. Binding over a live socket or a non-socket file now
104
+ raises `Errno::EADDRINUSE`. Closing a listener removes its socket file only if
105
+ it is still the one it created, by absolute path, so a later `chdir` or a
106
+ newer listener on the path is safe.
107
+ - Stopped a slow `#monitor` block from stalling the socket. Events went through
108
+ a 64-slot blocking queue, so accept loops, handshakes and teardown waited on
109
+ the monitor. Lifecycle events no longer block; verbose message events still
110
+ wait for the monitor to catch up.
111
+ - Dropped RADIO messages too large for one UDP datagram instead of killing the
112
+ socket with `Errno::EMSGSIZE`. The UDP send buffer now fits a maximum-size
113
+ datagram (macOS defaults to 9216 bytes), or uses `sndbuf` when set.
114
+ - Released the socket of a connection whose send was blocked on a peer that
115
+ stopped reading. A zero-linger `#close` returned, but the fd and its send pump
116
+ stayed alive forever (protocol-zmtp).
117
+ - Measured heartbeat expiry from the oldest unanswered PING, like libzmq. The
118
+ check ran right after sending a PING and compared the last receive time with
119
+ the timeout, so an idle healthy connection with the default
120
+ `heartbeat_timeout` (the interval) flapped. A zero `heartbeat_timeout` now
121
+ means the interval.
122
+ - Expired a silent peer while a send to it was blocked. The heartbeat queued its
123
+ PING behind the stuck write and never got to the expiry check, so a peer that
124
+ stopped reading stayed connected forever.
125
+ - Kept a live peer connected while the application doesn't read. With a full
126
+ receive queue the receive pump stops reading, so PONGs went unread and the
127
+ heartbeat dropped the connection, losing buffered data; it reconnected and
128
+ repeated.
129
+ - Honored the TTL a peer puts in its PINGs: the connection closes when nothing
130
+ arrives for that long, even without a local heartbeat. The TTL was parsed and
131
+ ignored.
132
+ - Counted SUB subscriptions like libzmq: subscribing to a prefix twice and
133
+ unsubscribing once keeps the subscription, and peers get the CANCEL only when
134
+ the last one goes. `#subscribe` and `#unsubscribe` no longer raise when a peer
135
+ is disconnecting.
136
+ - Recorded XSUB subscriptions and replayed them to every publisher that connects
137
+ or reconnects, like libzmq. Subscriptions sent before the first handshake were
138
+ dropped, and a restarted publisher never got them back. A cancel goes out only
139
+ when the last subscription to its prefix is gone.
140
+ - Reported an XPUB cancel for each subscription of a subscriber that
141
+ disconnects, like libzmq, so forwarders drop it upstream instead of keeping it
142
+ forever.
143
+ - Failed the handshake for a peer that sends a handshake frame over 64 KiB, more
144
+ than 256 properties, an identity over 255 bytes or an invalid as-server flag
145
+ (protocol-zmtp).
146
+ - Reserved ROUTER identities that start with a zero byte, as libzmq does: a peer
147
+ that claims one gets a generated identity, and generated identities are a zero
148
+ byte plus a 32-bit counter, so they can no longer collide with peer-chosen
149
+ ones.
150
+ - Rejected small-order CURVE keys from peers, which gave an all-zero shared
151
+ secret with the nuckle backend (protocol-zmtp).
152
+ - Yielded to other fibers while a DISH skips malformed datagrams or datagrams
153
+ for groups it didn't join. A flood on its UDP port kept the receive loop
154
+ spinning without letting anything else run.
155
+ - Stopped sending heartbeat PINGs to ZMTP 3.0 peers, which have no PING command.
156
+ - Made `udp://` work over IPv6 (`udp://[::1]:5555`) and resolve the RADIO
157
+ destination once at connect instead of on every datagram. DISH on a multicast
158
+ address now joins the group, and several DISH sockets can bind the same group
159
+ and port.
160
+ - PUB and XPUB match subscriptions with a radix trie instead of trying every
161
+ prefix. A subscriber at `max_peer_subscriptions` cost the publisher about 7 ms
162
+ per message; matching now takes well under a microsecond at any count.
163
+ - A frozen UTF-8 topic no longer raises `Encoding::CompatibilityError` in the
164
+ fan-out send pump against a non-ASCII subscription prefix, so the subscriber
165
+ gets the message. Matching compares bytes.
166
+
167
+ ## [0.29.1] - 2026-11-26
168
+
169
+ ### Fixed
170
+
171
+ - Reconnected in-process (`ruby://`, `inproc://`) connect sockets after the
172
+ bound peer closes, instead of raising `NoMethodError` in the connection
173
+ supervisor. A new socket bound to the same endpoint now receives messages
174
+ again (#30).
175
+
5
176
  ## [0.29.0] - 2026-10-15
6
177
 
7
178
  ### Added
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