async-rabbitmq 0.8.1 → 0.9.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +247 -0
- data/README.md +44 -9
- data/lib/async_rabbitmq/channel.rb +506 -78
- data/lib/async_rabbitmq/cluster.rb +53 -20
- data/lib/async_rabbitmq/frame_io.rb +43 -19
- data/lib/async_rabbitmq/log.rb +4 -1
- data/lib/async_rabbitmq/logging.rb +141 -0
- data/lib/async_rabbitmq/notifier.rb +5 -2
- data/lib/async_rabbitmq/sasl.rb +16 -3
- data/lib/async_rabbitmq/session.rb +302 -85
- data/lib/async_rabbitmq/version.rb +1 -1
- data/lib/async_rabbitmq.rb +22 -0
- metadata +32 -3
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
require "async"
|
|
2
2
|
require "async/condition"
|
|
3
|
+
require "async/promise"
|
|
3
4
|
require "async/semaphore"
|
|
5
|
+
require "async/notification"
|
|
6
|
+
require "async/barrier"
|
|
4
7
|
require "socket"
|
|
8
|
+
require "io/endpoint/host_endpoint"
|
|
5
9
|
require "openssl"
|
|
6
10
|
require "uri"
|
|
7
11
|
require "amq/uri"
|
|
@@ -62,9 +66,12 @@ module AsyncRabbitMQ
|
|
|
62
66
|
raise ArgumentError, "at least one URI string is required" if uri_strings.empty?
|
|
63
67
|
|
|
64
68
|
first_opts = uri_options(uri_strings.first)
|
|
69
|
+
# [host, port] pairs, never "host:port" strings: an IPv6 literal has
|
|
70
|
+
# colons of its own, and the round-trip through a joined string parsed
|
|
71
|
+
# "[::1]:5672" into host "[" port 0.
|
|
65
72
|
address_list = uri_strings.map do |u|
|
|
66
73
|
parsed = uri_options(u)
|
|
67
|
-
|
|
74
|
+
[parsed[:host] || "localhost", parsed[:port]]
|
|
68
75
|
end
|
|
69
76
|
|
|
70
77
|
# Connection-level settings come from the first URI; addresses from all.
|
|
@@ -84,7 +91,9 @@ module AsyncRabbitMQ
|
|
|
84
91
|
params = query ? ::URI.decode_www_form(query).to_h : {}
|
|
85
92
|
|
|
86
93
|
opts = { tls: !!parsed[:ssl], port: parsed[:port] }
|
|
87
|
-
|
|
94
|
+
# A URI carries an IPv6 literal in brackets and Ruby's URI keeps them:
|
|
95
|
+
# "amqp://[::1]" parses to host "[::1]". The socket layer wants the bare "::1".
|
|
96
|
+
opts[:host] = parsed[:host].delete_prefix("[").delete_suffix("]") if parsed[:host]
|
|
88
97
|
opts[:username] = parsed[:user] if parsed[:user]
|
|
89
98
|
opts[:password] = parsed[:pass] if parsed[:pass]
|
|
90
99
|
# "amqp://host/" yields an empty vhost; treat it as the default "/" rather
|
|
@@ -121,10 +130,7 @@ module AsyncRabbitMQ
|
|
|
121
130
|
# host: "rabbit1", port: 5672 (default) -> [["rabbit1",5672]]
|
|
122
131
|
def self.address_list(host:, port:, hosts: nil, addresses: nil)
|
|
123
132
|
if addresses && !addresses.empty?
|
|
124
|
-
addresses.map
|
|
125
|
-
h, p = addr.to_s.split(":", 2)
|
|
126
|
-
[h, p ? p.to_i : port]
|
|
127
|
-
end
|
|
133
|
+
addresses.map { |addr| split_address(addr, port) }
|
|
128
134
|
elsif hosts && !hosts.empty?
|
|
129
135
|
hosts.map { |h| [h.to_s, port] }
|
|
130
136
|
else
|
|
@@ -132,6 +138,32 @@ module AsyncRabbitMQ
|
|
|
132
138
|
end
|
|
133
139
|
end
|
|
134
140
|
|
|
141
|
+
# One address in any accepted shape to [host, port]. An IPv6 literal has
|
|
142
|
+
# colons of its own, so splitting on the first colon mangled it: bracketed
|
|
143
|
+
# ("[::1]:5672", the URI form) and bare ("::1", host only — a port after a
|
|
144
|
+
# bare literal is ambiguous and needs the brackets) are both handled.
|
|
145
|
+
# [host, port] pairs pass through, which is what from_uri now builds.
|
|
146
|
+
def self.split_address(addr, default_port)
|
|
147
|
+
if addr.is_a?(Array)
|
|
148
|
+
# Strip URI brackets here too, so ["[::1]", 5672] works like "[::1]:5672".
|
|
149
|
+
host = addr[0].to_s.delete_prefix("[").delete_suffix("]")
|
|
150
|
+
return [host, (addr[1] || default_port).to_i]
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
s = addr.to_s
|
|
154
|
+
if s.start_with?("[") # "[v6]:port" or "[v6]"
|
|
155
|
+
h, _, rest = s.delete_prefix("[").partition("]")
|
|
156
|
+
p = rest.delete_prefix(":")
|
|
157
|
+
[h, p.empty? ? default_port : p.to_i]
|
|
158
|
+
elsif s.count(":") > 1 # bare v6 literal: the whole thing is the host
|
|
159
|
+
[s, default_port]
|
|
160
|
+
else
|
|
161
|
+
h, p = s.split(":", 2)
|
|
162
|
+
[h, p ? p.to_i : default_port]
|
|
163
|
+
end
|
|
164
|
+
end
|
|
165
|
+
private_class_method :split_address
|
|
166
|
+
|
|
135
167
|
def initialize(
|
|
136
168
|
host: "localhost",
|
|
137
169
|
port: 5672,
|
|
@@ -165,7 +197,7 @@ module AsyncRabbitMQ
|
|
|
165
197
|
topology_recovery_filter: nil,
|
|
166
198
|
instrumenter: nil,
|
|
167
199
|
notifier: nil,
|
|
168
|
-
logger:
|
|
200
|
+
logger: Console
|
|
169
201
|
)
|
|
170
202
|
@addresses = self.class.address_list(host: host, port: port, hosts: hosts, addresses: addresses)
|
|
171
203
|
@host = @addresses.first[0]
|
|
@@ -199,14 +231,16 @@ module AsyncRabbitMQ
|
|
|
199
231
|
# Channel#recovers_cancelled_consumers? for why it is off.
|
|
200
232
|
@recover_cancelled_consumers = recover_cancelled_consumers
|
|
201
233
|
@topology = TopologyRegistry.new(filter: topology_recovery_filter)
|
|
202
|
-
@logger = logger
|
|
203
|
-
@notifier = notifier || Notifier.new(logger: logger)
|
|
234
|
+
@logger = Logging.resolve(logger)
|
|
235
|
+
@notifier = notifier || Notifier.new(logger: @logger)
|
|
204
236
|
@notifier.subscribe { |name, payload| instrumenter.call(name, payload) } if instrumenter
|
|
205
237
|
|
|
206
238
|
@state = :closed
|
|
207
239
|
@frame_io = nil
|
|
208
240
|
@channels = {} # channel_id => Channel; a closed channel's id is free again
|
|
209
241
|
@channel_mutex = Async::Semaphore.new(1)
|
|
242
|
+
@update_secret_sem = Async::Semaphore.new(1) # one connection.update-secret in flight
|
|
243
|
+
@topology_replay_failure = nil # set by reopen_channels when the replay stopped early
|
|
210
244
|
@negotiated_hb = nil
|
|
211
245
|
@negotiated_fm = nil
|
|
212
246
|
@negotiated_cmax = nil
|
|
@@ -219,12 +253,13 @@ module AsyncRabbitMQ
|
|
|
219
253
|
@heartbeat_task = nil
|
|
220
254
|
@channel0_task = nil # drains channel-0 queue; handles connection.blocked/unblocked
|
|
221
255
|
@recovery_task = nil
|
|
222
|
-
@
|
|
256
|
+
@background = nil # Async::Barrier per connection lifecycle; see spawn_background
|
|
257
|
+
@recovery_wakeup = Async::Notification.new # close pokes the retry sleep
|
|
223
258
|
@session_root_task = nil # top-level task; recovery is spawned here so it
|
|
224
259
|
# survives reader-task Cancel propagation
|
|
225
260
|
@on_blocked = nil
|
|
226
261
|
@on_unblocked = nil
|
|
227
|
-
@
|
|
262
|
+
@update_secret_promise = nil
|
|
228
263
|
@on_recovery_attempt = nil
|
|
229
264
|
@on_recovery = nil
|
|
230
265
|
@on_recovery_exhausted = nil
|
|
@@ -236,7 +271,23 @@ module AsyncRabbitMQ
|
|
|
236
271
|
# Raises NotOpenError if already connected.
|
|
237
272
|
def connect
|
|
238
273
|
raise NotOpenError, "Session is already connected" if open?
|
|
274
|
+
# :recovering (and a concurrent connect) must be refused too, not just
|
|
275
|
+
# :open. A connect racing the recovery loop would fight it for @frame_io
|
|
276
|
+
# and the background tasks — and when that connect failed (the broker
|
|
277
|
+
# being down is why recovery is running), cleanup_after_failed_connect
|
|
278
|
+
# would cancel the recovery task and mark the session closed, stranding
|
|
279
|
+
# every :recovering channel's parked fibers with nothing left that could
|
|
280
|
+
# ever release them. Close the session first to connect it afresh.
|
|
281
|
+
if @connecting || @recovery_in_progress || !closed?
|
|
282
|
+
doing = if @connecting then "connecting"
|
|
283
|
+
elsif !closed? then @state.to_s # :recovering, :closing
|
|
284
|
+
else "recovering" # recovery task still winding down
|
|
285
|
+
end
|
|
286
|
+
hint = @connecting ? "wait for the other connect to finish" : "close it first to force a fresh connection"
|
|
287
|
+
raise NotOpenError, "Session is #{doing}; #{hint}"
|
|
288
|
+
end
|
|
239
289
|
@connecting = true
|
|
290
|
+
attempt_started = true # read by the ensure below; nil if a guard raised
|
|
240
291
|
@closed_by_user = false # a previous failed connect must not disable recovery
|
|
241
292
|
@session_root_task = Async::Task.current
|
|
242
293
|
|
|
@@ -304,6 +355,16 @@ module AsyncRabbitMQ
|
|
|
304
355
|
else
|
|
305
356
|
raise ConnectionTimeoutError, "Could not connect to any host (tried #{tried}) — #{last_error&.message}"
|
|
306
357
|
end
|
|
358
|
+
ensure
|
|
359
|
+
# An exception the rescue clauses above never see can leave here with the
|
|
360
|
+
# attempt half-made: the caller's own with_timeout, its task being
|
|
361
|
+
# stopped (both arrive as non-StandardErrors at whatever yield point the
|
|
362
|
+
# handshake was parked on), or an error class outside the rescued list.
|
|
363
|
+
# @connecting stuck true would make the guard refuse every future
|
|
364
|
+
# connect — with close a no-op, permanently. Tear the half-made attempt
|
|
365
|
+
# down. attempt_started distinguishes our own flag from another fiber's:
|
|
366
|
+
# a guard raise above exits with it nil and must not stomp theirs.
|
|
367
|
+
cleanup_after_failed_connect if attempt_started && @connecting
|
|
307
368
|
end
|
|
308
369
|
|
|
309
370
|
def open?
|
|
@@ -317,18 +378,50 @@ module AsyncRabbitMQ
|
|
|
317
378
|
# Internal. Run a long-lived background loop (channel dispatch, heartbeat,
|
|
318
379
|
# channel-0 monitor).
|
|
319
380
|
#
|
|
320
|
-
#
|
|
321
|
-
#
|
|
322
|
-
#
|
|
323
|
-
#
|
|
324
|
-
#
|
|
325
|
-
#
|
|
381
|
+
# Infrastructure tasks: the frame reader and writer, heartbeat, channel-0
|
|
382
|
+
# monitor, recovery loop, channel dispatch loops and cancelled-consumer
|
|
383
|
+
# reconcilers. These must not become children of whichever task happened to
|
|
384
|
+
# open the channel or the session: a short-lived caller that finishes, or
|
|
385
|
+
# is stopped, would silently take its dispatch loop with it while the
|
|
386
|
+
# channel still reported itself open. Parent them at the reactor instead,
|
|
387
|
+
# and mark them transient so they never hold the reactor open by
|
|
388
|
+
# themselves.
|
|
389
|
+
#
|
|
390
|
+
# Every one is also registered in a per-lifecycle Async::Barrier, so #close
|
|
391
|
+
# can stop whatever the orderly teardown missed in one call — the class of
|
|
392
|
+
# leak the resync dispatch fiber once was — and a test can hold the barrier
|
|
393
|
+
# and assert nothing outlived the session.
|
|
326
394
|
#
|
|
327
395
|
# @api private
|
|
328
396
|
def spawn_background(&block)
|
|
329
|
-
#
|
|
397
|
+
# Refused after close (or a failed connect) until the next connect resets
|
|
398
|
+
# the flag. Without this the ||= below would quietly mint a fresh barrier
|
|
399
|
+
# and resurrect infrastructure on a closed session — every caller is
|
|
400
|
+
# gated today, but the guarantee belongs here, not in each of them.
|
|
401
|
+
# Callers tolerate nil (their task handles are all used through &.).
|
|
402
|
+
if @closed_by_user
|
|
403
|
+
@logger.debug(self, "Session closed: background task not started")
|
|
404
|
+
return nil
|
|
405
|
+
end
|
|
406
|
+
barrier = (@background ||= Async::Barrier.new)
|
|
407
|
+
# The barrier only sheds finished tasks in #wait, which nothing calls:
|
|
408
|
+
# sweep here instead, so a flapping connection's reader/heartbeat churn
|
|
409
|
+
# does not accumulate a node per task for the life of the session.
|
|
410
|
+
barrier.tasks.each { |node| barrier.tasks.remove?(node) if node.task.finished? }
|
|
411
|
+
# Parent looked up per call, never memoised: a Session reused across two
|
|
330
412
|
# separate Sync/Async reactors would otherwise keep spawning onto the
|
|
331
413
|
# first, finished one.
|
|
414
|
+
barrier.async(parent: Async::Task.current.root, transient: true, &block)
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
# Detached tasks: consumer-handler workers and application callbacks.
|
|
418
|
+
# Deliberately NOT in the barrier — a graceful #close lets workers finish
|
|
419
|
+
# the backlog they already hold (the broker considers auto-ack deliveries
|
|
420
|
+
# settled, so killing them loses messages), and an in-flight on_error/
|
|
421
|
+
# on_return callback is the application's code to finish, not ours to stop.
|
|
422
|
+
#
|
|
423
|
+
# @api private
|
|
424
|
+
def spawn_detached(&block)
|
|
332
425
|
Async::Task.current.root.async(transient: true, &block)
|
|
333
426
|
end
|
|
334
427
|
|
|
@@ -336,7 +429,7 @@ module AsyncRabbitMQ
|
|
|
336
429
|
def close
|
|
337
430
|
return if closed?
|
|
338
431
|
@closed_by_user = true
|
|
339
|
-
@recovery_wakeup
|
|
432
|
+
@recovery_wakeup.signal rescue nil
|
|
340
433
|
# Unblock any fibers waiting on channel replies (e.g. wait_for inside
|
|
341
434
|
# reopen_after_recovery) so that @recovery_task.cancel below can actually
|
|
342
435
|
# terminate the task rather than leaving it stuck on an Async::Condition.
|
|
@@ -351,6 +444,13 @@ module AsyncRabbitMQ
|
|
|
351
444
|
@channel0_task&.cancel rescue nil
|
|
352
445
|
@recovery_task&.cancel rescue nil
|
|
353
446
|
@frame_io&.stop rescue nil
|
|
447
|
+
# The catch-all, after the orderly teardown above: cancel every
|
|
448
|
+
# infrastructure task this lifecycle spawned — dispatch loops, reconcile
|
|
449
|
+
# loops, anything the targeted cancels missed. A cancelled barrier refuses
|
|
450
|
+
# new tasks, so it is dropped; the next connect starts a fresh one.
|
|
451
|
+
# Detached workers draining a backlog are deliberately not in it.
|
|
452
|
+
@background&.cancel rescue nil
|
|
453
|
+
@background = nil
|
|
354
454
|
@state = :closed
|
|
355
455
|
instrument("connection.closed") { { reason: :user, host: @host, port: @port } }
|
|
356
456
|
end
|
|
@@ -391,17 +491,39 @@ module AsyncRabbitMQ
|
|
|
391
491
|
def update_secret(new_secret, reason = "secret update")
|
|
392
492
|
raise NotOpenError, "Session is not open" unless open?
|
|
393
493
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
494
|
+
# One at a time. Two concurrent calls clobbered the shared reply slot:
|
|
495
|
+
# the first caller's ensure nilled the second's condition, both replies
|
|
496
|
+
# were dropped, both calls timed out — and @password was never updated
|
|
497
|
+
# although the broker had accepted the new secret, so the next reconnect
|
|
498
|
+
# authenticated with the stale one and recovery was abandoned for good.
|
|
499
|
+
@update_secret_sem.acquire do
|
|
500
|
+
raise NotOpenError, "Session is not open" unless open? # re-check after parking
|
|
398
501
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
502
|
+
begin
|
|
503
|
+
# A promise, registered before the write: write_frame can yield on a
|
|
504
|
+
# full write queue, and a reply resolved in that gap latches instead
|
|
505
|
+
# of being dropped (a Condition signalled with no waiter is a no-op).
|
|
506
|
+
promise = @update_secret_promise = Async::Promise.new
|
|
507
|
+
@frame_io.write_frame(AMQ::Protocol::Connection::UpdateSecret.encode(new_secret, reason).encode)
|
|
508
|
+
result = Async::Task.current.with_timeout(@rpc_timeout || RPC_TIMEOUT) { promise.wait }
|
|
509
|
+
raise result if result.is_a?(Exception)
|
|
510
|
+
|
|
511
|
+
@password = new_secret
|
|
512
|
+
true
|
|
513
|
+
rescue Async::TimeoutError
|
|
514
|
+
# No answer either way. The broker may well have applied the secret —
|
|
515
|
+
# the reply, not the request, may be what got lost — and with OAuth
|
|
516
|
+
# rotation the old token is the one about to expire, so reconnecting
|
|
517
|
+
# with it would strand the session. Keep the new secret for
|
|
518
|
+
# reconnects and say so.
|
|
519
|
+
@password = new_secret
|
|
520
|
+
@logger.warn(self, "connection.update-secret got no reply in #{@rpc_timeout || RPC_TIMEOUT}s; " \
|
|
521
|
+
"the new secret will be used for reconnects, its acceptance unconfirmed")
|
|
522
|
+
raise RpcTimeoutError, "No reply to connection.update-secret within #{@rpc_timeout || RPC_TIMEOUT}s"
|
|
523
|
+
ensure
|
|
524
|
+
@update_secret_promise = nil
|
|
525
|
+
end
|
|
526
|
+
end
|
|
405
527
|
end
|
|
406
528
|
|
|
407
529
|
# Check whether a queue exists on the broker without creating it.
|
|
@@ -513,9 +635,15 @@ module AsyncRabbitMQ
|
|
|
513
635
|
# Called by a channel when topology recovery re-declared a server-named
|
|
514
636
|
# queue under a new name: update the registry and every consumer of it.
|
|
515
637
|
def queue_renamed(old_name, new_name)
|
|
516
|
-
@logger.info("Server-named queue #{old_name} recovered as #{new_name}")
|
|
638
|
+
@logger.info(self, "Server-named queue #{old_name} recovered as #{new_name}")
|
|
517
639
|
@topology.rename_queue(old_name, new_name)
|
|
518
|
-
@channels.values.each
|
|
640
|
+
@channels.values.each do |ch|
|
|
641
|
+
ch.rename_consumer_queue(old_name, new_name)
|
|
642
|
+
# Before finish_recovery! replays them: an unconfirmed publish to this
|
|
643
|
+
# queue via the default exchange has the old name encoded in its kept
|
|
644
|
+
# frames, and replaying that is silently unroutable.
|
|
645
|
+
ch.rename_unconfirmed_queue(old_name, new_name)
|
|
646
|
+
end
|
|
519
647
|
end
|
|
520
648
|
|
|
521
649
|
# --- Async::Pool resource interface ---
|
|
@@ -569,7 +697,7 @@ module AsyncRabbitMQ
|
|
|
569
697
|
return
|
|
570
698
|
end
|
|
571
699
|
|
|
572
|
-
@logger.warn("Connection lost (#{error.class}: #{error.message}). Starting recovery...")
|
|
700
|
+
@logger.warn(self, "Connection lost (#{error.class}: #{error.message}). Starting recovery...")
|
|
573
701
|
|
|
574
702
|
if @recovery_in_progress
|
|
575
703
|
# Connection died again while a recovery attempt is in progress.
|
|
@@ -596,7 +724,7 @@ module AsyncRabbitMQ
|
|
|
596
724
|
# on the channels park until they are reopened after reconnect.
|
|
597
725
|
conn_error = ConnectionError.new(code: 0, text: "Connection lost: #{error.message}")
|
|
598
726
|
@channels.values.each { |ch| ch.mark_recovering!(conn_error) rescue nil }
|
|
599
|
-
@
|
|
727
|
+
@update_secret_promise&.resolve(conn_error)
|
|
600
728
|
# Tell the owner now, while the channels are still in the table: a
|
|
601
729
|
# Cluster in :drop mode gives them up here, before they are reopened.
|
|
602
730
|
connection_lost(error)
|
|
@@ -630,7 +758,7 @@ module AsyncRabbitMQ
|
|
|
630
758
|
def connection_lost(error)
|
|
631
759
|
@on_connection_lost&.call(self, error)
|
|
632
760
|
rescue => e
|
|
633
|
-
@logger.error("on_connection_lost callback failed: #{e.class}: #{e.message}")
|
|
761
|
+
@logger.error(self, "on_connection_lost callback failed: #{e.class}: #{e.message}")
|
|
634
762
|
end
|
|
635
763
|
|
|
636
764
|
# Return the address list in the order they should be tried for this
|
|
@@ -654,35 +782,69 @@ module AsyncRabbitMQ
|
|
|
654
782
|
@channel0_task&.cancel rescue nil
|
|
655
783
|
@frame_io&.stop rescue nil
|
|
656
784
|
@frame_io = nil
|
|
785
|
+
# Cancel whatever the half-made attempt spawned (reader/writer at least);
|
|
786
|
+
# the next connect starts a fresh barrier.
|
|
787
|
+
@background&.cancel rescue nil
|
|
788
|
+
@background = nil
|
|
657
789
|
@state = :closed
|
|
658
790
|
end
|
|
659
791
|
|
|
792
|
+
# Connect one host through io-endpoint, the connection layer the rest of
|
|
793
|
+
# the socketry stack (async-http, falcon) is built on. It resolves the
|
|
794
|
+
# host and tries the addresses in order, IPv6 included. They share one
|
|
795
|
+
# connect_timeout (the caller's with_timeout around this call and the
|
|
796
|
+
# handshake after it), so an address that silently drops packets can use
|
|
797
|
+
# up the budget before the next is tried — as TCPSocket.new under a fiber
|
|
798
|
+
# scheduler did before this, since it skips Happy Eyeballs there too.
|
|
799
|
+
#
|
|
800
|
+
# Sockets are created with TCP_NODELAY, as messaging clients
|
|
801
|
+
# conventionally are: an ack or a confirm should not sit behind Nagle's
|
|
802
|
+
# algorithm waiting on a delayed ACK.
|
|
660
803
|
def open_socket(target_host = @host, target_port = @port)
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
804
|
+
tcp = IO::Endpoint.tcp(target_host, target_port)
|
|
805
|
+
# Built before any socket exists, so a TLS configuration error (a bad
|
|
806
|
+
# certificate path, say) fails without opening anything to leak.
|
|
807
|
+
tls = tls_endpoint(tcp) if @tls
|
|
808
|
+
# io-endpoint closes the socket on ANY exception during the TCP connect,
|
|
809
|
+
# cancellation included.
|
|
810
|
+
socket = tcp.connect
|
|
811
|
+
socket = tls_handshake(tls, socket) if tls
|
|
812
|
+
# On the TCP socket itself; an SSL socket exposes it through #to_io.
|
|
813
|
+
apply_socket_timeouts(socket.respond_to?(:to_io) ? socket.to_io : socket)
|
|
814
|
+
socket
|
|
815
|
+
end
|
|
816
|
+
|
|
817
|
+
def tls_endpoint(tcp)
|
|
818
|
+
require "io/endpoint/ssl_endpoint"
|
|
819
|
+
# The SSL endpoint takes the hostname from the TCP endpoint, for SNI and
|
|
820
|
+
# certificate verification alike.
|
|
821
|
+
IO::Endpoint::SSLEndpoint.new(tcp, ssl_context: @tls_context || build_tls_context)
|
|
822
|
+
end
|
|
823
|
+
|
|
824
|
+
# The TLS handshake, run here rather than through SSLEndpoint#connect.
|
|
825
|
+
# That method closes the socket on a failed handshake with a bare
|
|
826
|
+
# `rescue`, which catches StandardError only: an Async::Cancel or
|
|
827
|
+
# Async::Stop arriving mid-handshake — #close cancelling a recovery that
|
|
828
|
+
# is retrying an amqps broker, or the caller's task being stopped — skips
|
|
829
|
+
# it, and with no frame_io yet there is nothing else to close the TCP
|
|
830
|
+
# socket until GC. The endpoint's pieces are still used: make_socket sets
|
|
831
|
+
# sync_close (or closing the TLS socket leaves the TCP one open, one
|
|
832
|
+
# leaked connection per amqps reconnect), and hostname drives SNI and
|
|
833
|
+
# certificate verification.
|
|
834
|
+
def tls_handshake(endpoint, tcp_socket)
|
|
835
|
+
socket = tcp_socket
|
|
836
|
+
socket = endpoint.make_socket(tcp_socket)
|
|
837
|
+
if (name = endpoint.hostname)
|
|
838
|
+
socket.hostname = name
|
|
685
839
|
end
|
|
840
|
+
socket.connect
|
|
841
|
+
socket
|
|
842
|
+
rescue Exception # rubocop:disable Lint/RescueException
|
|
843
|
+
# Any exit but success, cancellation included. Closing the TLS socket
|
|
844
|
+
# closes the TCP one through sync_close; if make_socket itself raised,
|
|
845
|
+
# `socket` is still the TCP socket.
|
|
846
|
+
socket&.close rescue nil
|
|
847
|
+
raise
|
|
686
848
|
end
|
|
687
849
|
|
|
688
850
|
# Bound how long the kernel will retransmit unacknowledged data before it
|
|
@@ -702,7 +864,7 @@ module AsyncRabbitMQ
|
|
|
702
864
|
sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_USER_TIMEOUT, millis)
|
|
703
865
|
rescue StandardError => e
|
|
704
866
|
# Unsupported on this platform or socket type; the heartbeat still covers us.
|
|
705
|
-
@logger.debug("Could not set TCP_USER_TIMEOUT: #{e.class}: #{e.message}")
|
|
867
|
+
@logger.debug(self, "Could not set TCP_USER_TIMEOUT: #{e.class}: #{e.message}")
|
|
706
868
|
end
|
|
707
869
|
|
|
708
870
|
def build_tls_context
|
|
@@ -734,14 +896,18 @@ module AsyncRabbitMQ
|
|
|
734
896
|
start.mechanisms,
|
|
735
897
|
preferred: @auth_mechanism,
|
|
736
898
|
username: @username,
|
|
737
|
-
password: @password
|
|
899
|
+
password: @password,
|
|
900
|
+
# Certificate material means this connection can be identified by its
|
|
901
|
+
# cert, and the password is usually the untouched guest default: let
|
|
902
|
+
# EXTERNAL outrank PLAIN then, and only then.
|
|
903
|
+
prefer_external: !(@tls_cert || @tls_context).nil?
|
|
738
904
|
)
|
|
739
905
|
send_connection_start_ok(sasl)
|
|
740
906
|
|
|
741
907
|
# connection.tune (broker may send connection.secure challenges first)
|
|
742
908
|
msg = wait_channel0_method(AMQ::Protocol::Connection::Tune, AMQ::Protocol::Connection::Secure)
|
|
743
909
|
while msg.is_a?(AMQ::Protocol::Connection::Secure)
|
|
744
|
-
@logger.debug("Received connection.secure SASL challenge for #{sasl.mechanism_name}")
|
|
910
|
+
@logger.debug(self, "Received connection.secure SASL challenge for #{sasl.mechanism_name}")
|
|
745
911
|
@frame_io.write_frame(AMQ::Protocol::Connection::SecureOk.encode(sasl.challenge_response(msg.challenge)).encode)
|
|
746
912
|
msg = wait_channel0_method(AMQ::Protocol::Connection::Tune, AMQ::Protocol::Connection::Secure)
|
|
747
913
|
end
|
|
@@ -843,7 +1009,7 @@ module AsyncRabbitMQ
|
|
|
843
1009
|
unwritten = @frame_io&.pending_writes.to_i
|
|
844
1010
|
return unless unwritten.positive?
|
|
845
1011
|
|
|
846
|
-
@logger.warn("Close discarded #{unwritten} queued write(s) (#{e.class})")
|
|
1012
|
+
@logger.warn(self, "Close discarded #{unwritten} queued write(s) (#{e.class})")
|
|
847
1013
|
end
|
|
848
1014
|
|
|
849
1015
|
def negotiate_heartbeat(broker_hb)
|
|
@@ -950,7 +1116,7 @@ module AsyncRabbitMQ
|
|
|
950
1116
|
|
|
951
1117
|
# Check retry limit (nil = unlimited)
|
|
952
1118
|
if @recovery_attempts && attempts > @recovery_attempts
|
|
953
|
-
@logger.warn("Recovery exhausted after #{@recovery_attempts} attempt(s)")
|
|
1119
|
+
@logger.warn(self, "Recovery exhausted after #{@recovery_attempts} attempt(s)")
|
|
954
1120
|
@state = :closed
|
|
955
1121
|
@recovery_in_progress = false
|
|
956
1122
|
exhausted = ConnectionError.new(code: 0, text: "Recovery exhausted after #{@recovery_attempts} attempt(s)")
|
|
@@ -963,16 +1129,18 @@ module AsyncRabbitMQ
|
|
|
963
1129
|
jitter = delay * RECOVERY_JITTER * (rand * 2 - 1)
|
|
964
1130
|
wait_secs = delay + jitter
|
|
965
1131
|
|
|
966
|
-
# Sleep until the delay expires OR session.close signals
|
|
967
|
-
|
|
1132
|
+
# Sleep until the delay expires OR session.close signals the wakeup.
|
|
1133
|
+
# An Async::Notification — the purpose-built "poke a sleeping loop"
|
|
1134
|
+
# primitive — created once in the constructor; a signal with nobody
|
|
1135
|
+
# sleeping is a no-op, and the loop's own @closed_by_user check covers
|
|
1136
|
+
# that case on its next pass.
|
|
968
1137
|
Async::Task.current.with_timeout(wait_secs) do
|
|
969
1138
|
@recovery_wakeup.wait
|
|
970
|
-
end rescue nil # TimeoutError is normal
|
|
971
|
-
@recovery_wakeup = nil
|
|
1139
|
+
end rescue nil # TimeoutError is normal
|
|
972
1140
|
|
|
973
1141
|
break if @closed_by_user
|
|
974
1142
|
|
|
975
|
-
@logger.info("Recovery attempt #{attempts} (delay was #{delay.round(1)}s)...")
|
|
1143
|
+
@logger.info(self, "Recovery attempt #{attempts} (delay was #{delay.round(1)}s)...")
|
|
976
1144
|
instrument("recovery.attempt") { { attempt: attempts, delay: wait_secs } }
|
|
977
1145
|
@on_recovery_attempt&.call(attempts)
|
|
978
1146
|
|
|
@@ -995,7 +1163,7 @@ module AsyncRabbitMQ
|
|
|
995
1163
|
# The credentials no longer work; retrying cannot help.
|
|
996
1164
|
@frame_io&.stop rescue nil
|
|
997
1165
|
@frame_io = nil
|
|
998
|
-
@logger.error("Recovery abandoned: #{e.message}")
|
|
1166
|
+
@logger.error(self, "Recovery abandoned: #{e.message}")
|
|
999
1167
|
@state = :closed
|
|
1000
1168
|
@recovery_in_progress = false
|
|
1001
1169
|
@channels.values.each { |ch| ch.mark_closed!(e) rescue nil }
|
|
@@ -1005,7 +1173,7 @@ module AsyncRabbitMQ
|
|
|
1005
1173
|
return
|
|
1006
1174
|
rescue => e
|
|
1007
1175
|
@frame_io&.stop rescue nil
|
|
1008
|
-
@logger.debug("Recovery: #{target_host}:#{target_port} failed — #{e.class}: #{e.message}")
|
|
1176
|
+
@logger.debug(self, "Recovery: #{target_host}:#{target_port} failed — #{e.class}: #{e.message}")
|
|
1009
1177
|
end
|
|
1010
1178
|
end
|
|
1011
1179
|
|
|
@@ -1023,7 +1191,7 @@ module AsyncRabbitMQ
|
|
|
1023
1191
|
# that session.close can still cancel this task (and therefore interrupt
|
|
1024
1192
|
# any wait_for calls inside reopen_after_recovery) if the user closes
|
|
1025
1193
|
# the session while channels are being reopened.
|
|
1026
|
-
@logger.info("Recovery successful after #{attempts} attempt(s)")
|
|
1194
|
+
@logger.info(self, "Recovery successful after #{attempts} attempt(s)")
|
|
1027
1195
|
|
|
1028
1196
|
# Re-open channels and re-register consumers. @recovery_in_progress
|
|
1029
1197
|
# stays true across this: clearing it first leaves a window where a
|
|
@@ -1036,7 +1204,7 @@ module AsyncRabbitMQ
|
|
|
1036
1204
|
# this half-built connection down first. Leaving it up reported the
|
|
1037
1205
|
# session as open (so a Cluster would place new channels on a dead
|
|
1038
1206
|
# node), held the socket, and leaked a channel-0 monitor per flap.
|
|
1039
|
-
@logger.warn("Connection lost while reopening channels; retrying recovery")
|
|
1207
|
+
@logger.warn(self, "Connection lost while reopening channels; retrying recovery")
|
|
1040
1208
|
@state = :recovering
|
|
1041
1209
|
@heartbeat_task&.cancel rescue nil
|
|
1042
1210
|
@heartbeat_task = nil
|
|
@@ -1050,13 +1218,16 @@ module AsyncRabbitMQ
|
|
|
1050
1218
|
@recovery_in_progress = false
|
|
1051
1219
|
instrument("recovery.succeeded") do
|
|
1052
1220
|
{ attempts: attempts, host: @host, port: @port, channels: @channels.size,
|
|
1221
|
+
# false when the topology replay stopped early; the details went
|
|
1222
|
+
# out on recovery.topology_incomplete as it happened.
|
|
1223
|
+
topology_complete: @topology_replay_failure.nil?,
|
|
1053
1224
|
duration: recovery_started_at ? instrument_elapsed(recovery_started_at) : nil }
|
|
1054
1225
|
end
|
|
1055
1226
|
@on_recovery&.call(self)
|
|
1056
1227
|
@recovery_task = nil
|
|
1057
1228
|
return
|
|
1058
1229
|
else
|
|
1059
|
-
@logger.warn("Recovery attempt #{attempts} failed: no reachable host")
|
|
1230
|
+
@logger.warn(self, "Recovery attempt #{attempts} failed: no reachable host")
|
|
1060
1231
|
delay = [delay * 2, @recovery_max_interval].min
|
|
1061
1232
|
break if @closed_by_user
|
|
1062
1233
|
end
|
|
@@ -1084,14 +1255,15 @@ module AsyncRabbitMQ
|
|
|
1084
1255
|
return false if @recovery_interrupted
|
|
1085
1256
|
|
|
1086
1257
|
# Fail the channel loudly rather than leave its parked callers hanging.
|
|
1087
|
-
@logger.error("Channel #{channel.channel_id} could not be reopened after recovery: #{e.class}: #{e.message}")
|
|
1258
|
+
@logger.error(self, "Channel #{channel.channel_id} could not be reopened after recovery: #{e.class}: #{e.message}")
|
|
1088
1259
|
channel.mark_closed!(ChannelError.new("Channel could not be reopened after recovery: #{e.message}",
|
|
1089
1260
|
channel_id: channel.channel_id))
|
|
1090
1261
|
channel_closed(channel.channel_id)
|
|
1091
1262
|
end
|
|
1092
1263
|
end
|
|
1093
1264
|
|
|
1094
|
-
|
|
1265
|
+
@topology_replay_failure = nil
|
|
1266
|
+
@topology_replay_failure = recover_topology_on(reopened) if @recover_topology && !@topology.empty?
|
|
1095
1267
|
return false if @recovery_interrupted
|
|
1096
1268
|
|
|
1097
1269
|
reopened.each { |channel| channel.finish_recovery! rescue nil }
|
|
@@ -1100,22 +1272,67 @@ module AsyncRabbitMQ
|
|
|
1100
1272
|
|
|
1101
1273
|
# Re-declare exchanges, then queues, then bindings. Each entity is replayed
|
|
1102
1274
|
# on the channel that declared it if that channel is still open, otherwise
|
|
1103
|
-
# on a temporary channel.
|
|
1275
|
+
# on a temporary channel. A broker rejection of one entity does not stop
|
|
1276
|
+
# the others (recover_entity handles it per entity, reopening the channel).
|
|
1277
|
+
#
|
|
1278
|
+
# Returns nil when everything was replayed. A harder failure — an
|
|
1279
|
+
# RpcTimeoutError from a broker that stopped answering, a ConnectionError
|
|
1280
|
+
# from another drop — would cost a full timeout per remaining entity, so
|
|
1281
|
+
# the replay stops there; but what is missing is now REPORTED, not just
|
|
1282
|
+
# logged: the return value carries the failed entity and the skip count,
|
|
1283
|
+
# recover_loop puts topology_complete: false in recovery.succeeded, and a
|
|
1284
|
+
# recovery.topology_incomplete event names the details. Previously this
|
|
1285
|
+
# aborted silently and recovery still looked fully successful.
|
|
1104
1286
|
def recover_topology_on(channels)
|
|
1105
1287
|
by_id = channels.to_h { |ch| [ch.channel_id, ch] }
|
|
1106
1288
|
temp = nil
|
|
1107
1289
|
on = ->(channel_id) { by_id[channel_id] || (temp ||= open_channel) }
|
|
1108
1290
|
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1291
|
+
entities =
|
|
1292
|
+
@topology.exchanges.map { |x| [:exchange, x] } +
|
|
1293
|
+
@topology.queues.map { |q| [:queue, q] } +
|
|
1294
|
+
@topology.queue_bindings.map { |b| [:queue_binding, b] } +
|
|
1295
|
+
@topology.exchange_bindings.map { |b| [:exchange_binding, b] }
|
|
1296
|
+
|
|
1297
|
+
entities.each_with_index do |(kind, entity), index|
|
|
1298
|
+
begin
|
|
1299
|
+
channel = on.call(entity.channel_id)
|
|
1300
|
+
case kind
|
|
1301
|
+
when :exchange then channel.recover_exchange(entity)
|
|
1302
|
+
when :queue then channel.recover_queue(entity)
|
|
1303
|
+
when :queue_binding then channel.recover_queue_binding(entity)
|
|
1304
|
+
when :exchange_binding then channel.recover_exchange_binding(entity)
|
|
1305
|
+
end
|
|
1306
|
+
rescue => e
|
|
1307
|
+
# A drop mid-replay is not an incomplete replay: reopen_channels
|
|
1308
|
+
# returns false on @recovery_interrupted and the whole recovery runs
|
|
1309
|
+
# again, replaying everything. Emitting here would page a false
|
|
1310
|
+
# alarm once per connection flap.
|
|
1311
|
+
return nil if @recovery_interrupted
|
|
1312
|
+
|
|
1313
|
+
skipped = entities.size - index - 1
|
|
1314
|
+
failure = { kind: kind, entity: describe_entity(kind, entity),
|
|
1315
|
+
error: e.class.name, message: e.message,
|
|
1316
|
+
replayed: index, skipped: skipped }
|
|
1317
|
+
@logger.error(self, "Topology replay stopped at #{kind} #{failure[:entity]} " \
|
|
1318
|
+
"(#{e.class}: #{e.message}); #{index} replayed, #{skipped} skipped")
|
|
1319
|
+
instrument("recovery.topology_incomplete") { failure }
|
|
1320
|
+
return failure
|
|
1321
|
+
end
|
|
1322
|
+
end
|
|
1323
|
+
nil
|
|
1115
1324
|
ensure
|
|
1116
1325
|
temp&.close rescue nil
|
|
1117
1326
|
end
|
|
1118
1327
|
|
|
1328
|
+
def describe_entity(kind, entity)
|
|
1329
|
+
case kind
|
|
1330
|
+
when :exchange, :queue then entity.name
|
|
1331
|
+
when :queue_binding then "#{entity.exchange} -> #{entity.queue} (#{entity.routing_key})"
|
|
1332
|
+
else "#{entity.source} -> #{entity.destination} (#{entity.routing_key})"
|
|
1333
|
+
end
|
|
1334
|
+
end
|
|
1335
|
+
|
|
1119
1336
|
|
|
1120
1337
|
# Dedicated long-lived task that drains the channel-0 queue after the
|
|
1121
1338
|
# AMQP handshake completes. Handles connection.blocked / connection.unblocked
|
|
@@ -1145,17 +1362,17 @@ module AsyncRabbitMQ
|
|
|
1145
1362
|
instrument("connection.unblocked") { {} }
|
|
1146
1363
|
@on_unblocked&.call
|
|
1147
1364
|
when AMQ::Protocol::Connection::UpdateSecretOk
|
|
1148
|
-
@
|
|
1365
|
+
@update_secret_promise&.resolve(method)
|
|
1149
1366
|
when AMQ::Protocol::Connection::Close
|
|
1150
1367
|
# FrameIO has already answered with close-ok and triggered recovery;
|
|
1151
1368
|
# fail a pending update_secret with the broker's reason.
|
|
1152
|
-
@
|
|
1369
|
+
@update_secret_promise&.resolve(ConnectionError.new(code: method.reply_code, text: method.reply_text))
|
|
1153
1370
|
end
|
|
1154
1371
|
# Other channel-0 methods during normal operation are intentionally
|
|
1155
1372
|
# ignored; the handshake uses wait_channel0_method, not this loop.
|
|
1156
1373
|
end
|
|
1157
1374
|
rescue => e
|
|
1158
|
-
@logger.debug("Channel-0 monitor exited: #{e.class}: #{e.message}")
|
|
1375
|
+
@logger.debug(self, "Channel-0 monitor exited: #{e.class}: #{e.message}")
|
|
1159
1376
|
end
|
|
1160
1377
|
end
|
|
1161
1378
|
end
|