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
data/lib/omq/engine.rb CHANGED
@@ -8,6 +8,9 @@ require_relative "engine/reconnect"
8
8
  require_relative "engine/connection_lifecycle"
9
9
  require_relative "engine/socket_lifecycle"
10
10
  require_relative "engine/maintenance"
11
+ require_relative "engine/endpoints"
12
+ require_relative "engine/monitoring"
13
+ require_relative "engine/pump_tasks"
11
14
 
12
15
  module OMQ
13
16
  # Per-socket orchestrator.
@@ -16,6 +19,11 @@ module OMQ
16
19
  # OMQ::Socket instance. Each socket type creates one Engine.
17
20
  #
18
21
  class Engine
22
+ include Endpoints
23
+ include Monitoring
24
+ include PumpTasks
25
+
26
+
19
27
  # Scheme → transport module registry.
20
28
  # Plugins add entries via +Engine.transports["scheme"] = MyTransport+.
21
29
  #
@@ -60,7 +68,7 @@ module OMQ
60
68
 
61
69
 
62
70
  # @!attribute [w] monitor_queue
63
- # @param value [Async::Queue, nil] queue for monitor events
71
+ # @param value [MonitorQueue, nil] queue for monitor events
64
72
  #
65
73
  attr_writer :monitor_queue
66
74
 
@@ -86,21 +94,58 @@ module OMQ
86
94
  @routing = nil
87
95
  @connections = {} # connection => ConnectionLifecycle
88
96
  @dialers = {} # endpoint => Dialer (reconnect intent + connect logic)
97
+ @dialer_barriers = {} # endpoint => Async::Barrier (its reconnect + connection tasks)
89
98
  @listeners = {} # endpoint => Listener
99
+ @bind_aliases = {} # endpoint as passed to #bind => listener endpoint
90
100
  @lifecycle = SocketLifecycle.new
91
101
  @fatal_error = nil
92
102
  @monitor_queue = nil
93
103
  @verbose_monitor = false
104
+ @drain_signal = nil # set while #close waits for send queues
105
+ @batches_sending = 0 # batches pumps took off a queue and haven't flushed
106
+ end
107
+
108
+
109
+ # @return [Async::Promise] resolves with the first peer that connects
110
+ #
111
+ def peer_connected
112
+ @lifecycle.peer_connected
113
+ end
114
+
115
+
116
+ # @return [Async::Promise] resolves once every peer is gone
117
+ #
118
+ def all_peers_gone
119
+ @lifecycle.all_peers_gone
120
+ end
121
+
122
+
123
+ # @return [Async::Task, nil] the task the socket's tasks run under
124
+ #
125
+ def parent_task
126
+ @lifecycle.parent_task
127
+ end
128
+
129
+
130
+ # @return [Async::Barrier, nil] the socket-level barrier
131
+ #
132
+ def barrier
133
+ @lifecycle.barrier
94
134
  end
95
135
 
96
136
 
97
- # Delegated to {SocketLifecycle}.
98
- def peer_connected = @lifecycle.peer_connected
99
- def all_peers_gone = @lifecycle.all_peers_gone
100
- def parent_task = @lifecycle.parent_task
101
- def barrier = @lifecycle.barrier
102
- def closed? = @lifecycle.closed?
103
- def on_io_thread? = @lifecycle.on_io_thread
137
+ # @return [Boolean] true once the socket is closed
138
+ #
139
+ def closed?
140
+ @lifecycle.closed?
141
+ end
142
+
143
+
144
+ # @return [Boolean] true if the socket runs on the shared IO thread
145
+ #
146
+ def on_io_thread?
147
+ @lifecycle.on_io_thread
148
+ end
104
149
 
105
150
 
106
151
  # Enables or disables auto-reconnect for dropped connections.
@@ -155,34 +200,6 @@ module OMQ
155
200
  end
156
201
 
157
202
 
158
- # Returns the transport object (Dialer or Listener) for an endpoint.
159
- # Used by {ConnectionLifecycle#ready!} to call +#wrap_connection+.
160
- #
161
- # @param endpoint [String]
162
- # @return [Dialer, Listener, nil]
163
- #
164
- def transport_object_for(endpoint)
165
- @dialers[endpoint] || @listeners[endpoint]
166
- end
167
-
168
-
169
- # Spawns a ruby:// reconnect retry task under the socket's parent task.
170
- #
171
- # @param endpoint [String]
172
- # @yield [interval] the retry loop body
173
- #
174
- def spawn_inproc_retry(endpoint)
175
- ri = @options.reconnect_interval
176
- ivl = ri.is_a?(Range) ? ri.begin : ri
177
- ann = "inproc reconnect #{endpoint}"
178
-
179
- @lifecycle.barrier.async(transient: true, annotation: ann) do
180
- yield ivl
181
- rescue Async::Stop, Async::Cancel
182
- end
183
- end
184
-
185
-
186
203
  # Binds to an endpoint.
187
204
  #
188
205
  # @param endpoint [String] e.g. "tcp://127.0.0.1:5555", "ruby://foo"
@@ -198,6 +215,7 @@ module OMQ
198
215
  start_accept_loops(listener)
199
216
 
200
217
  @listeners[listener.endpoint] = listener
218
+ remember_bind_alias(endpoint, listener.endpoint)
201
219
  emit_monitor_event(:listening, endpoint: listener.endpoint)
202
220
  URI.parse(listener.endpoint)
203
221
  rescue => error
@@ -217,12 +235,12 @@ module OMQ
217
235
  endpoint, transport = resolve_endpoint(endpoint)
218
236
  validate_endpoint!(endpoint, transport)
219
237
 
238
+ dialer = transport.dialer(endpoint, self, **opts)
239
+ @dialers[endpoint] = dialer
240
+
220
241
  if endpoint.start_with?("ruby://")
221
- # Ruby in-process connect is synchronous and instant — no Dialer
222
- transport.connect(endpoint, self, **opts)
223
- @dialers[endpoint] = :ruby # sentinel for reconnect intent
242
+ connect_inproc(endpoint, dialer)
224
243
  else
225
- @dialers[endpoint] = transport.dialer(endpoint, self, **opts)
226
244
  emit_monitor_event(:connect_delayed, endpoint: endpoint)
227
245
  schedule_reconnect(endpoint, delay: 0)
228
246
  end
@@ -231,8 +249,8 @@ module OMQ
231
249
  end
232
250
 
233
251
 
234
- # Disconnects from an endpoint. Closes connections to that endpoint
235
- # and stops auto-reconnection for it.
252
+ # Disconnects from an endpoint. Stops its reconnect loop and any
253
+ # handshake in progress, then closes its connections.
236
254
  #
237
255
  # @param endpoint [String]
238
256
  # @return [void]
@@ -240,20 +258,26 @@ module OMQ
240
258
  def disconnect(endpoint)
241
259
  endpoint = canonical_endpoint(endpoint)
242
260
  @dialers.delete(endpoint)
261
+ @dialer_barriers.delete(endpoint)&.stop
243
262
  close_connections_at(endpoint)
263
+ drop_route(endpoint)
244
264
  end
245
265
 
246
266
 
247
267
  # Unbinds from an endpoint. Stops the listener and closes all
248
- # connections that were accepted on it.
268
+ # connections that were accepted on it. Accepts the resolved
269
+ # endpoint (as returned by {#bind}) or the string passed to
270
+ # {#bind}, e.g. +tcp://localhost:5555+.
249
271
  #
250
272
  # @param endpoint [String]
251
273
  # @return [void]
252
274
  #
253
275
  def unbind(endpoint)
254
276
  endpoint = canonical_endpoint(endpoint)
277
+ endpoint = @bind_aliases.fetch(endpoint, endpoint)
255
278
  listener = @listeners.delete(endpoint) or return
256
279
 
280
+ @bind_aliases.delete_if { |_, bound| bound == endpoint }
257
281
  listener.stop
258
282
  close_connections_at(endpoint)
259
283
  end
@@ -277,8 +301,16 @@ module OMQ
277
301
  # @return [void]
278
302
  #
279
303
  def handle_connected(io, endpoint: nil)
304
+ barrier = @dialer_barriers[endpoint]
305
+
306
+ # Disconnected (or closed) while the dial was in flight.
307
+ unless barrier && @dialers.key?(endpoint)
308
+ io.close rescue nil
309
+ return
310
+ end
311
+
280
312
  emit_monitor_event(:connected, endpoint: endpoint)
281
- spawn_connection(io, as_server: false, endpoint: endpoint)
313
+ spawn_connection(io, as_server: false, endpoint: endpoint, parent: barrier)
282
314
  end
283
315
 
284
316
 
@@ -286,20 +318,82 @@ module OMQ
286
318
  # Skips ZMTP handshake — just registers with routing strategy.
287
319
  #
288
320
  # @param pipe [Transport::Inproc::Pipe]
321
+ # @return [Boolean] false if the routing strategy refused the peer
322
+ #
323
+ def connection_ready(pipe, endpoint: nil, dialed: false)
324
+ ConnectionLifecycle.new(self, endpoint: endpoint, dialed: dialed).ready_direct!(pipe)
325
+ end
326
+
327
+
328
+ # @param conn [Protocol::ZMTP::Connection, Transport::Inproc::Pipe]
329
+ # @return [String, nil] the endpoint this socket dialed to get +conn+,
330
+ # nil for an accepted connection
331
+ #
332
+ def dialed_endpoint(conn)
333
+ lifecycle = @connections[conn]
334
+ lifecycle.endpoint if lifecycle&.dialed?
335
+ end
336
+
337
+
338
+ # @param endpoint [String, nil]
339
+ # @return [Boolean] true if a lost connection to +endpoint+ gets
340
+ # redialed
341
+ #
342
+ def redials?(endpoint)
343
+ return false unless endpoint && @dialers.key?(endpoint)
344
+
345
+ @lifecycle.open? && @lifecycle.reconnect_enabled
346
+ end
347
+
348
+
349
+ # Drops the send queue a routing strategy keeps for a dialed
350
+ # endpoint between connections (ROUTER, SERVER, PEER).
351
+ #
352
+ # @param endpoint [String, nil]
289
353
  # @return [void]
290
354
  #
291
- def connection_ready(pipe, endpoint: nil)
292
- ConnectionLifecycle.new(self, endpoint: endpoint).ready_direct!(pipe)
355
+ def drop_route(endpoint)
356
+ @routing.drop_route(endpoint) if endpoint && @routing.respond_to?(:drop_route)
357
+ wake_drain
358
+ end
359
+
360
+
361
+ # Wakes {#drain_send_queues} to check the send queues again. Send
362
+ # pumps call it after each batch, teardown when a queue goes away.
363
+ # A no-op unless {#close} is waiting.
364
+ #
365
+ # @return [void]
366
+ #
367
+ def wake_drain
368
+ @drain_signal&.signal
369
+ end
370
+
371
+
372
+ # Runs a send pump's write of a batch it took off a queue. Until the
373
+ # block returns, {#drain_send_queues} counts the batch as unsent, so
374
+ # #close doesn't tear the connection down under the write.
375
+ #
376
+ # @yield the write and flush
377
+ # @return [Object] the block's value
378
+ #
379
+ def sending_batch
380
+ @batches_sending += 1
381
+ yield
382
+ ensure
383
+ @batches_sending -= 1
384
+ wake_drain
293
385
  end
294
386
 
295
387
 
296
388
  # Dequeues the next received message. Blocks until available.
297
389
  #
298
- # @return [Array<String>] message parts
390
+ # @return [Array<String>, nil] message parts, or nil once the socket
391
+ # is closed (like +Thread::Queue#pop+ on a closed queue)
299
392
  # @raise if a background pump task crashed
300
393
  #
301
394
  def dequeue_recv
302
395
  raise @fatal_error if @fatal_error
396
+ return if @lifecycle.closed?
303
397
 
304
398
  msg = routing.dequeue_recv
305
399
  raise @fatal_error if msg.nil? && @fatal_error
@@ -321,10 +415,16 @@ module OMQ
321
415
  # @param parts [Array<String>]
322
416
  # @return [void]
323
417
  # @raise if a background pump task crashed
418
+ # @raise [SocketClosedError] if the socket is closing or closed,
419
+ # including while blocked at HWM
324
420
  #
325
421
  def enqueue_send(parts)
326
422
  raise @fatal_error if @fatal_error
423
+ raise_if_closed!
424
+
327
425
  routing.enqueue(parts)
426
+ rescue Async::Queue::ClosedError, ClosedQueueError
427
+ raise SocketClosedError, "#{@socket_type} socket closed while sending"
328
428
  end
329
429
 
330
430
 
@@ -367,12 +467,9 @@ module OMQ
367
467
  # and the endpoint is still dialed.
368
468
  #
369
469
  def maybe_reconnect(endpoint)
370
- return unless endpoint && @dialers.key?(endpoint)
371
- return unless @lifecycle.open? && @lifecycle.reconnect_enabled
470
+ return unless redials?(endpoint)
372
471
 
373
- dialer = @dialers[endpoint]
374
-
375
- Reconnect.schedule(dialer, @options, @lifecycle.parent_task, self)
472
+ Reconnect.schedule(@dialers[endpoint], @options, dialer_barrier(endpoint), self)
376
473
  end
377
474
 
378
475
 
@@ -384,6 +481,7 @@ module OMQ
384
481
  # @return [void]
385
482
  #
386
483
  def close
484
+ return close_unopened if @lifecycle.state == :new
387
485
  return unless @lifecycle.open?
388
486
 
389
487
  @lifecycle.start_closing!
@@ -401,6 +499,7 @@ module OMQ
401
499
 
402
500
  stop_listeners
403
501
  tear_down_barrier
502
+ close_routing_queues
404
503
  emit_monitor_event(:closed)
405
504
  close_monitor_queue
406
505
  end
@@ -423,100 +522,12 @@ module OMQ
423
522
 
424
523
  stop_listeners
425
524
  tear_down_barrier
525
+ close_routing_queues
426
526
  emit_monitor_event(:closed)
427
527
  close_monitor_queue
428
528
  end
429
529
 
430
530
 
431
- # Spawns a transient pump task with error propagation.
432
- #
433
- # Unexpected exceptions are caught and forwarded to
434
- # {#signal_fatal_error} so blocked callers (send/recv)
435
- # see the real error instead of deadlocking.
436
- #
437
- # @param annotation [String] task annotation for debugging
438
- # @param parent [Async::Task, Async::Barrier] parent for the spawned
439
- # task. Defaults to the current task. Routing strategies that own
440
- # loose pump tasks (Radio, Channel) pass their own +Async::Barrier+
441
- # so a single +barrier.stop+ tears the lot down at strategy
442
- # shutdown without per-task bookkeeping.
443
- # @yield the pump loop body
444
- # @return [Async::Task]
445
- #
446
- def spawn_pump_task(annotation:, parent: Async::Task.current, &block)
447
- parent.async(transient: true, annotation: annotation) do
448
- yield
449
- rescue Async::Stop, Async::Cancel, Protocol::ZMTP::Error, *CONNECTION_LOST
450
- # normal shutdown / expected disconnect
451
- rescue => error
452
- signal_fatal_error(error)
453
- end
454
- end
455
-
456
-
457
- # Spawns a per-connection pump task on the connection's own
458
- # lifecycle barrier. When any pump on the barrier exits (e.g. the
459
- # send pump sees EPIPE and calls {#connection_lost}), {ConnectionLifecycle#tear_down!}
460
- # calls `barrier.stop` which cancels every sibling pump for that
461
- # connection — so a dead peer can no longer leave orphan send
462
- # pumps blocked on `dequeue` waiting for messages that will never
463
- # be written.
464
- #
465
- # @param conn [Protocol::ZMTP::Connection, Transport::Inproc::Pipe]
466
- # @param annotation [String]
467
- #
468
- def spawn_conn_pump_task(conn, annotation:, &block)
469
- lifecycle = @connections[conn]
470
-
471
- unless lifecycle
472
- return spawn_pump_task(annotation: annotation, &block)
473
- end
474
-
475
- lifecycle.barrier.async(transient: true, annotation: annotation) do
476
- yield
477
- rescue Async::Stop, Async::Cancel
478
- # normal shutdown / sibling tore us down
479
- rescue Protocol::ZMTP::Error, *CONNECTION_LOST => error
480
- # expected disconnect — stash reason for the :disconnected
481
- # monitor event, then let the lifecycle reconnect as usual
482
- lifecycle.record_disconnect_reason(error)
483
- rescue => error
484
- signal_fatal_error(error)
485
- end
486
- end
487
-
488
-
489
- # Wraps an unexpected pump error as {OMQ::SocketDeadError} and
490
- # unblocks any callers waiting on the recv queue. The original
491
- # error is preserved as +#cause+ so callers can surface the real
492
- # reason.
493
- #
494
- # @param error [Exception]
495
- #
496
- def signal_fatal_error(error)
497
- return unless @lifecycle.open?
498
-
499
- @fatal_error = build_fatal_error(error)
500
- routing.unblock_recv rescue nil
501
- @lifecycle.peer_connected.resolve(nil) rescue nil
502
- end
503
-
504
-
505
- # Constructs a SocketDeadError whose +cause+ is +error+. Uses the
506
- # raise-in-rescue idiom because Ruby only sets +cause+ on an
507
- # exception when it is raised from inside a rescue block -- works
508
- # regardless of the original caller's +$!+ state.
509
- def build_fatal_error(error)
510
- raise error
511
- rescue
512
- begin
513
- raise SocketDeadError, "#{@socket_type} socket killed: #{error.message}"
514
- rescue SocketDeadError => wrapped
515
- wrapped
516
- end
517
- end
518
-
519
-
520
531
  # Captures the socket's task tree root and starts the socket-level
521
532
  # maintenance task. If +parent+ is given, it is used as the parent
522
533
  # for every task spawned under this socket (connection supervisors,
@@ -531,6 +542,8 @@ module OMQ
531
542
  # @param parent [#async, nil] optional Async parent
532
543
  #
533
544
  def capture_parent_task(parent: nil)
545
+ raise_if_closed!
546
+
534
547
  task = @lifecycle.capture_parent_task(parent: parent, linger: @options.linger)
535
548
 
536
549
  return unless task
@@ -539,87 +552,6 @@ module OMQ
539
552
  end
540
553
 
541
554
 
542
- # Emits a lifecycle event to the monitor queue, if one is attached.
543
- #
544
- # @param type [Symbol] event type (e.g. :listening, :connected, :disconnected)
545
- # @param endpoint [String, nil] the endpoint involved
546
- # @param detail [Hash, nil] extra context
547
- # @return [void]
548
- #
549
- def emit_monitor_event(type, endpoint: nil, detail: nil)
550
- return unless @monitor_queue
551
-
552
- event = MonitorEvent.new type: type, endpoint: endpoint, detail: detail
553
-
554
- @monitor_queue << event
555
- rescue Async::Stop, ClosedQueueError
556
- end
557
-
558
-
559
- # Emits a verbose-only monitor event (e.g. message traces).
560
- # Only emitted when {Socket#monitor} was called with +verbose: true+.
561
- # Uses +**detail+ to avoid Hash allocation when verbose is off.
562
- #
563
- # @param type [Symbol] event type (e.g. :message_sent, :message_received)
564
- # @param detail [Hash] extra context forwarded as keyword args
565
- # @return [void]
566
- #
567
- def emit_verbose_monitor_event(type, **detail)
568
- return unless @verbose_monitor
569
- emit_monitor_event(type, detail: detail)
570
- end
571
-
572
-
573
- # Emits a :message_sent verbose event and enriches it with the
574
- # on-wire (post-compression) byte size if +conn+ exposes
575
- # +last_wire_size_out+ (installed by ZMTP-Zstd etc.).
576
- def emit_verbose_msg_sent(conn, parts)
577
- return unless @verbose_monitor
578
-
579
- detail = { parts: parts }
580
-
581
- if conn.respond_to? :last_wire_size_out
582
- detail[:wire_size] = conn.last_wire_size_out
583
- end
584
-
585
- emit_monitor_event :message_sent, detail: detail
586
- end
587
-
588
-
589
- # Emits a :message_received verbose event and enriches it with the
590
- # on-wire (pre-decompression) byte size if +conn+ exposes
591
- # +last_wire_size_in+.
592
- def emit_verbose_msg_received(conn, parts)
593
- return unless @verbose_monitor
594
-
595
- detail = { parts: parts }
596
-
597
- if conn.respond_to? :last_wire_size_in
598
- detail[:wire_size] = conn.last_wire_size_in
599
- end
600
-
601
- emit_monitor_event :message_received, detail: detail
602
- end
603
-
604
-
605
- # Looks up the transport module for an endpoint URI.
606
- #
607
- # @param endpoint [String] endpoint URI (e.g. "tcp://...", "ruby://...")
608
- # @return [Module] the transport module
609
- # @raise [ArgumentError] if the scheme is not registered
610
- #
611
- def transport_for(endpoint)
612
- scheme = scheme_for(endpoint)
613
- transport = registered_transport(scheme)
614
-
615
- unless transport
616
- raise ArgumentError, "unsupported transport: #{endpoint}"
617
- end
618
-
619
- transport
620
- end
621
-
622
-
623
555
  private
624
556
 
625
557
 
@@ -632,12 +564,15 @@ module OMQ
632
564
  # @param io [#read, #write, #close] accepted or dialed socket
633
565
  # @param as_server [Boolean] true for accepted connections
634
566
  # @param endpoint [String, nil] the endpoint URI, for monitor events
567
+ # @param parent [Async::Barrier, nil] owner of the connection task:
568
+ # the dialer's barrier for dialed connections, so {#disconnect}
569
+ # also stops a handshake in progress
635
570
  #
636
- def spawn_connection(io, as_server:, endpoint: nil)
637
- @lifecycle.barrier&.async(transient: true, annotation: "conn #{endpoint}") do
571
+ def spawn_connection(io, as_server:, endpoint: nil, parent: @lifecycle.barrier)
572
+ parent&.async(transient: true, annotation: "conn #{endpoint}") do
638
573
  done = Async::Promise.new
639
574
  transport = endpoint ? transport_for(endpoint) : nil
640
- lifecycle = ConnectionLifecycle.new(self, endpoint: endpoint, done: done, transport: transport)
575
+ lifecycle = ConnectionLifecycle.new(self, endpoint: endpoint, done: done, transport: transport, dialed: !as_server)
641
576
  lifecycle.handshake!(io, as_server: as_server)
642
577
  done.wait
643
578
  rescue Async::Stop, Async::Cancel
@@ -654,31 +589,35 @@ module OMQ
654
589
 
655
590
  # Blocks until the routing strategy reports all send queues drained
656
591
  # or +timeout+ seconds have elapsed. Called from the linger path on
657
- # close so pending outgoing messages get a chance to flush.
592
+ # close so pending outgoing messages get a chance to flush. Sleeps
593
+ # until {#wake_drain} says something changed.
658
594
  #
659
595
  # @param timeout [Numeric, nil] max seconds to wait; nil = no limit
660
596
  #
661
- # TODO: replace the 1 ms busy-poll with a promise/condition that
662
- # the send pump resolves when its queue hits empty. The loop exists
663
- # because there is currently no signal for "send queue fully
664
- # drained"; fixing it cleanly requires plumbing a notifier through
665
- # every routing strategy, so it is flagged rather than fixed here.
666
- #
667
597
  def drain_send_queues(timeout)
668
598
  return unless @routing.respond_to?(:send_queues_drained?)
669
599
 
670
- if timeout
671
- deadline = Async::Clock.now + timeout
672
- end
600
+ deadline = timeout&.finite? ? Async::Clock.now + timeout : nil # nil, Infinity: no limit
601
+ @drain_signal = Async::Notification.new
602
+
603
+ until @batches_sending.zero? && @routing.send_queues_drained?
604
+ if deadline
605
+ remaining = deadline - Async::Clock.now
606
+ break if remaining <= 0
673
607
 
674
- until @routing.send_queues_drained?
675
- break if deadline && (deadline - Async::Clock.now) <= 0
676
- sleep 0.001
608
+ Async::Task.current.with_timeout(remaining) { @drain_signal.wait }
609
+ else
610
+ @drain_signal.wait
611
+ end
677
612
  end
613
+ rescue Async::TimeoutError
614
+ # linger expired
678
615
  rescue Async::Stop
679
616
  # Parent task is being cancelled — stop draining and let close
680
617
  # proceed with the rest of teardown instead of propagating the
681
618
  # cancellation out of the ensure path.
619
+ ensure
620
+ @drain_signal = nil
682
621
  end
683
622
 
684
623
 
@@ -691,73 +630,37 @@ module OMQ
691
630
  #
692
631
  def schedule_reconnect(endpoint, delay: nil)
693
632
  dialer = @dialers[endpoint]
694
- Reconnect.schedule(dialer, @options, @lifecycle.parent_task, self, delay: delay)
695
- end
696
-
697
-
698
- # Delegates endpoint validation to the transport if it defines one.
699
- # Called from {#connect} so a bad URI fails fast instead of landing
700
- # in a reconnect loop.
701
- #
702
- # @param endpoint [String]
703
- # @raise [ArgumentError] if the transport rejects the endpoint
704
- #
705
- def validate_endpoint!(endpoint, transport)
706
- if transport.respond_to?(:validate_endpoint!)
707
- transport.validate_endpoint!(endpoint)
708
- end
633
+ Reconnect.schedule(dialer, @options, dialer_barrier(endpoint), self, delay: delay)
709
634
  end
710
635
 
711
636
 
712
- # Resolves transport aliases before the endpoint is stored in
713
- # listener, dialer, or connection maps.
637
+ # Returns the barrier that owns +endpoint+'s reconnect loop and
638
+ # dialed connection tasks, nested in the socket barrier so
639
+ # {#close} stops them too.
714
640
  #
715
641
  # @param endpoint [String]
716
- # @return [Array(String, Module)]
717
- #
718
- def resolve_endpoint(endpoint)
719
- transport = transport_for(endpoint)
720
- if transport.respond_to?(:canonical_endpoint)
721
- endpoint = transport.canonical_endpoint(endpoint)
722
- end
723
-
724
- [endpoint, transport]
725
- end
726
-
727
-
728
- # Best-effort normalization for disconnect/unbind. Unknown schemes
729
- # stay as-is so those calls remain no-ops instead of raising.
730
- #
731
- # @param endpoint [String]
732
- # @return [String]
733
- #
734
- def canonical_endpoint(endpoint)
735
- transport = registered_transport(scheme_for(endpoint))
736
- return endpoint unless transport&.respond_to?(:canonical_endpoint)
737
-
738
- transport.canonical_endpoint(endpoint)
739
- end
740
-
741
-
742
- # Looks up a registered transport. If no real inproc transport is
743
- # registered, inproc:// falls back to the Ruby in-process transport.
642
+ # @return [Async::Barrier]
744
643
  #
745
- # @param scheme [String, nil]
746
- # @return [Module, nil]
747
- #
748
- def registered_transport(scheme)
749
- self.class.transports[scheme] ||
750
- (scheme == "inproc" ? self.class.transports["ruby"] : nil)
644
+ def dialer_barrier(endpoint)
645
+ @dialer_barriers[endpoint] ||= Async::Barrier.new(parent: @lifecycle.barrier)
751
646
  end
752
647
 
753
648
 
754
- # Extracts the URI scheme from an endpoint.
649
+ # Ruby in-process connects are synchronous: link now, or wait up to
650
+ # one reconnect interval for a bind, then keep retrying in the
651
+ # background like any other dialer.
755
652
  #
756
653
  # @param endpoint [String]
757
- # @return [String, nil]
654
+ # @param dialer [Transport::Inproc::Dialer]
758
655
  #
759
- def scheme_for(endpoint)
760
- endpoint[/\A([^:]+):\/\//, 1]
656
+ def connect_inproc(endpoint, dialer)
657
+ dialer.connect(wait: true)
658
+ rescue Errno::ECONNREFUSED
659
+ emit_monitor_event(:connect_delayed, endpoint: endpoint)
660
+ schedule_reconnect(endpoint)
661
+ rescue
662
+ @dialers.delete(endpoint)
663
+ raise
761
664
  end
762
665
 
763
666
 
@@ -782,6 +685,22 @@ module OMQ
782
685
  def stop_listeners
783
686
  @listeners.each_value(&:stop)
784
687
  @listeners.clear
688
+ @bind_aliases.clear
689
+ end
690
+
691
+
692
+ # Lets {#unbind} find a listener by the string the caller passed to
693
+ # {#bind}. Ephemeral-port requests (+:0+, +:*+) can bind many
694
+ # listeners, so they don't get an alias.
695
+ #
696
+ # @param requested [String] canonical endpoint passed to #bind
697
+ # @param bound [String] the listener's resolved endpoint
698
+ #
699
+ def remember_bind_alias(requested, bound)
700
+ return if requested == bound
701
+ return if requested.end_with?(":0", ":*")
702
+
703
+ @bind_aliases[requested] = bound
785
704
  end
786
705
 
787
706
 
@@ -798,21 +717,40 @@ module OMQ
798
717
  # Cascades teardown through the socket-level barrier. Stopping the
799
718
  # barrier cancels every tracked task: connection supervisors (whose
800
719
  # `ensure lost!` runs the ordered disconnect side effects), accept
801
- # loops, heartbeat, maintenance. Reconnect loops live on the user's
802
- # parent task and self-exit via `@engine.closed?`.
720
+ # loops, heartbeat, maintenance, and the per-endpoint dialer
721
+ # barriers with their reconnect loops.
803
722
  #
804
723
  def tear_down_barrier
805
724
  @lifecycle.barrier&.stop
806
725
  end
807
726
 
808
727
 
809
- # Signals end-of-stream on the monitor queue (if any) by pushing a
810
- # +nil+ sentinel, so consumers iterating with {Socket#each_event}
811
- # can exit cleanly.
728
+ # @raise [SocketClosedError] once {#close} or {#stop} has started
812
729
  #
813
- def close_monitor_queue
814
- return unless @monitor_queue
815
- @monitor_queue.push(nil)
730
+ def raise_if_closed!
731
+ return if @lifecycle.alive?
732
+
733
+ raise SocketClosedError, "#{@socket_type} socket is closed"
816
734
  end
735
+
736
+
737
+ # Closes a socket that never bound or connected: there are no tasks
738
+ # to stop, but later calls must see it closed.
739
+ #
740
+ def close_unopened
741
+ @lifecycle.finish_closing!
742
+ close_routing_queues
743
+ emit_monitor_event(:closed)
744
+ close_monitor_queue
745
+ end
746
+
747
+
748
+ # Wakes fibers blocked in a send (they raise {SocketClosedError}) or
749
+ # a receive (they get +nil+).
750
+ #
751
+ def close_routing_queues
752
+ @routing.close_queues if @routing.respond_to?(:close_queues)
753
+ end
754
+
817
755
  end
818
756
  end