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.
@@ -73,7 +73,9 @@ module AsyncRabbitMQ
73
73
 
74
74
  @on_node_down_policy = on_node_down
75
75
  @clear_topology_on_drop = clear_topology_on_drop
76
- @logger = session_opts[:logger] || Log.new
76
+ # Resolved once; Sessions resolve it again, which is a no-op on an
77
+ # already-adapted logger. A key present with nil means discard.
78
+ @logger = Logging.resolve(session_opts.fetch(:logger, Console))
77
79
  @notifier = session_opts[:notifier] || Notifier.new(logger: @logger)
78
80
  if (instrumenter = session_opts[:instrumenter])
79
81
  @notifier.subscribe { |name, payload| instrumenter.call(name, payload) }
@@ -93,8 +95,9 @@ module AsyncRabbitMQ
93
95
  end
94
96
 
95
97
  @closed = true
96
- @supervisors = {} # session => the task connecting it, until it is up
98
+ @supervisor_barrier = nil # Async::Barrier over the per-node supervisors, per connect
97
99
  @wakeups = {} # session => Async::Condition, to cut a retry sleep short on close
100
+ @connect_condition = nil # set while #connect waits for first reports
98
101
  @on_node_down = @on_node_up = @on_connection_lost = nil
99
102
  @on_blocked = @on_unblocked = @on_recovery_attempt = @on_recovery = @on_recovery_exhausted = nil
100
103
  end
@@ -122,15 +125,23 @@ module AsyncRabbitMQ
122
125
  @closed = false
123
126
  pending = @sessions.size
124
127
  errors = {}
125
- reported = Async::Condition.new
128
+ # Held in an ivar, not just a local, so #close can wake this connect from
129
+ # another fiber. Without that, close stops the supervisors before they
130
+ # report their first attempt, pending never reaches zero, and the fiber
131
+ # here parks on reported.wait for the life of the reactor.
132
+ reported = @connect_condition = Async::Condition.new
126
133
  # Parent the per-node supervisors at the reactor, not at whichever task
127
134
  # called connect. A caller that finishes, or is stopped, would otherwise
128
135
  # take every node's supervisor down with it — and with them the retry
129
136
  # loop that brings a node back — without raising anything. Transient so
130
137
  # they never hold the reactor open on their own; #close stops them.
131
138
  root = Async::Task.current.root
139
+ # One barrier over all the node supervisors, fresh per connect (a cancelled
140
+ # barrier refuses new tasks): #close stops the lot in one call instead of
141
+ # bookkeeping a task per session.
142
+ barrier = @supervisor_barrier = Async::Barrier.new
132
143
  @sessions.each do |session|
133
- @supervisors[session] = root.async(transient: true) do
144
+ barrier.async(parent: root, transient: true) do
134
145
  supervise(session) do |error|
135
146
  errors[session] = error
136
147
  pending -= 1
@@ -139,14 +150,23 @@ module AsyncRabbitMQ
139
150
  end
140
151
  end
141
152
 
142
- loop do
143
- if (refused = errors.values.find { |e| e.is_a?(AuthenticationError) })
144
- close
145
- raise refused
153
+ begin
154
+ loop do
155
+ if (refused = errors.values.find { |e| e.is_a?(AuthenticationError) })
156
+ close
157
+ raise refused
158
+ end
159
+ break if pending.zero?
160
+ # A concurrent close stops the supervisors and signals this; bail out
161
+ # rather than wait for reports that are no longer coming.
162
+ break if @closed
163
+ reported.wait
164
+ break if @closed
146
165
  end
147
- break if pending.zero?
148
- reported.wait
166
+ ensure
167
+ @connect_condition = nil
149
168
  end
169
+ raise NotOpenError, "Cluster was closed during connect" if @closed
150
170
  return if open?
151
171
 
152
172
  close
@@ -168,13 +188,15 @@ module AsyncRabbitMQ
168
188
  def close
169
189
  return if @closed
170
190
  @closed = true
191
+ # Wake a connect parked waiting for first reports; it re-checks @closed.
192
+ @connect_condition&.signal rescue nil
171
193
  @sessions.each { |s| s.close rescue nil }
172
194
  @wakeups.values.each { |c| c.signal rescue nil }
173
195
  # The supervisors are parented at the reactor, so dropping the references
174
196
  # would not stop them; a node still in its retry backoff would keep
175
197
  # reconnecting after the cluster was closed.
176
- @supervisors.each_value { |task| task.stop rescue nil }
177
- @supervisors.clear
198
+ @supervisor_barrier&.cancel rescue nil
199
+ @supervisor_barrier = nil
178
200
  end
179
201
 
180
202
  # Open a channel on the connected node with the fewest channels.
@@ -354,7 +376,7 @@ module AsyncRabbitMQ
354
376
  end
355
377
  return if error.is_a?(AuthenticationError)
356
378
 
357
- @logger.warn("Node #{session.host}:#{session.port} unreachable (#{error.class}: #{error.message}); " \
379
+ @logger.warn(self, "Node #{session.host}:#{session.port} unreachable (#{error.class}: #{error.message}); " \
358
380
  "next attempt in #{delay.round(1)}s")
359
381
  wait_for(session, delay)
360
382
  delay = [delay * 2, @retry_max_interval].min
@@ -365,7 +387,7 @@ module AsyncRabbitMQ
365
387
  session.connect
366
388
  nil
367
389
  rescue AuthenticationError => e
368
- @logger.error("Node #{session.host}:#{session.port} refused the credentials: #{e.message}")
390
+ @logger.error(self, "Node #{session.host}:#{session.port} refused the credentials: #{e.message}")
369
391
  e
370
392
  rescue Error, SystemCallError, IOError => e
371
393
  e
@@ -395,10 +417,21 @@ module AsyncRabbitMQ
395
417
  else @on_node_down_policy.call(session, channels, error)
396
418
  end
397
419
  rescue => e
398
- @logger.error("on_node_down failed for #{session.host}:#{session.port}: #{e.class}: #{e.message}")
420
+ @logger.error(self, "on_node_down failed for #{session.host}:#{session.port}: #{e.class}: #{e.message}")
421
+ end
422
+ # Each callback is isolated: a raising on_connection_lost must not skip
423
+ # notify_node_down, which under :drop is the only chance to see the
424
+ # messages the lost node never confirmed (they are gone after drop_channels).
425
+ begin
426
+ @on_connection_lost&.call(session, error)
427
+ rescue => e
428
+ @logger.error(self, "on_connection_lost failed for #{session.host}:#{session.port}: #{e.class}: #{e.message}")
429
+ end
430
+ begin
431
+ notify_node_down(session, channels, error, unconfirmed)
432
+ rescue => e
433
+ @logger.error(self, "on_node_down callback failed for #{session.host}:#{session.port}: #{e.class}: #{e.message}")
399
434
  end
400
- @on_connection_lost&.call(session, error)
401
- notify_node_down(session, channels, error, unconfirmed)
402
435
  end
403
436
 
404
437
  # on_node_down took three arguments before unconfirmed messages were passed
@@ -420,14 +453,14 @@ module AsyncRabbitMQ
420
453
  # bindings stay recorded: if this node comes back from an empty data
421
454
  # directory they still need re-declaring.
422
455
  session.topology.clear_transient if @clear_topology_on_drop
423
- @logger.info("Dropped #{channels.size} channel(s) on #{session.host}:#{session.port}")
456
+ @logger.info(self, "Dropped #{channels.size} channel(s) on #{session.host}:#{session.port}")
424
457
  end
425
458
 
426
459
  def node_up(session)
427
- @logger.info("Node #{session.host}:#{session.port} connected")
460
+ @logger.info(self, "Node #{session.host}:#{session.port} connected")
428
461
  @on_node_up&.call(session)
429
462
  rescue => e
430
- @logger.error("on_node_up failed for #{session.host}:#{session.port}: #{e.class}: #{e.message}")
463
+ @logger.error(self, "on_node_up failed for #{session.host}:#{session.port}: #{e.class}: #{e.message}")
431
464
  end
432
465
  end
433
466
  end
@@ -1,6 +1,7 @@
1
1
  require "async"
2
2
  require "async/queue"
3
3
  require "async/limited_queue"
4
+ require "async/promise"
4
5
  require "async/semaphore"
5
6
  require "socket"
6
7
  require "amq/protocol"
@@ -28,9 +29,9 @@ module AsyncRabbitMQ
28
29
  # 403 access-refused, 404 not-found, 405 resource-locked, 406 precondition-failed.
29
30
  SOFT_ERROR_CODES = [311, 312, 313, 403, 404, 405, 406].freeze
30
31
 
31
- def initialize(socket, logger: Log.new)
32
+ def initialize(socket, logger: Console)
32
33
  @socket = socket
33
- @logger = logger
34
+ @logger = Logging.resolve(logger)
34
35
  @channels = {}
35
36
  @channel_sem = Async::Semaphore.new(1)
36
37
  @write_queue = Async::LimitedQueue.new(WRITE_QUEUE_LIMIT)
@@ -41,7 +42,7 @@ module AsyncRabbitMQ
41
42
  @content_state = {}
42
43
  @on_frame = nil # optional proc called each time a frame is read
43
44
  @blocked = false
44
- @unblocked_condition = nil
45
+ @unblocked_promise = nil # per blocked episode; see write_frame
45
46
  end
46
47
 
47
48
  # Set a callback invoked immediately after each frame is successfully read.
@@ -84,6 +85,13 @@ module AsyncRabbitMQ
84
85
  # Publishers parked on the connection.blocked gate can never proceed now.
85
86
  @blocked = false
86
87
  release_blocked_writers(ConnectionError.new(code: 0, text: "Connection closed while blocked by the broker"))
88
+ # Close the write queue. A publisher parked on a full queue is woken only
89
+ # by a pop, a close, or nothing at all: the writer that pops is about to
90
+ # be cancelled, so without this the publisher stays parked forever — and
91
+ # it is holding its channel's publish semaphore, which bricks the channel
92
+ # for every publish after recovery. Closing wakes it; write_frame turns
93
+ # the ClosedError into the no-op these writes already were (see there).
94
+ @write_queue.close rescue nil
87
95
  # Push nil sentinel to every channel queue FIRST so blocked poppers
88
96
  # (e.g. wait_channel0_method) are unblocked before we cancel tasks.
89
97
  # Cancelling the CURRENT task raises Async::Cancel (< Exception, not
@@ -103,25 +111,40 @@ module AsyncRabbitMQ
103
111
  def write_frame(data, publish: false)
104
112
  if publish
105
113
  while @blocked
106
- @unblocked_condition ||= Async::Condition.new
107
- outcome = @unblocked_condition.wait
114
+ # One promise per blocked episode, created lazily by the first
115
+ # waiter (set_blocked only flips the flag). A latch: a publisher
116
+ # arriving between the unblock resolving and the flag flipping gets
117
+ # the same answer immediately instead of parking on a spent signal.
118
+ outcome = (@unblocked_promise ||= Async::Promise.new).wait
108
119
  raise outcome if outcome.is_a?(Exception)
109
120
  end
110
121
  end
111
122
  @write_queue.push(data)
123
+ rescue Async::Queue::ClosedError
124
+ # The connection was stopped while this write was parked on (or racing)
125
+ # the queue. Writing to a stopped connection has always been a silent
126
+ # no-op — the bytes were enqueued to a queue nobody would ever drain —
127
+ # so a write that loses that race stays one. Returning rather than
128
+ # raising is load-bearing: a confirm-mode publisher reserves its confirm
129
+ # tag AFTER this call returns, and that reservation is what gets the
130
+ # message replayed on the recovered channel. A publish without confirms
131
+ # is fire-and-forget by contract. The point of the close is to get here
132
+ # at all instead of parking forever.
133
+ @logger.debug(self, "FrameIO: write after stop discarded (#{data.bytesize} bytes)")
134
+ nil
112
135
  end
113
136
 
114
137
  # Called by the Session channel-0 monitor when connection.blocked is received.
115
138
  def set_blocked(reason)
116
139
  @blocked = true
117
- @logger.warn("Connection blocked: #{reason}")
140
+ @logger.warn(self, "Connection blocked: #{reason}")
118
141
  end
119
142
 
120
143
  # Called by the Session channel-0 monitor when connection.unblocked is received.
121
144
  def set_unblocked
122
145
  @blocked = false
123
146
  release_blocked_writers
124
- @logger.info("Connection unblocked")
147
+ @logger.info(self, "Connection unblocked")
125
148
  end
126
149
 
127
150
  def blocked?
@@ -151,14 +174,15 @@ module AsyncRabbitMQ
151
174
  # Wake every publisher waiting on the blocked gate. With +outcome+ nil they
152
175
  # re-check the gate; with an exception they raise it.
153
176
  def release_blocked_writers(outcome = nil)
154
- cond = @unblocked_condition
155
- @unblocked_condition = nil
156
- cond&.signal(outcome)
177
+ promise = @unblocked_promise
178
+ @unblocked_promise = nil
179
+ promise&.resolve(outcome)
157
180
  end
158
181
 
159
182
  def writer_loop
160
183
  while @running
161
184
  data = @write_queue.pop
185
+ break if data.nil? # queue closed by #stop
162
186
  @socket_sem.acquire { @socket.write(data) }
163
187
  end
164
188
  rescue IOError, Errno::EPIPE, Errno::EBADF, Errno::ECONNRESET
@@ -166,7 +190,7 @@ module AsyncRabbitMQ
166
190
  rescue => e
167
191
  # The writer is gone either way; without recovery every publisher would
168
192
  # block forever once the write queue fills, with nothing to drain it.
169
- @logger.error("FrameIO writer: #{e.class}: #{e.message}")
193
+ @logger.error(self, "FrameIO writer: #{e.class}: #{e.message}")
170
194
  trigger_recovery(e) if @running
171
195
  end
172
196
 
@@ -178,17 +202,17 @@ module AsyncRabbitMQ
178
202
  end
179
203
  rescue EOFError, Errno::ECONNRESET, Errno::EPIPE, IOError, Errno::EBADF => e
180
204
  if @running
181
- @logger.warn("FrameIO reader closed: #{e.class}")
205
+ @logger.warn(self, "FrameIO reader closed: #{e.class}")
182
206
  trigger_recovery(e)
183
207
  else
184
208
  # #stop closed the socket under us: an orderly shutdown, not a failure.
185
- @logger.debug("FrameIO reader stopped (#{e.class})")
209
+ @logger.debug(self, "FrameIO reader stopped (#{e.class})")
186
210
  end
187
211
  rescue AMQ::Protocol::Error => e
188
- @logger.error("FrameIO AMQP error: #{e.class}: #{e.message}")
212
+ @logger.error(self, "FrameIO AMQP error: #{e.class}: #{e.message}")
189
213
  trigger_recovery(e)
190
214
  rescue => e
191
- @logger.error("FrameIO reader error: #{e.class}: #{e.message}")
215
+ @logger.error(self, "FrameIO reader error: #{e.class}: #{e.message}")
192
216
  trigger_recovery(e)
193
217
  end
194
218
 
@@ -242,7 +266,7 @@ module AsyncRabbitMQ
242
266
  @socket.write(AMQ::Protocol::Connection::CloseOk.encode.encode)
243
267
  end
244
268
  rescue => e
245
- @logger.warn("FrameIO: could not send Connection::CloseOk — #{e.message}")
269
+ @logger.warn(self, "FrameIO: could not send Connection::CloseOk — #{e.message}")
246
270
  end
247
271
  route_to_channel(0, [:method, method])
248
272
  trigger_recovery(
@@ -271,7 +295,7 @@ module AsyncRabbitMQ
271
295
  when AMQ::Protocol::BodyFrame
272
296
  state = @content_state[channel_id]
273
297
  unless state
274
- @logger.warn("Body frame on channel #{channel_id} without content header — dropped")
298
+ @logger.warn(self, "Body frame on channel #{channel_id} without content header — dropped")
275
299
  return
276
300
  end
277
301
  chunk = frame_obj.payload
@@ -288,7 +312,7 @@ module AsyncRabbitMQ
288
312
  route_to_channel(0, [:heartbeat])
289
313
 
290
314
  else
291
- @logger.warn("Unknown frame type #{frame_obj.class} on channel #{channel_id} — dropped")
315
+ @logger.warn(self, "Unknown frame type #{frame_obj.class} on channel #{channel_id} — dropped")
292
316
  end
293
317
  end
294
318
 
@@ -297,7 +321,7 @@ module AsyncRabbitMQ
297
321
  if queue
298
322
  queue.push(message)
299
323
  else
300
- @logger.debug("No queue for channel #{channel_id} — frame dropped (#{message.first})")
324
+ @logger.debug(self, "No queue for channel #{channel_id} — frame dropped (#{message.first})")
301
325
  end
302
326
  end
303
327
 
@@ -1,7 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AsyncRabbitMQ
4
- # The default logger: warnings and errors, one line each, to $stderr.
4
+ # A minimal logger: warnings and errors, one line each, to $stderr. Not the
5
+ # default - the client logs through Console unless given +logger:+ (see
6
+ # AsyncRabbitMQ::Logging) - but a plain destination for when you want one
7
+ # without the logger gem.
5
8
  #
6
9
  # Anything that responds to +debug+, +info+, +warn+ and +error+ can be passed
7
10
  # as +logger:+ instead, and that is the expected thing to do in an
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsyncRabbitMQ
4
+ # Every log call in this gem has Console's shape: the object doing the
5
+ # logging, then the message —
6
+ #
7
+ # @logger.warn(self, "Connection lost ...")
8
+ #
9
+ # — and +@logger+ is an adapter Logging.resolve made from the +logger:+ the
10
+ # caller passed. Each session gets its own adapter object; nothing shared is
11
+ # ever handed out, so patching a session's logger cannot reach another.
12
+ #
13
+ # [Console (the default)] forwarded to Console with the subject kept, so
14
+ # Console's per-class filtering, CONSOLE_LEVEL and its fiber-local
15
+ # Console.logger work as for the rest of the socketry stack. A
16
+ # Console::Logger instance is forwarded to as given; the Console module is
17
+ # looked up on every call, so a Console.logger set before connect reaches
18
+ # every task the session spawns.
19
+ # [A Logger-compatible object] (stdlib Logger, Rails.logger,
20
+ # AsyncRabbitMQ::Log, anything with debug/info/warn/error taking a
21
+ # message) — the subject is dropped. One destination per session,
22
+ # independent of the process-wide Console logger.
23
+ # [nil] every message discarded.
24
+ #
25
+ # On top of whatever the destination does, AsyncRabbitMQ.log_level caps
26
+ # what this gem emits at all (default :warn) — so an application running
27
+ # Console at info is not flooded with this client's info and debug lines
28
+ # unless it asks for them.
29
+ #
30
+ # Session.new # Console, warnings and up
31
+ # Session.new(logger: Rails.logger) # Rails' logger
32
+ # Session.new(logger: nil) # silent
33
+ # AsyncRabbitMQ.log_level = :debug # everything, wherever it goes
34
+ # AsyncRabbitMQ.log_level = :off # nothing, from any session
35
+ module Logging
36
+ LEVELS = %i[debug info warn error fatal].freeze
37
+ SEVERITY = LEVELS.each_with_index.to_h.merge(off: LEVELS.size).freeze
38
+
39
+ # Whether +level+ passes AsyncRabbitMQ.log_level. Read on every call, so
40
+ # changing the level takes effect at once, for every session.
41
+ def self.enabled?(level)
42
+ SEVERITY.fetch(level) >= SEVERITY.fetch(AsyncRabbitMQ.log_level)
43
+ end
44
+
45
+ # Shared by the adapters: one method per level that checks the gem-wide
46
+ # level, then hands the call to #emit.
47
+ module Gate
48
+ LEVELS.each do |level|
49
+ define_method(level) do |subject, *arguments, **fields, &block|
50
+ emit(level, subject, *arguments, **fields, &block) if Logging.enabled?(level)
51
+ nil
52
+ end
53
+ end
54
+ end
55
+
56
+ # Forwards to Console, keeping the subject.
57
+ class ConsoleAdapter
58
+ include Gate
59
+
60
+ # +target+ nil means the Console module, resolved per call.
61
+ def initialize(target = nil)
62
+ @target = target
63
+ end
64
+
65
+ def target
66
+ @target || ::Console
67
+ end
68
+
69
+ private
70
+
71
+ def emit(level, subject, *arguments, **fields, &block)
72
+ target.public_send(level, subject, *arguments, **fields, &block)
73
+ end
74
+ end
75
+
76
+ # Adapts a Logger-compatible object to the (subject, message) call shape
77
+ # by dropping the subject. Accepts the whole Console call shape - extra
78
+ # arguments and keywords included, e.g. error(self, msg, exception: e) -
79
+ # and passes on only the message, so a call site written for Console
80
+ # never raises for a user who passed a plain Logger.
81
+ class LoggerShim
82
+ include Gate
83
+
84
+ attr_reader :logger
85
+
86
+ def initialize(logger)
87
+ @logger = logger
88
+ end
89
+
90
+ private
91
+
92
+ def emit(level, _subject, message = nil, *_rest, **_fields, &block)
93
+ # resolve only requires debug/info/warn/error, the levels this gem
94
+ # uses; a logger without fatal gets it as error rather than raising
95
+ # NoMethodError from inside an error path.
96
+ level = :error if level == :fatal && !@logger.respond_to?(:fatal)
97
+ @logger.public_send(level, message, &block)
98
+ end
99
+ end
100
+
101
+ # Discards everything: what +logger: nil+ means.
102
+ class Null
103
+ LEVELS.each { |level| define_method(level) { |*, **, &| nil } }
104
+ end
105
+
106
+ NULL = Null.new.freeze
107
+
108
+ # Turn a +logger:+ argument into an adapter that takes (subject, message).
109
+ # Idempotent, so every component that accepts a logger can resolve it
110
+ # without caring whether its caller already did.
111
+ def self.resolve(logger)
112
+ case logger
113
+ when nil then NULL
114
+ when ConsoleAdapter, LoggerShim, Null then logger
115
+ else
116
+ if console_module?(logger)
117
+ ConsoleAdapter.new
118
+ elsif console_logger?(logger)
119
+ ConsoleAdapter.new(logger)
120
+ elsif LEVELS.take(4).all? { |level| logger.respond_to?(level) }
121
+ LoggerShim.new(logger)
122
+ else
123
+ raise ArgumentError, "logger: must respond to debug, info, warn and error " \
124
+ "(or be Console, or nil to discard) - got #{logger.inspect}"
125
+ end
126
+ end
127
+ end
128
+
129
+ # Console is referenced only when the caller chose it — it is the default
130
+ # Session/Cluster argument, and async loads it anyway — so neither check
131
+ # requires it.
132
+ def self.console_module?(logger)
133
+ defined?(::Console) && logger.equal?(::Console)
134
+ end
135
+
136
+ def self.console_logger?(logger)
137
+ defined?(::Console::Filter) && logger.is_a?(::Console::Filter)
138
+ end
139
+ private_class_method :console_module?, :console_logger?
140
+ end
141
+ end
@@ -29,6 +29,7 @@ module AsyncRabbitMQ
29
29
  connection.unblocked
30
30
  recovery.attempt
31
31
  recovery.succeeded
32
+ recovery.topology_incomplete
32
33
  recovery.exhausted
33
34
  heartbeat.sent
34
35
  channel.open
@@ -46,7 +47,9 @@ module AsyncRabbitMQ
46
47
 
47
48
  def initialize(logger: nil)
48
49
  @subscribers = []
49
- @logger = logger
50
+ # Default nil: a Notifier built on its own (to share between sessions)
51
+ # stays as quiet as it always was; sessions pass theirs.
52
+ @logger = Logging.resolve(logger)
50
53
  end
51
54
 
52
55
  def subscribe(pattern = nil, &block)
@@ -80,7 +83,7 @@ module AsyncRabbitMQ
80
83
  begin
81
84
  block.call(name, payload)
82
85
  rescue => e
83
- @logger&.error("Event subscriber for #{name} raised #{e.class}: #{e.message}")
86
+ @logger.error(self, "Event subscriber for #{name} raised #{e.class}: #{e.message}")
84
87
  end
85
88
  end
86
89
  nil
@@ -87,7 +87,10 @@ module AsyncRabbitMQ
87
87
  # Select the best mechanism the broker supports, in preference order.
88
88
  # Returns an instantiated mechanism object.
89
89
  # Raises AuthenticationError if no common mechanism is found.
90
- def self.negotiate(broker_mechanisms_string, preferred: nil, username: nil, password: nil)
90
+ # +prefer_external+: the caller has transport-layer identity to offer — a
91
+ # TLS client certificate — so EXTERNAL outranks PLAIN for it. Session sets
92
+ # this when certificate material was configured.
93
+ def self.negotiate(broker_mechanisms_string, preferred: nil, username: nil, password: nil, prefer_external: false)
91
94
  broker_list = broker_mechanisms_string.split(/\s+/)
92
95
 
93
96
  if preferred
@@ -98,8 +101,18 @@ module AsyncRabbitMQ
98
101
  return instantiate(name, username: username, password: password)
99
102
  end
100
103
 
101
- # Preference order: EXTERNAL (strongest, no credentials on wire), PLAIN (universal)
102
- %w[EXTERNAL PLAIN].each do |name|
104
+ # Preference order. EXTERNAL identifies the client by its TLS
105
+ # certificate and sends no credentials at all, so auto-selecting it for
106
+ # a caller who supplied a password silently discards that password — and
107
+ # fails against any broker whose auth_mechanisms happens to advertise
108
+ # EXTERNAL, despite the credentials being valid. PLAIN therefore wins
109
+ # whenever there is a password and no client certificate (Bunny and the
110
+ # Java client default to PLAIN for the same reason). EXTERNAL wins when
111
+ # the connection carries a certificate to be identified by — a password
112
+ # is usually the untouched guest default there — or when there is no
113
+ # password at all; auth_mechanism: forces either outright.
114
+ order = (prefer_external || !password) ? %w[EXTERNAL PLAIN] : %w[PLAIN EXTERNAL]
115
+ order.each do |name|
103
116
  if broker_list.include?(name)
104
117
  return instantiate(name, username: username, password: password)
105
118
  end