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.
@@ -1,5 +1,6 @@
1
1
  require "async"
2
2
  require "async/condition"
3
+ require "async/promise"
3
4
  require "async/semaphore"
4
5
  require_relative "errors"
5
6
 
@@ -116,7 +117,7 @@ module AsyncRabbitMQ
116
117
  @notifier = session.respond_to?(:notifier) ? session.notifier : nil
117
118
  @frame_io = frame_io
118
119
  @frame_max = frame_max
119
- @logger = logger
120
+ @logger = Logging.resolve(logger)
120
121
  @rpc_timeout = rpc_timeout # seconds a synchronous operation waits for its reply; nil = forever
121
122
 
122
123
  @state = :closed
@@ -143,7 +144,7 @@ module AsyncRabbitMQ
143
144
  @recover_cancelled_consumers = recover_cancelled_consumers
144
145
  @on_error_disposition = :dead_letter
145
146
  @resyncing = false
146
- @resync_condition = nil
147
+ @resync_promise = nil
147
148
  # Incremented on every reopen (connection recovery or a single-channel
148
149
  # reopen). Delivery tags are stamped with it so acks raised against a
149
150
  # previous generation can be dropped instead of hitting a live message.
@@ -153,10 +154,10 @@ module AsyncRabbitMQ
153
154
  @mutex = Async::Semaphore.new(1)
154
155
  @publish_sem = Async::Semaphore.new(1) # one publish's frames go out contiguously
155
156
  @rpc_sem = Async::Semaphore.new(1) # one request/reply in flight per channel
156
- @reply_condition = nil
157
+ @reply_promise = nil
157
158
  @content_condition = nil
158
159
  @pending_content = nil
159
- @recovered_condition = nil # fibers parked while the connection recovers
160
+ @recovery_promise = nil # per-episode latch; fibers park on it while the connection recovers
160
161
  @pool_size = validate_pool_size!(pool_size)
161
162
  @work_queue = nil # Async::Queue of [method, header, body, entry]
162
163
  @workers = [] # long-lived handler fibers draining it
@@ -215,14 +216,64 @@ module AsyncRabbitMQ
215
216
  end
216
217
 
217
218
  def close
219
+ # A resync is reopening the channel in the background; it will land on
220
+ # :open (or :closed if it failed, or :recovering if the connection then
221
+ # dropped). Park until it settles, then close the live channel — rather
222
+ # than falling through `return unless open?` and silently doing nothing
223
+ # while the channel goes on consuming. If recovery is abandoned while we
224
+ # wait, wait_for_recovery! raises the reason; the channel is closed
225
+ # either way, which is what the caller asked for, so swallow it.
226
+ begin
227
+ wait_for_recovery! while resyncing?
228
+ rescue => e
229
+ @logger.debug(self, "Channel #{@channel_id}: close saw recovery end while resyncing: #{e.class}")
230
+ return
231
+ end
218
232
  if recovering?
219
233
  # Give the channel up rather than letting recovery reopen it.
220
234
  drop!(NotOpenError.new("Channel #{@channel_id} closed during recovery"), reason: :user)
221
235
  return
222
236
  end
223
237
  return unless open?
224
- rpc(AMQ::Protocol::Channel::Close.encode(@channel_id, 200, "Goodbye", 0, 0), AMQ::Protocol::Channel::CloseOk)
238
+ close_attempts = 0
239
+ begin
240
+ rpc(AMQ::Protocol::Channel::Close.encode(@channel_id, 200, "Goodbye", 0, 0), AMQ::Protocol::Channel::CloseOk)
241
+ rescue RpcTimeoutError
242
+ # No close-ok in time. rpc's ensure has already resynchronised the
243
+ # channel: it is back :open with its consumers (or dead, its waiters
244
+ # failed through the resync's own teardown). Nothing is left parked,
245
+ # but the close did not happen — try it once more on the resynced
246
+ # channel. A broker that answers neither attempt gets the error raised
247
+ # to the caller, with the channel alive and usable; raising beats
248
+ # pretending it closed, and beats force-forgetting an id the broker
249
+ # still considers open, which a later channel.open would collide with.
250
+ close_attempts += 1
251
+ retry if close_attempts == 1 && open?
252
+ # The resync can also leave the channel in a terminal state. Already
253
+ # :closed means its teardown ran (waiters failed, id released): close
254
+ # is done, not failed. :recovering means the connection went while the
255
+ # resync waited; the user asked for the channel to be gone, so drop it
256
+ # before the next recovery pass resurrects it, consumers and all.
257
+ return if closed?
258
+ unless open?
259
+ drop!(NotOpenError.new("Channel #{@channel_id} closed during recovery"), reason: :user)
260
+ return
261
+ end
262
+ raise
263
+ rescue => e
264
+ # The connection went while we waited (ConnectionError, NotOpenError
265
+ # out of the resync/park machinery). The session's teardown has
266
+ # already released this channel's waiters; the user still asked for
267
+ # the channel to be gone, so give it up rather than let recovery
268
+ # resurrect it. Already :closed means exactly that — done.
269
+ drop!(NotOpenError.new("Channel #{@channel_id} closed during recovery"), reason: :user) unless closed?
270
+ return
271
+ end
225
272
  @state = :closed
273
+ # Confirms outstanding at close will never be resolved now; a fiber in
274
+ # wait_for_confirms or parked on an outstanding slot has to hear that
275
+ # from us, or it waits forever.
276
+ fail_waiters!(NotOpenError.new("Channel #{@channel_id} was closed"))
226
277
  # Closing the channel cancelled its consumers on the broker side; an
227
278
  # auto-delete queue that just lost its last one is gone with it.
228
279
  forget_consumers_in_topology
@@ -434,8 +485,11 @@ module AsyncRabbitMQ
434
485
  def basic_get(queue_name, manual_ack: true)
435
486
  msg, content = @rpc_sem.acquire do
436
487
  assert_open!
488
+ # Reply slot registered before the write, as in send_and_wait: the
489
+ # reply can be dispatched while write_frame yields on a full queue.
490
+ promise = @reply_promise = Async::Promise.new
437
491
  @frame_io.write_frame(AMQ::Protocol::Basic::Get.encode(@channel_id, queue_name, !manual_ack).encode)
438
- m = wait_for_any(AMQ::Protocol::Basic::GetOk, AMQ::Protocol::Basic::GetEmpty)
492
+ m = wait_for_any(promise, AMQ::Protocol::Basic::GetOk, AMQ::Protocol::Basic::GetEmpty)
439
493
  stamp_delivery_tag(m) if m.is_a?(AMQ::Protocol::Basic::GetOk)
440
494
  # After GetOk the content header + body follow on this channel.
441
495
  [m, m.is_a?(AMQ::Protocol::Basic::GetOk) ? wait_content : nil]
@@ -576,11 +630,15 @@ module AsyncRabbitMQ
576
630
  deadline = timeout && (Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout)
577
631
 
578
632
  until @pending_confirms.empty?
633
+ # A closed channel will never resolve them. The teardown paths signal
634
+ # the waiters parked at that moment; a waiter arriving afterwards has
635
+ # to hear it here, or it parks on a condition nothing will ever signal.
636
+ raise NotOpenError, "Channel #{@channel_id} is not open" if closed?
579
637
  # Lazily (re)created: interrupt_wait! clears it on connection loss and a
580
638
  # caller may arrive before reopen_after_recovery has re-selected confirms.
581
639
  @confirm_condition ||= Async::Condition.new
582
640
 
583
- if deadline
641
+ outcome = if deadline
584
642
  remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
585
643
  raise ConfirmTimeoutError.new(unconfirmed_tags: @pending_confirms.keys, channel_id: @channel_id) if remaining <= 0
586
644
 
@@ -593,6 +651,9 @@ module AsyncRabbitMQ
593
651
  @confirm_condition.wait
594
652
  end
595
653
 
654
+ # A teardown path signalled us its error (broker channel close, user
655
+ # close, connection loss): raise that, it names what actually happened.
656
+ raise outcome if outcome.is_a?(Exception)
596
657
  raise ConnectionError, "Session disconnected while waiting for confirms" unless open?
597
658
  end
598
659
  result = @only_acks
@@ -761,10 +822,29 @@ module AsyncRabbitMQ
761
822
  # with +error+; new publishes and RPCs park until #reopen_after_recovery
762
823
  # (see #assert_open!); consumers are re-registered on reopen.
763
824
  def mark_recovering!(error)
825
+ begin_recovery_wait!
764
826
  @state = :recovering
765
827
  interrupt_wait!(error)
766
828
  end
767
829
 
830
+ # Start a park-and-wait episode (:recovering or :resyncing): a fresh
831
+ # promise every arriving waiter latches onto. A promise, not a condition:
832
+ # resolution is sticky, so a waiter that arrives after finish_recovery! has
833
+ # already resolved the episode returns at once instead of parking on a
834
+ # signal that will never come again — the lost-wakeup class that used to
835
+ # need a re-check loop at every wait site. Every transition INTO
836
+ # :recovering or :resyncing must come through here.
837
+ #
838
+ # A still-PENDING promise is kept, not replaced: fibers are parked on it,
839
+ # and a replacement would orphan them forever — a resync that a connection
840
+ # drop escalates into recovery is one episode to its waiters, resolved by
841
+ # whichever teardown or finish ends it. Only a resolved (or absent) promise
842
+ # means the previous episode is over and a new latch is needed.
843
+ def begin_recovery_wait!
844
+ @recovery_promise = Async::Promise.new if @recovery_promise.nil? || @recovery_promise.resolved?
845
+ end
846
+ private :begin_recovery_wait!
847
+
768
848
  # Give the channel up while the session is recovering, instead of letting
769
849
  # recovery reopen it: everything waiting or parked raises +error+, #each
770
850
  # callers return, the consumers are forgotten and the id goes back.
@@ -789,13 +869,7 @@ module AsyncRabbitMQ
789
869
  # (used on connection loss, and again if the connection dies mid-recovery).
790
870
  def interrupt_wait!(error = nil)
791
871
  error ||= ConnectionError.new(code: 0, text: "Connection lost during recovery")
792
- @reply_condition&.signal(error)
793
- @reply_condition = nil
794
- @content_condition&.signal(error)
795
- @content_condition = nil
796
- @confirm_condition&.signal(error)
797
- @confirm_condition = nil
798
- release_outstanding_slots(error)
872
+ fail_waiters!(error)
799
873
  @queue&.push(nil) rescue nil
800
874
  # The connection is gone, so the queued deliveries are too: the broker
801
875
  # requeues whatever was unacknowledged and sends it again on the new one.
@@ -804,6 +878,37 @@ module AsyncRabbitMQ
804
878
  # ignore — best-effort unblock
805
879
  end
806
880
 
881
+ # Wake every fiber parked on a reply, content, confirm or slot wait with
882
+ # +error+. Every teardown path — connection loss, broker-sent channel
883
+ # close, user close — must release all four: whichever one a path misses
884
+ # parks its caller forever, since nothing else will ever signal it on a
885
+ # channel that is gone. A confirm waiter with no timeout (the default) and
886
+ # a publisher parked on an outstanding slot are the two with no clock of
887
+ # their own.
888
+ def fail_waiters!(error)
889
+ # Reply and resync are one-shot promises: resolving with the error hands
890
+ # it to the waiter through the same value path a real reply takes, and a
891
+ # second resolution (a race between teardown paths) is a silent no-op.
892
+ promise = @reply_promise
893
+ @reply_promise = nil
894
+ promise&.resolve(error)
895
+ @content_condition&.signal(error)
896
+ @content_condition = nil
897
+ @confirm_condition&.signal(error)
898
+ @confirm_condition = nil
899
+ release_outstanding_slots(error)
900
+ # A resync in progress is parked waiting for a close-ok that this
901
+ # connection will never deliver. Wake it so it can see the channel is
902
+ # now :recovering and hand the reopen to the recovery loop instead of
903
+ # racing it (see resync_after_rpc_timeout). Nil the slot too, so the
904
+ # dispatch filter stops discarding frames — recovery's channel.open-ok
905
+ # among them.
906
+ promise = @resync_promise
907
+ @resync_promise = nil
908
+ promise&.resolve(error)
909
+ end
910
+ private :fail_waiters!
911
+
807
912
  # -------------------------------------------------------------------------
808
913
  # Internal: called by Session after reconnect
809
914
  # -------------------------------------------------------------------------
@@ -863,6 +968,42 @@ module AsyncRabbitMQ
863
968
  @consumers.each_value { |c| c[:queue_name] = new_name if c[:queue_name] == old_name }
864
969
  end
865
970
 
971
+ # Internal: a server-named queue came back under a new name — rewrite the
972
+ # unconfirmed publishes that refer to it, in two places. The routing key,
973
+ # when the publish went through the default exchange, whose routing key IS
974
+ # the queue name: replayed unchanged it addresses a queue that no longer
975
+ # exists, unroutable and silently dropped — the loss confirms exist to
976
+ # prevent. And reply_to, whatever the exchange: in the RPC pattern the
977
+ # request names the publisher's own server-named queue there, and a replay
978
+ # carrying the old name sends the responder's answer to a dead queue. Only
979
+ # those two are structurally tied to the queue name; a routing key on a
980
+ # named exchange is the caller's semantics, and the renamed binding already
981
+ # carries it to the right queue. The rewrite only updates the kept context:
982
+ # republish_unconfirmed re-encodes the frames from it.
983
+ def rename_unconfirmed_queue(old_name, new_name)
984
+ @pending_confirms.each_value do |entry|
985
+ ctx = entry[2]
986
+ next unless ctx
987
+
988
+ routing = ctx.exchange.to_s.empty? && ctx.routing_key == old_name
989
+ reply_to = ctx.options[:reply_to] == old_name ||
990
+ (ctx.options[:properties].is_a?(Hash) && ctx.options[:properties][:reply_to] == old_name)
991
+ next unless routing || reply_to
992
+
993
+ opts = ctx.options
994
+ if reply_to
995
+ opts = opts.dup
996
+ opts[:reply_to] = new_name if opts[:reply_to] == old_name
997
+ if opts[:properties].is_a?(Hash) && opts[:properties][:reply_to] == old_name
998
+ opts[:properties] = opts[:properties].merge(reply_to: new_name)
999
+ end
1000
+ end
1001
+ # Contexts are frozen and a batch shares one across its entries, so
1002
+ # replace rather than mutate. publish_context re-copies the options.
1003
+ entry[2] = publish_context(ctx.exchange, routing ? new_name : ctx.routing_key, opts)
1004
+ end
1005
+ end
1006
+
866
1007
  # The consumers on this channel no longer exist on the broker (the channel
867
1008
  # is closed, by us or by it). @consumers itself is kept so that
868
1009
  # reopen(recover_consumers: true) can register them again, which records
@@ -885,6 +1026,7 @@ module AsyncRabbitMQ
885
1026
  @consumers.clear unless recover_consumers
886
1027
  # Reopened :resyncing, not :open: the replay below must reach the wire
887
1028
  # before any new publish, or a tag no longer matches its position on it.
1029
+ begin_recovery_wait! # callers arriving while :resyncing park on this episode
888
1030
  @session.reopen_channel(self, state: :resyncing)
889
1031
  # Only this channel was closed, so the topology is intact and anything
890
1032
  # left unconfirmed can go straight back out.
@@ -902,6 +1044,12 @@ module AsyncRabbitMQ
902
1044
  # until the topology has been replayed (see #finish_recovery!).
903
1045
  def reopen_on(frame_io, state: :open)
904
1046
  @frame_io = frame_io
1047
+ # The reconnect may have negotiated a different frame_max (a failover to
1048
+ # a differently configured node). Splitting frames at the old size would
1049
+ # hand the broker over-sized body frames — a 501 that kills the fresh
1050
+ # connection — so every encode from here on, replays included, uses the
1051
+ # live value.
1052
+ @frame_max = @session.frame_max if @session.respond_to?(:frame_max)
905
1053
  # The broker restarts delivery tags at 1 on a reopened channel, so any
906
1054
  # tag handed out before this point is now stale.
907
1055
  @delivery_generation += 1
@@ -911,6 +1059,15 @@ module AsyncRabbitMQ
911
1059
  # Whatever was outstanding belonged to the old channel; the broker
912
1060
  # requeued it and will deliver it again with fresh tags.
913
1061
  @unsettled.clear
1062
+ # Stop the dispatch loop bound to the old queue before swapping it out.
1063
+ # It is parked inside old_queue.pop, which captured that queue as its
1064
+ # receiver, so reassigning @queue alone would never wake it: it would
1065
+ # park there for the life of the reactor (one leaked fiber per resync).
1066
+ # The connection-recovery path already pushed this nil via interrupt_wait!
1067
+ # — a second one into an orphaned queue is harmless; the resync path,
1068
+ # which keeps the live connection, has pushed nothing, so this is its
1069
+ # only stop signal.
1070
+ @queue&.push(nil) rescue nil
914
1071
  @queue = @frame_io.register_channel(@channel_id)
915
1072
  start_dispatch_task
916
1073
  send_and_wait(AMQ::Protocol::Channel::Open.encode(@channel_id, ""), AMQ::Protocol::Channel::OpenOk)
@@ -953,7 +1110,7 @@ module AsyncRabbitMQ
953
1110
  return false unless delivery_tag.is_a?(VersionedDeliveryTag)
954
1111
  return false unless delivery_tag.stale?(@delivery_generation)
955
1112
 
956
- @logger.warn(
1113
+ @logger.warn(self,
957
1114
  "Channel #{@channel_id}: dropped #{action} for delivery tag #{delivery_tag.to_i} from " \
958
1115
  "generation #{delivery_tag.generation} (now #{@delivery_generation}) — the message was " \
959
1116
  "redelivered on the new connection"
@@ -980,7 +1137,7 @@ module AsyncRabbitMQ
980
1137
  return if manual_ack && @prefetch && @prefetch[:count].to_i > 0
981
1138
 
982
1139
  @qos_warned = true
983
- @logger.warn(
1140
+ @logger.warn(self,
984
1141
  if manual_ack
985
1142
  "Channel #{@channel_id}: consuming from #{queue_name} without basic_qos. " \
986
1143
  "The broker will send the whole queue as fast as it can and the backlog is " \
@@ -1016,7 +1173,7 @@ module AsyncRabbitMQ
1016
1173
  # life of the connection and, once prefetch messages are stuck that way,
1017
1174
  # the consumer stops receiving anything at all.
1018
1175
  def handle_consumer_error(error, method, entry)
1019
- @logger.error(
1176
+ @logger.error(self,
1020
1177
  "Channel #{@channel_id}: consumer #{method.consumer_tag} raised " "#{error.class}: #{error.message}"
1021
1178
  )
1022
1179
  instrument("consumer.error") do
@@ -1049,7 +1206,7 @@ module AsyncRabbitMQ
1049
1206
  rescue *PROPAGATE_FROM_HANDLER
1050
1207
  raise
1051
1208
  rescue Exception => e # rubocop:disable Lint/RescueException
1052
- @logger.error("Channel #{@channel_id}: could not settle after consumer error: #{e.class}: #{e.message}")
1209
+ @logger.error(self, "Channel #{@channel_id}: could not settle after consumer error: #{e.class}: #{e.message}")
1053
1210
  end
1054
1211
  end
1055
1212
 
@@ -1065,7 +1222,7 @@ module AsyncRabbitMQ
1065
1222
  # The hook is the caller's code as much as the handler is, and it runs
1066
1223
  # while a delivery is still unsettled: letting it escape would strand the
1067
1224
  # message and kill the worker.
1068
- @logger.error("Channel #{@channel_id}: on_handler_error hook raised #{e.class}: #{e.message}")
1225
+ @logger.error(self, "Channel #{@channel_id}: on_handler_error hook raised #{e.class}: #{e.message}")
1069
1226
  nil
1070
1227
  end
1071
1228
 
@@ -1120,7 +1277,9 @@ module AsyncRabbitMQ
1120
1277
  def ensure_worker(queue)
1121
1278
  return if queue.nil? || @workers.size >= @pool_size
1122
1279
 
1123
- @workers << @session.spawn_background { worker_loop(queue) }
1280
+ # Detached, not in the session barrier: a graceful close lets workers
1281
+ # finish the backlog they hold (see Session#spawn_detached).
1282
+ @workers << @session.spawn_detached { worker_loop(queue) }
1124
1283
  end
1125
1284
 
1126
1285
  # Retire this generation's workers. The sentinel goes on the back of the
@@ -1198,13 +1357,13 @@ module AsyncRabbitMQ
1198
1357
  rescue *PROPAGATE_FROM_HANDLER
1199
1358
  raise
1200
1359
  rescue => e
1201
- @logger.error("Channel #{@channel_id} dispatch error: #{e.class}: #{e.message}")
1360
+ @logger.error(self, "Channel #{@channel_id} dispatch error: #{e.class}: #{e.message}")
1202
1361
  rescue Exception => e # rubocop:disable Lint/RescueException
1203
1362
  # Handlers are contained now, so nothing should reach here. If something
1204
1363
  # does, this channel is about to stop delivering anything at all - no
1205
1364
  # confirms, no RPC replies, no close-ok - and the one thing that must not
1206
1365
  # happen is for it to go quiet without saying so.
1207
- @logger.error(
1366
+ @logger.error(self,
1208
1367
  "Channel #{@channel_id} dispatch died on #{e.class}: #{e.message}. " \
1209
1368
  "The channel will not deliver anything further."
1210
1369
  )
@@ -1238,12 +1397,12 @@ module AsyncRabbitMQ
1238
1397
  # While resynchronising, everything except the close-ok we are waiting
1239
1398
  # for belongs to the request that timed out. Dropping it here is the
1240
1399
  # point of the reopen: it must not reach the next caller.
1241
- if @resync_condition
1400
+ if @resync_promise
1242
1401
  case method
1243
1402
  when AMQ::Protocol::Channel::CloseOk
1244
- cond = @resync_condition
1245
- @resync_condition = nil
1246
- cond.signal(:closed)
1403
+ promise = @resync_promise
1404
+ @resync_promise = nil
1405
+ promise.resolve(:closed)
1247
1406
  when AMQ::Protocol::Basic::Ack
1248
1407
  # Confirms still in flight for messages published before the close.
1249
1408
  # Dropping them would strand their entries in @pending_confirms: they
@@ -1256,9 +1415,9 @@ module AsyncRabbitMQ
1256
1415
  # Content frames follow on this channel; take them off with the
1257
1416
  # method so the stream does not skew.
1258
1417
  @queue.pop
1259
- @logger.debug("Channel #{@channel_id}: discarded #{method.class} while resynchronising")
1418
+ @logger.debug(self, "Channel #{@channel_id}: discarded #{method.class} while resynchronising")
1260
1419
  else
1261
- @logger.warn("Channel #{@channel_id}: discarded #{method.class} while resynchronising")
1420
+ @logger.warn(self, "Channel #{@channel_id}: discarded #{method.class} while resynchronising")
1262
1421
  end
1263
1422
  return
1264
1423
  end
@@ -1286,7 +1445,7 @@ module AsyncRabbitMQ
1286
1445
  ensure_worker(queue)
1287
1446
  end
1288
1447
  else
1289
- @logger.warn("Delivery on channel #{@channel_id} for unknown consumer #{method.consumer_tag}")
1448
+ @logger.warn(self, "Delivery on channel #{@channel_id} for unknown consumer #{method.consumer_tag}")
1290
1449
  end
1291
1450
 
1292
1451
  when AMQ::Protocol::Basic::Return
@@ -1300,7 +1459,7 @@ module AsyncRabbitMQ
1300
1459
  if @return_handler
1301
1460
  Async { @return_handler.call(method, header, body) }
1302
1461
  else
1303
- @logger.warn("Unhandled basic.return on channel #{@channel_id} — register on_return to handle")
1462
+ @logger.warn(self, "Unhandled basic.return on channel #{@channel_id} — register on_return to handle")
1304
1463
  end
1305
1464
 
1306
1465
  when AMQ::Protocol::Basic::Ack
@@ -1325,12 +1484,15 @@ module AsyncRabbitMQ
1325
1484
  AMQ::Protocol::Connection::Unblocked
1326
1485
  # These arrive on channel 0 and are handled by the Session channel-0 monitor.
1327
1486
  # They should never reach a Channel object — log and ignore defensively.
1328
- @logger.debug("Channel #{@channel_id}: ignoring connection-level #{method.class} frame")
1487
+ @logger.debug(self, "Channel #{@channel_id}: ignoring connection-level #{method.class} frame")
1329
1488
 
1330
1489
  else
1331
- # Wake any fiber waiting on this method type
1332
- @reply_condition&.signal(method)
1333
- @reply_condition = nil
1490
+ # Resolve the registered reply slot. The promise latches, so a reply
1491
+ # that lands while the requester is still parked inside its own
1492
+ # write_frame (full write queue) is kept for it.
1493
+ promise = @reply_promise
1494
+ @reply_promise = nil
1495
+ promise&.resolve(method)
1334
1496
  # Yield so the newly-woken fiber (e.g. basic_consume registering its consumer)
1335
1497
  # can run before dispatch_loop processes the next queued message.
1336
1498
  Async::Task.current.yield
@@ -1390,9 +1552,12 @@ module AsyncRabbitMQ
1390
1552
  ConnectionError.new(code: code, text: text)
1391
1553
  end
1392
1554
 
1393
- # Wake any waiting fiber with the error
1394
- @reply_condition&.signal(error)
1395
- @reply_condition = nil
1555
+ # Wake every parked fiber with the error — the RPC caller, but equally a
1556
+ # fiber in wait_for_confirms and a publisher parked on an outstanding
1557
+ # slot: no ack will ever arrive on a closed channel, so missing them
1558
+ # here was a permanent hang for a confirm wait with no timeout (the
1559
+ # default), and a 15s stall holding the publish semaphore for the slot.
1560
+ fail_waiters!(error)
1396
1561
  # Stop dispatch_loop
1397
1562
  @queue&.push(nil)
1398
1563
  stop_workers(discard: true)
@@ -1417,7 +1582,8 @@ module AsyncRabbitMQ
1417
1582
  # Bunny hands cancel notifications to its consumer work pool and the Java
1418
1583
  # client to its work service, for the same reason.
1419
1584
  def notify_app(name, &block)
1420
- @session.spawn_background { run_callback(name, &block) }
1585
+ # Detached: an application callback is not ours to stop at close.
1586
+ @session.spawn_detached { run_callback(name, &block) }
1421
1587
  end
1422
1588
 
1423
1589
  # The body of #notify_app, for a caller that is already off the dispatch
@@ -1427,7 +1593,7 @@ module AsyncRabbitMQ
1427
1593
  rescue *PROPAGATE_FROM_HANDLER
1428
1594
  raise
1429
1595
  rescue Exception => e # rubocop:disable Lint/RescueException
1430
- @logger.error("Channel #{@channel_id}: #{name} callback raised #{e.class}: #{e.message}")
1596
+ @logger.error(self, "Channel #{@channel_id}: #{name} callback raised #{e.class}: #{e.message}")
1431
1597
  end
1432
1598
 
1433
1599
  # The broker cancels a consumer when it can no longer serve the queue to
@@ -1454,7 +1620,7 @@ module AsyncRabbitMQ
1454
1620
  # queue being deleted and a reconnect re-declares the registry wholesale.
1455
1621
  # Settled by #reconcile_cancelled_consumer, either way.
1456
1622
  topology&.suspend_queue(entry[:queue_name])
1457
- @logger.warn("Channel #{@channel_id}: broker cancelled consumer #{tag} on #{entry[:queue_name]}")
1623
+ @logger.warn(self, "Channel #{@channel_id}: broker cancelled consumer #{tag} on #{entry[:queue_name]}")
1458
1624
  instrument("consumer.cancelled") do
1459
1625
  { channel: @channel_id, consumer_tag: tag, queue: entry[:queue_name], reason: :broker }
1460
1626
  end
@@ -1592,7 +1758,7 @@ module AsyncRabbitMQ
1592
1758
  # Consuming again, so the queue is there and recovery can have it
1593
1759
  # back (#handle_broker_cancel held it).
1594
1760
  topology&.resume_queue(queue)
1595
- @logger.info("Channel #{@channel_id}: re-subscribed consumer #{tag} to #{queue}")
1761
+ @logger.info(self, "Channel #{@channel_id}: re-subscribed consumer #{tag} to #{queue}")
1596
1762
  instrument("consumer.recovered") do
1597
1763
  { channel: @channel_id, consumer_tag: tag, queue: queue, attempts: failures + 1 }
1598
1764
  end
@@ -1606,7 +1772,7 @@ module AsyncRabbitMQ
1606
1772
  # on consumer.recovery_failed would otherwise be told twice about
1607
1773
  # one event, and told it in the words of the more serious of the
1608
1774
  # two.
1609
- @logger.debug("Channel #{@channel_id}: re-subscribe of #{tag} interrupted by " \
1775
+ @logger.debug(self, "Channel #{@channel_id}: re-subscribe of #{tag} interrupted by " \
1610
1776
  "#{e.class}; waiting for the connection")
1611
1777
  rescue ChannelError => e
1612
1778
  # The queue went between the question and the answer. The broker
@@ -1634,13 +1800,13 @@ module AsyncRabbitMQ
1634
1800
  # hundreds.
1635
1801
  def note_recovery_failure(tag, queue, error, failures)
1636
1802
  if failures == 1
1637
- @logger.warn("Channel #{@channel_id}: could not re-subscribe #{tag} to #{queue}, " \
1803
+ @logger.warn(self, "Channel #{@channel_id}: could not re-subscribe #{tag} to #{queue}, " \
1638
1804
  "retrying: #{error.class}: #{error.message}")
1639
1805
  instrument("consumer.recovery_failed") do
1640
1806
  { channel: @channel_id, consumer_tag: tag, queue: queue, reason: :error, error: error }
1641
1807
  end
1642
1808
  else
1643
- @logger.debug("Channel #{@channel_id}: re-subscribe attempt #{failures} for #{tag} failed: #{error.message}")
1809
+ @logger.debug(self, "Channel #{@channel_id}: re-subscribe attempt #{failures} for #{tag} failed: #{error.message}")
1644
1810
  end
1645
1811
  end
1646
1812
 
@@ -1650,7 +1816,7 @@ module AsyncRabbitMQ
1650
1816
  # back" bug the Java client has been fixing instances of for years.
1651
1817
  def forget_deleted_queue(tag, queue)
1652
1818
  topology&.delete_queue(queue)
1653
- @logger.warn("Channel #{@channel_id}: queue #{queue} no longer exists; consumer #{tag} will not be recovered")
1819
+ @logger.warn(self, "Channel #{@channel_id}: queue #{queue} no longer exists; consumer #{tag} will not be recovered")
1654
1820
  instrument("consumer.recovery_failed") do
1655
1821
  { channel: @channel_id, consumer_tag: tag, queue: queue, reason: :queue_deleted }
1656
1822
  end
@@ -1677,7 +1843,7 @@ module AsyncRabbitMQ
1677
1843
  rescue *PROPAGATE_FROM_HANDLER
1678
1844
  raise
1679
1845
  rescue => e
1680
- @logger.debug("Channel #{@channel_id}: could not check whether #{name} still exists: #{e.class}: #{e.message}")
1846
+ @logger.debug(self, "Channel #{@channel_id}: could not check whether #{name} still exists: #{e.class}: #{e.message}")
1681
1847
  :unreachable
1682
1848
  end
1683
1849
 
@@ -1752,29 +1918,60 @@ module AsyncRabbitMQ
1752
1918
  # a publish issued now would go out after channel.close and be dropped by
1753
1919
  # the broker without a word, and another request's reply would be thrown
1754
1920
  # away as the late one we are shedding.
1921
+ begin_recovery_wait!
1755
1922
  @state = :resyncing
1756
- @logger.warn(
1923
+ @logger.warn(self,
1757
1924
  "Channel #{@channel_id}: reopening after an RPC timeout. A late reply carries nothing " \
1758
1925
  "to match it to its request, so it would be handed to the next caller on this channel."
1759
1926
  )
1760
1927
  instrument("channel.resync") { { channel: @channel_id, reason: :rpc_timeout } }
1761
1928
 
1762
1929
  consumers = @consumers.dup
1763
- cond = @resync_condition = Async::Condition.new
1930
+ # A promise: resolution is sticky, so a close-ok dispatched while this
1931
+ # fiber is still parked inside its own write (full write queue) is kept
1932
+ # rather than lost. Registered before the write for the same reason.
1933
+ promise = @resync_promise = Async::Promise.new
1764
1934
  @frame_io.write_frame(
1765
1935
  AMQ::Protocol::Channel::Close.encode(@channel_id, 200, "Resynchronising after RPC timeout", 0, 0).encode
1766
1936
  )
1767
1937
 
1938
+ outcome = nil
1768
1939
  begin
1769
- Async::Task.current.with_timeout(@rpc_timeout || RESYNC_TIMEOUT) { cond.wait }
1940
+ outcome = Async::Task.current.with_timeout(@rpc_timeout || RESYNC_TIMEOUT) { promise.wait }
1770
1941
  rescue Async::TimeoutError
1771
- @logger.error("Channel #{@channel_id}: no channel.close-ok while resynchronising")
1772
- ensure
1773
- @resync_condition = nil
1942
+ @logger.error(self, "Channel #{@channel_id}: no channel.close-ok while resynchronising")
1943
+ # Deliberately NOT clearing @resync_promise here: the dispatch filter
1944
+ # keys on it, and it must keep discarding frames — a very late
1945
+ # close-ok above all — until just before the reopen below. Cleared
1946
+ # there; the teardown paths (fail_waiters!) clear it themselves.
1947
+ end
1948
+
1949
+ # The connection dropped while we waited: mark_recovering! moved the
1950
+ # channel to :recovering and woke us (interrupt_wait! → fail_waiters!).
1951
+ # The reopen is the recovery loop's job now — it reopens every channel on
1952
+ # the new connection and replays the topology first. Racing it from here
1953
+ # would set the channel :closed and call reopen_channel against a session
1954
+ # that is not open, which raises, drops the channel out of the session,
1955
+ # and strands its consumers (they were never cleared, so recovery can
1956
+ # still restore them). Leave it be. @consumers is untouched; the dup is
1957
+ # moot on this path.
1958
+ if recovering? || outcome.is_a?(Exception)
1959
+ @logger.info(self, "Channel #{@channel_id}: connection lost during resync; recovery will reopen it")
1960
+ return
1774
1961
  end
1775
1962
 
1776
1963
  @state = :closed
1777
- @consumers.clear
1964
+ # The dispatch filter stays on until this point so a close-ok arriving
1965
+ # after the timeout is still discarded — otherwise it would resolve the
1966
+ # Open's reply promise below (registered before its write) and kill the
1967
+ # reopen with "expected OpenOk, got CloseOk".
1968
+ @resync_promise = nil
1969
+ # @consumers is deliberately NOT cleared here. If the connection drops
1970
+ # while reopen_channel below is parked waiting for channel.open-ok, this
1971
+ # method unwinds into the rescue with the channel now :recovering; the
1972
+ # recovery loop will reopen it and re-register whatever is in @consumers,
1973
+ # so emptying it would silently lose every consumer. (The dup is kept for
1974
+ # the same reason — see the rescue.)
1778
1975
  @session.reopen_channel(self, state: :resyncing)
1779
1976
  # reopen_on restores confirm mode but deliberately leaves the unconfirmed
1780
1977
  # messages alone: during connection recovery the topology they are
@@ -1788,7 +1985,18 @@ module AsyncRabbitMQ
1788
1985
  re_register_consumers
1789
1986
  resume_parked!(:open)
1790
1987
  rescue => e
1791
- @logger.error("Channel #{@channel_id}: could not resynchronise after an RPC timeout: #{e.class}: #{e.message}")
1988
+ # A connection drop during the reopen (after the early-return guard above
1989
+ # passed) lands here: the channel is now :recovering, or the session is no
1990
+ # longer open. Recovery will reopen this channel and re-register its
1991
+ # consumers, so leave it in the table with @consumers intact — restore the
1992
+ # dup in case it was mid-replace — rather than marking it closed and
1993
+ # dropping it, which would strand the consumers for good.
1994
+ if recovering? || !@session.open?
1995
+ @consumers.replace(consumers) if @consumers.empty?
1996
+ @logger.info(self, "Channel #{@channel_id}: connection lost during resync reopen; recovery will handle it")
1997
+ return
1998
+ end
1999
+ @logger.error(self, "Channel #{@channel_id}: could not resynchronise after an RPC timeout: #{e.class}: #{e.message}")
1792
2000
  mark_closed!(ChannelError.new("Channel could not be resynchronised after an RPC timeout: #{e.message}",
1793
2001
  channel_id: @channel_id))
1794
2002
  @session.channel_closed(@channel_id) rescue nil
@@ -1797,8 +2005,13 @@ module AsyncRabbitMQ
1797
2005
  end
1798
2006
 
1799
2007
  def send_and_wait(frame, *expected_classes)
2008
+ # Register the reply slot BEFORE writing: write_frame yields when the
2009
+ # write queue is full, and the reply can be dispatched inside that gap.
2010
+ # The promise keeps it for us; a condition registered afterwards lost it,
2011
+ # and the caller timed out into a needless resync.
2012
+ promise = @reply_promise = Async::Promise.new
1800
2013
  @frame_io.write_frame(frame.encode)
1801
- wait_for_any(*expected_classes)
2014
+ wait_for_any(promise, *expected_classes)
1802
2015
  end
1803
2016
 
1804
2017
  def topology
@@ -1808,7 +2021,7 @@ module AsyncRabbitMQ
1808
2021
  def recover_entity(what)
1809
2022
  yield
1810
2023
  rescue ChannelError => e
1811
- @logger.error("Channel #{@channel_id}: could not recover #{what}: #{e.message}")
2024
+ @logger.error(self, "Channel #{@channel_id}: could not recover #{what}: #{e.message}")
1812
2025
  # The broker closed this channel; put it back so the rest can continue.
1813
2026
  @session.reopen_channel(self)
1814
2027
  end
@@ -1847,6 +2060,13 @@ module AsyncRabbitMQ
1847
2060
  # until the broker acks it, so it can be re-published after a reconnect.
1848
2061
  def reserve_confirm_tag(bytes, payload = nil, context = nil)
1849
2062
  @delivery_tag += 1
2063
+ # Snapshot the payload: the caller may reuse or mutate its string after
2064
+ # publishing (publish_context copies headers for the same reason), and
2065
+ # everything that reads this entry later — a replay re-encoded after a
2066
+ # queue rename or a frame_max change, #unconfirmed_messages handed out on
2067
+ # a node failure — must see the bytes as they were sent, not as the
2068
+ # buffer looks now. Frozen strings skip the copy.
2069
+ payload = payload.dup if payload.is_a?(String) && !payload.frozen?
1850
2070
  @pending_confirms[@delivery_tag] = [bytes, payload, context]
1851
2071
  # The encoded frames carry this channel's id, so they can only be replayed
1852
2072
  # on this channel. Keep the payload and where it was going alongside, so a
@@ -1904,29 +2124,49 @@ module AsyncRabbitMQ
1904
2124
  @delivery_tag = 0
1905
2125
  @confirm_condition ||= Async::Condition.new # keep one an early waiter created
1906
2126
  pending.each do |entry|
1907
- @frame_io.write_frame(entry[0], publish: true)
2127
+ # Re-encode from the kept payload and context instead of replaying the
2128
+ # bytes recorded at publish time: the context may have been rewritten
2129
+ # by a server-named queue rename, and the reconnect may have negotiated
2130
+ # a different frame_max, so stale frames could be mis-addressed or
2131
+ # over-sized. This is the rare recovery path; the per-publish hot path
2132
+ # still records the pre-encoded bytes untouched.
2133
+ bytes = if (ctx = entry[2])
2134
+ encode_publish(entry[1], exchange: ctx.exchange, routing_key: ctx.routing_key, **ctx.options)
2135
+ else
2136
+ entry[0]
2137
+ end
2138
+ @frame_io.write_frame(bytes, publish: true)
1908
2139
  @delivery_tag += 1
1909
- @pending_confirms[@delivery_tag] = entry
2140
+ @pending_confirms[@delivery_tag] = [bytes, entry[1], entry[2]]
1910
2141
  end
1911
- @logger.info("Channel #{@channel_id}: re-published #{pending.size} unconfirmed message(s) after recovery") unless pending.empty?
2142
+ @logger.info(self, "Channel #{@channel_id}: re-published #{pending.size} unconfirmed message(s) after recovery") unless pending.empty?
1912
2143
  end
1913
2144
 
2145
+ # Park until the current episode resolves. The promise is a latch: a waiter
2146
+ # arriving after resolution returns immediately with the same outcome, so
2147
+ # there is no window between "state says recovering" and "the wait is
2148
+ # registered" for a resume to slip through. Raises the teardown error when
2149
+ # the episode ended in mark_closed!.
1914
2150
  def wait_for_recovery!
1915
- @recovered_condition ||= Async::Condition.new
1916
- outcome = @recovered_condition.wait
1917
- raise outcome if outcome.is_a?(Exception)
2151
+ promise = (@recovery_promise ||= Async::Promise.new)
2152
+ promise.wait # :open, or raises the rejection from resume_parked!
1918
2153
  end
1919
2154
 
1920
2155
  def resume_parked!(outcome)
1921
- cond = @recovered_condition
1922
- @recovered_condition = nil
1923
- cond&.signal(outcome)
1924
- end
1925
-
1926
- def wait_for_any(*expected_classes)
1927
- condition = @reply_condition = Async::Condition.new
1928
- result = wait_with_timeout(condition) do
1929
- @reply_condition = nil if @reply_condition.equal?(condition)
2156
+ promise = @recovery_promise
2157
+ return unless promise
2158
+ # Keep the resolved promise in place as the latch for late arrivals; the
2159
+ # next episode replaces it via begin_recovery_wait!.
2160
+ outcome.is_a?(Exception) ? promise.reject(outcome) : promise.resolve(outcome)
2161
+ end
2162
+
2163
+ # Wait on the reply promise +send_and_wait+ registered BEFORE it wrote the
2164
+ # request. The promise latches, so a reply the dispatch fiber delivers
2165
+ # while the writer is still parked on a full write queue — a yield point
2166
+ # between send and wait under a Condition — is kept, not dropped.
2167
+ def wait_for_any(promise, *expected_classes)
2168
+ result = wait_with_timeout(promise) do
2169
+ @reply_promise = nil if @reply_promise.equal?(promise)
1930
2170
  # amq-protocol method classes report their AMQP name, e.g. "queue.declare-ok".
1931
2171
  "No reply to #{expected_classes.map(&:name).join('/')} within #{@rpc_timeout}s on channel #{@channel_id}"
1932
2172
  end
@@ -1964,18 +2204,206 @@ module AsyncRabbitMQ
1964
2204
  raise RpcTimeoutError, yield
1965
2205
  end
1966
2206
 
2207
+ # Re-subscribe every consumer after a reopen. What a failure means depends
2208
+ # on what the broker closed the channel over — channel.close names the
2209
+ # method that caused it:
2210
+ #
2211
+ # - This consumer's own basic.consume (a 404: its queue is gone): drop that
2212
+ # consumer, with a consumer.recovery_failed event, and reopen to
2213
+ # re-subscribe the survivors the close cancelled. The dropped set bounds
2214
+ # it, so a queue that stays gone is dropped once, not retried forever.
2215
+ # - A basic.publish, or a close that landed during the replay of the
2216
+ # unconfirmed messages: a replayed message the broker refuses (sent to an
2217
+ # exchange that is gone), not the consumer's fault. Reopen WITHOUT
2218
+ # replaying - replaying would draw the same close every time - and report
2219
+ # the unconfirmed messages as nacked, since their fate is unknown.
2220
+ # - Anything else that closed the channel (a qos refused on reopen, an ack
2221
+ # timeout): not the consumer's fault, and not the replay's. Reopen,
2222
+ # replaying as usual.
2223
+ # - A second close that was not a consumer's: give the channel up rather
2224
+ # than loop.
2225
+ # - A ChannelError that left the channel open (an unexpected reply): that
2226
+ # consumer is not subscribed now, but nothing closed; it stays registered
2227
+ # and the rest carry on.
2228
+ #
2229
+ # A connection or session error, anywhere here — the connection dropping
2230
+ # again mid-recovery, the session going away — is not a verdict on any
2231
+ # consumer or on the channel. It aborts and leaves everything, consumers
2232
+ # included, for the next recovery cycle; dropping or closing here would
2233
+ # turn a network blip into permanent loss with recovery still reporting
2234
+ # success.
1967
2235
  def re_register_consumers
1968
- @consumers.each do |tag, entry|
2236
+ return if @consumers.empty?
2237
+
2238
+ dropped = {}
2239
+ foreign_closes = 0
2240
+ replay = true
2241
+ restart = true
2242
+ while restart
2243
+ restart = false
2244
+ outcome = catch(:reregister) do
2245
+ @consumers.keys.each do |tag|
2246
+ next if dropped.key?(tag)
2247
+ entry = @consumers[tag]
2248
+ begin
2249
+ reopen_for_reregister!(replay: replay) unless open?
2250
+ basic_consume(entry[:queue_name], consumer_tag: tag, manual_ack: entry[:manual_ack],
2251
+ exclusive: entry[:exclusive], arguments: entry[:arguments] || {},
2252
+ on_error: entry[:on_error], &entry[:block])
2253
+ rescue ChannelError => e
2254
+ if open?
2255
+ # Nothing closed; this one is not subscribed, but neither is it
2256
+ # known to be gone. Keep it and carry on.
2257
+ @logger.error(self, "Channel #{@channel_id}: could not re-register consumer #{tag} on #{entry[:queue_name]} " \
2258
+ "(#{e.message}); it stays registered but is not consuming")
2259
+ next
2260
+ elsif consume_rejected?(e)
2261
+ dropped[tag] = e
2262
+ @logger.error(self, "Channel #{@channel_id}: consumer #{tag} on #{entry[:queue_name]} rejected (#{e.message}); dropping it")
2263
+ else
2264
+ foreign_closes += 1
2265
+ throw :reregister, [:give_up, e] if foreign_closes > 1
2266
+
2267
+ replay = false if replay_refused?(e)
2268
+ @logger.warn(self, "Channel #{@channel_id}: closed by the broker during consumer re-registration, " \
2269
+ "not by a consumer (#{e.message}); reopening#{replay ? '' : ' without replaying unconfirmed messages'}")
2270
+ end
2271
+ # The close cancelled the consumers already restored on this
2272
+ # channel; restart to re-subscribe them.
2273
+ restart = true
2274
+ break
2275
+ rescue => e
2276
+ @logger.warn(self, "Channel #{@channel_id}: consumer re-registration interrupted (#{e.class}: #{e.message}); " \
2277
+ "leaving consumers for the next recovery")
2278
+ throw :reregister, [:abort]
2279
+ end
2280
+ end
2281
+ [:done]
2282
+ end
2283
+
2284
+ case outcome.first
2285
+ when :abort then return
2286
+ when :give_up
2287
+ forget_dropped_consumers(dropped)
2288
+ give_up_reregistration!(outcome.last)
2289
+ return
2290
+ end
2291
+ end
2292
+
2293
+ # The last pass can end on a close with nothing left to subscribe (every
2294
+ # consumer was rejected). Reopen so the channel is usable and anything
2295
+ # parked on it is released.
2296
+ unless open?
1969
2297
  begin
1970
- basic_consume(entry[:queue_name], consumer_tag: tag, manual_ack: entry[:manual_ack],
1971
- exclusive: entry[:exclusive], arguments: entry[:arguments] || {},
1972
- on_error: entry[:on_error], &entry[:block])
2298
+ reopen_for_reregister!(replay: replay)
2299
+ rescue ChannelError => e
2300
+ forget_dropped_consumers(dropped)
2301
+ give_up_reregistration!(e)
2302
+ return
1973
2303
  rescue => e
1974
- # Typically 404: the queue is gone and was not recovered. The broker
1975
- # closes the channel on that, so say so instead of failing silently.
1976
- @logger.error("Channel #{@channel_id}: could not re-register consumer #{tag} on #{entry[:queue_name]}: #{e.class}: #{e.message}")
2304
+ @logger.warn(self, "Channel #{@channel_id}: reopen after re-registration interrupted (#{e.class}: #{e.message}); " \
2305
+ "leaving it for the next recovery")
2306
+ return
2307
+ end
2308
+ end
2309
+
2310
+ forget_dropped_consumers(dropped)
2311
+ end
2312
+
2313
+ # Forget the consumers the broker will not serve, and release anyone in
2314
+ # #each waiting on them: they are not coming back on their own.
2315
+ def forget_dropped_consumers(dropped)
2316
+ dropped.each_key do |tag|
2317
+ cancelled = @consumers.delete(tag)
2318
+ topology&.delete_consumer(tag)
2319
+ wake_each_waiters(tag)
2320
+ instrument("consumer.recovery_failed") do
2321
+ { channel: @channel_id, consumer_tag: tag, queue: cancelled&.dig(:queue_name), reason: :queue_deleted }
2322
+ end
2323
+ end
2324
+ end
2325
+
2326
+ # Whether the broker closed the channel over a basic.consume — the
2327
+ # consumer's own subscription, as opposed to anything else on the channel.
2328
+ def consume_rejected?(error)
2329
+ closed_over?(error, AMQ::Protocol::Basic::Consume)
2330
+ end
2331
+
2332
+ # Whether the close points at the replay of unconfirmed messages: a
2333
+ # basic.publish the broker refused, or a close that landed while they were
2334
+ # being replayed (raised by reopen_for_reregister!, with no close method).
2335
+ def replay_refused?(error)
2336
+ error.close_method.nil? || closed_over?(error, AMQ::Protocol::Basic::Publish)
2337
+ end
2338
+
2339
+ def closed_over?(error, method_class)
2340
+ close = error.close_method
2341
+ !close.nil? && close.class_id == AMQ::Protocol::Basic.method_id && close.method_id == method_class.method_id
2342
+ end
2343
+
2344
+ # Re-registration cannot bring this channel back. Close it for good: every
2345
+ # parked fiber is released with the error rather than waiting on a reopen
2346
+ # that is not coming, and the remaining consumers are kept, for
2347
+ # reopen(recover_consumers: true). The broker's close already released
2348
+ # this channel's id, and another channel may have been given it since:
2349
+ # only a session that still maps the id to THIS channel is told.
2350
+ def give_up_reregistration!(error)
2351
+ @logger.error(self, "Channel #{@channel_id}: giving up re-registering consumers (#{error.class}: #{error.message})")
2352
+ mark_closed!(error)
2353
+ return unless @session.respond_to?(:channels) && @session.channels.any? { |ch| ch.equal?(self) }
2354
+
2355
+ @session.channel_closed(@channel_id) rescue nil
2356
+ end
2357
+
2358
+ # The unconfirmed messages could not be replayed: report them to the
2359
+ # publisher as nacked, as a broker nack would — wait_for_confirms returns
2360
+ # false (or raises MessageNacked when tracking) and nacked_tags names
2361
+ # them — and reset the counter to match the broker's fresh numbering.
2362
+ def abandon_unconfirmed!
2363
+ abandoned = @pending_confirms.keys
2364
+ @pending_confirms = {}
2365
+ @delivery_tag = 0
2366
+ return if abandoned.empty?
2367
+
2368
+ @logger.warn(self, "Channel #{@channel_id}: #{abandoned.size} unconfirmed message(s) could not be re-published " \
2369
+ "and are reported as nacked")
2370
+ @nacked_tags.concat(abandoned)
2371
+ @nacked_this_cycle.concat(abandoned)
2372
+ @only_acks = false
2373
+ @confirm_condition&.signal
2374
+ release_outstanding_slots
2375
+ end
2376
+
2377
+ # Reopen the channel in place during consumer re-registration, after the
2378
+ # broker closed it. Keeps the same id; reopen_on restores prefetch,
2379
+ # confirm and tx mode. Leaves the channel :open.
2380
+ #
2381
+ # Like #reopen, and for the same reason: the broker restarts confirm
2382
+ # numbering at 1 on the reopened channel, so the unconfirmed messages are
2383
+ # replayed — which also resets @delivery_tag to match — before anything
2384
+ # new is published, or every later ack resolves the wrong publish. With
2385
+ # +replay+ false they are reported as nacked instead (see
2386
+ # #re_register_consumers). Reopened :resyncing first so a publisher
2387
+ # arriving meanwhile parks rather than taking a tag ahead of the replay.
2388
+ # If the channel did not stay :resyncing through the replay it is not
2389
+ # overwritten with :open: a connection loss raises as one (the next
2390
+ # recovery handles it), a broker close as a ChannelError.
2391
+ def reopen_for_reregister!(replay: true)
2392
+ begin_recovery_wait!
2393
+ @session.reopen_channel(self, state: :resyncing)
2394
+ if @confirms_enabled
2395
+ replay ? republish_unconfirmed : abandon_unconfirmed!
2396
+ end
2397
+ unless resyncing?
2398
+ if recovering?
2399
+ raise ConnectionError.new(code: 0, text: "Connection lost while reopening channel #{@channel_id}")
1977
2400
  end
2401
+
2402
+ raise ChannelError.new("Channel #{@channel_id} was closed while replaying unconfirmed messages",
2403
+ channel_id: @channel_id)
1978
2404
  end
2405
+ @state = :open
2406
+ resume_parked!(:open)
1979
2407
  end
1980
2408
 
1981
2409
  # Raise unless the channel is open. While the connection is being recovered