pgbus 0.26.0 → 0.27.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.
@@ -0,0 +1,282 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "concurrent/atomic/atomic_reference"
4
+
5
+ module Pgbus
6
+ # Process signals (issue #674): run a block in every web process when any
7
+ # process sends a signal — the "drop your in-memory cache now" message.
8
+ #
9
+ # # config/initializers/widgets.rb
10
+ # Pgbus.on_signal(:widgets_changed, on_gap: -> { WIDGETS.clear }) { |_payload| WIDGETS.clear }
11
+ #
12
+ # # anywhere, after the change (inside a transaction it is sent at COMMIT)
13
+ # Pgbus.signal(:widgets_changed)
14
+ # Pgbus.signal(:widgets_changed, "id=42") # a String payload, under NOTIFY's 7999-byte cap
15
+ #
16
+ # Transport: a NOTIFY on one channel per signal, `<queue_prefix>_signal_<name>`,
17
+ # LISTENed by the connection the streamer already owns: the per-worker
18
+ # Listener under `streams_listen_scope :process`, the MasterHub's under
19
+ # `:master` (fanned out to the workers over the hub socket). Subscribers run
20
+ # on the streamer's signal delivery thread, never on the LISTEN thread, each
21
+ # inside the Rails executor; one that raises is reported and the others run.
22
+ #
23
+ # The registry is process-local, like Pgbus::Streams.filters: register in an
24
+ # initializer. With at least one subscriber, the first request a process
25
+ # serves starts the streamer on a background thread (Signals::Middleware),
26
+ # so a process that never served an SSE connection still listens and no
27
+ # request waits on the connect; with none, nothing changes.
28
+ #
29
+ # Delivery is at-most-once: a NOTIFY sent while a process was not LISTENing
30
+ # (before its streamer started, a reconnect, a hub failover) is lost. Every
31
+ # subscriber's `on_gap` runs once after each such gap, once the LISTEN is in
32
+ # place (the first LISTEN of a process included), so it can assume it
33
+ # missed signals.
34
+ module Signals
35
+ NAME_PATTERN = /\A[a-z0-9_]+\z/
36
+
37
+ # How long a failed eager start waits before the next request tries again.
38
+ START_RETRY_SECONDS = 30
39
+
40
+ # One registered block, and the optional callable run after a LISTEN gap.
41
+ Subscriber = Data.define(:name, :callback, :on_gap)
42
+
43
+ # Built at load, never `||=` (AGENTS.md, Never Do 5). @lock guards
44
+ # @subscribers (a frozen Hash of name → frozen Array of Subscriber,
45
+ # replaced whole on write, so a reader iterates a snapshot). @started_pid
46
+ # is the pid whose streamer started (an atomic, so the per-request check
47
+ # takes no lock once started). @start_lock guards the rest of the
48
+ # eager-start bookkeeping and is only held for constant-time work: the
49
+ # connect runs on a starter thread, outside it.
50
+ @lock = Mutex.new
51
+ @start_lock = Mutex.new
52
+ @subscribers = {}.freeze
53
+ @started_pid = Concurrent::AtomicReference.new(nil)
54
+ @starting_pid = nil
55
+ @failed_at = nil
56
+
57
+ class << self
58
+ # Pgbus.on_signal. Returns the Subscriber.
59
+ def subscribe(name, on_gap: nil, &block)
60
+ name = validate_name!(name)
61
+ raise ArgumentError, "Pgbus.on_signal(#{name.inspect}) needs a block" unless block
62
+ raise ArgumentError, "on_gap: must respond to #call (got #{on_gap.class})" if on_gap && !on_gap.respond_to?(:call)
63
+
64
+ subscriber = Subscriber.new(name: name, callback: block, on_gap: on_gap)
65
+ @lock.synchronize do
66
+ @subscribers = @subscribers.merge(name => [*@subscribers[name], subscriber].freeze).freeze
67
+ end
68
+ # A streamer already running in this process LISTENs on the new
69
+ # channel now; one started later subscribes every channel at start.
70
+ Pgbus::Web::Streamer.listen_signal(channel_for(name))
71
+ subscriber
72
+ end
73
+
74
+ # Pgbus.signal. Sends the NOTIFY now, or at the COMMIT of the caller's
75
+ # open, joinable ActiveRecord transaction (nothing is sent on its
76
+ # rollback; OpenTransaction.defer explains joinable). Returns nil.
77
+ def publish(name, payload = nil)
78
+ name = validate_name!(name)
79
+ validate_payload!(payload)
80
+ # A NOTIFY delivers an empty payload as none: the same in every mode.
81
+ # A frozen copy, so a caller mutating its String afterwards changes
82
+ # neither a deferred NOTIFY nor a test recording.
83
+ payload = payload.empty? ? nil : payload.dup.freeze if payload
84
+ return testing_signal(name, payload) if testing?
85
+
86
+ send_now = -> { Pgbus.client.notify_signal(name, payload) }
87
+ send_now.call unless OpenTransaction.defer(&send_now)
88
+ nil
89
+ end
90
+
91
+ def names
92
+ @lock.synchronize { @subscribers.keys }
93
+ end
94
+
95
+ def subscribed?
96
+ @lock.synchronize { @subscribers.any? }
97
+ end
98
+
99
+ def gap_handlers?
100
+ @lock.synchronize { @subscribers.values.flatten.any?(&:on_gap) }
101
+ end
102
+
103
+ # The NOTIFY channel of +name+: `<queue_prefix>_signal_<name>`, through
104
+ # config.queue_name, so it is bounded by the queue-name budget (47) and
105
+ # always a valid, unquoted-safe identifier under PostgreSQL's 63.
106
+ def channel_for(name)
107
+ Pgbus.configuration.queue_name("signal_#{name}")
108
+ end
109
+
110
+ def channels
111
+ names.map { |name| channel_for(name) }
112
+ end
113
+
114
+ # The registered signal whose channel is +channel+, or nil.
115
+ def name_for(channel)
116
+ names.find { |name| channel_for(name) == channel }
117
+ end
118
+
119
+ # Runs every subscriber of +name+ with +payload+, in registration order.
120
+ # On the streamer's signal delivery thread each runs in the Rails
121
+ # executor; Pgbus::Testing's inline mode passes executor: false, since it
122
+ # runs on the caller's thread, whose CurrentAttributes the executor's
123
+ # completion would reset. Never raises.
124
+ def deliver(name, payload, executor: true)
125
+ subscribers_of(name).each do |subscriber|
126
+ run_safely({ action: "signal_subscriber", signal: name }, executor: executor) do
127
+ subscriber.callback.call(payload)
128
+ end
129
+ end
130
+ nil
131
+ end
132
+
133
+ # Runs every subscriber's on_gap once. Never raises.
134
+ def deliver_gap
135
+ all = @lock.synchronize { @subscribers.values.flatten }
136
+ all.each do |subscriber|
137
+ next unless subscriber.on_gap
138
+
139
+ run_safely({ action: "signal_on_gap", signal: subscriber.name }, executor: true) { subscriber.on_gap.call }
140
+ end
141
+ nil
142
+ end
143
+
144
+ # The eager start Signals::Middleware runs on every request: with a
145
+ # subscriber, start this process's streamer once, on a background
146
+ # thread, so no request waits on the LISTEN connect (a connect to an
147
+ # unreachable streams host can take as long as the OS lets it). The
148
+ # streamer runs every on_gap once its first LISTEN is in place, which
149
+ # covers whatever the process cached before. A no-op under
150
+ # streams_test_mode (Pgbus::Testing.fake!/inline!), with streams
151
+ # disabled, and in a schema rake task. Never raises into the request: a
152
+ # failure is reported, and a request START_RETRY_SECONDS later tries
153
+ # again. Once started, it costs one atomic read.
154
+ def start_listening!
155
+ pid = ::Process.pid
156
+ return if started_pid == pid
157
+ return unless subscribed? && startable?
158
+
159
+ @start_lock.synchronize do
160
+ return if started_pid == pid || @starting_pid == pid
161
+ return if @failed_at && (monotonic_now - @failed_at) < START_RETRY_SECONDS
162
+
163
+ @starting_pid = pid
164
+ begin
165
+ # One short-lived starter thread per attempt, owned by this
166
+ # module: it ends when Streamer.current returns or raises.
167
+ Thread.new { start_streamer(pid) } # rubocop:disable ThreadSafety/NewThread
168
+ rescue ThreadError => e
169
+ # At the process's thread limit: not this request's problem.
170
+ @starting_pid = nil
171
+ @failed_at = monotonic_now
172
+ Pgbus::ErrorReporter.report(e, { action: "signals_start" })
173
+ end
174
+ end
175
+ nil
176
+ end
177
+
178
+ # Streamer.reset! tore this process's streamer down: the next request
179
+ # starts a new one.
180
+ def streamer_reset!
181
+ @start_lock.synchronize { @started_pid.set(nil) }
182
+ end
183
+
184
+ # A fresh registry. Tests only.
185
+ def reset!
186
+ @lock.synchronize { @subscribers = {}.freeze }
187
+ @start_lock.synchronize do
188
+ @started_pid.set(nil)
189
+ @starting_pid = nil
190
+ @failed_at = nil
191
+ end
192
+ end
193
+
194
+ private
195
+
196
+ def started_pid
197
+ # An AtomicReference built at load and never reassigned: reading it
198
+ # takes no lock (the per-request fast path).
199
+ @started_pid.get # rubocop:disable ThreadSafety/ClassInstanceVariable
200
+ end
201
+
202
+ def start_streamer(pid)
203
+ Pgbus::Web::Streamer.current
204
+ @start_lock.synchronize do
205
+ @started_pid.set(pid)
206
+ @failed_at = nil
207
+ end
208
+ rescue StandardError => e
209
+ @start_lock.synchronize { @failed_at = monotonic_now }
210
+ Pgbus::ErrorReporter.report(e, { action: "signals_start" })
211
+ ensure
212
+ # Also for a starter killed by a non-StandardError, so a later
213
+ # request can try again.
214
+ @start_lock.synchronize { @starting_pid = nil }
215
+ end
216
+
217
+ def startable?
218
+ config = Pgbus.configuration
219
+ config.streams_enabled && !config.streams_test_mode && !Pgbus.database_task?
220
+ end
221
+
222
+ def subscribers_of(name)
223
+ @lock.synchronize { @subscribers[name.to_s] } || []
224
+ end
225
+
226
+ def validate_name!(name)
227
+ string = name.to_s
228
+ unless NAME_PATTERN.match?(string)
229
+ raise ArgumentError,
230
+ "Invalid signal name #{name.inspect}: use lowercase letters, digits and underscores only"
231
+ end
232
+
233
+ budget = QueueNameValidator::MAX_QUEUE_NAME_LENGTH
234
+ channel = "#{Pgbus.configuration.queue_prefix}_signal_#{string}"
235
+ if channel.length > budget
236
+ raise ArgumentError,
237
+ "Signal name #{string.inspect} is too long: its channel #{channel.inspect} is " \
238
+ "#{channel.length} chars, the budget is #{budget}"
239
+ end
240
+
241
+ string
242
+ end
243
+
244
+ def validate_payload!(payload)
245
+ return if payload.nil?
246
+ raise ArgumentError, "A signal payload must be a String or nil (got #{payload.class})" unless payload.is_a?(String)
247
+
248
+ limit = Client::NotifyStream::NOTIFY_PAYLOAD_LIMIT_BYTES
249
+ return if payload.bytesize <= limit
250
+
251
+ raise ArgumentError, "A signal payload is #{payload.bytesize} bytes; NOTIFY caps it at #{limit}"
252
+ end
253
+
254
+ def run_safely(context, executor:, &)
255
+ executor ? with_executor(&) : yield
256
+ rescue StandardError => e
257
+ Pgbus::ErrorReporter.report(e, context)
258
+ end
259
+
260
+ def with_executor(&)
261
+ if defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application
262
+ ::Rails.application.executor.wrap(&)
263
+ else
264
+ yield
265
+ end
266
+ end
267
+
268
+ def testing?
269
+ defined?(Pgbus::Testing) && !Pgbus::Testing.disabled?
270
+ end
271
+
272
+ def testing_signal(name, payload)
273
+ Pgbus::Testing.record_signal(name, payload)
274
+ nil
275
+ end
276
+
277
+ def monotonic_now
278
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
279
+ end
280
+ end
281
+ end
282
+ end
data/lib/pgbus/streams.rb CHANGED
@@ -391,46 +391,10 @@ module Pgbus
391
391
  end
392
392
  end
393
393
 
394
- # Returns the current AR transaction if one is open, nil otherwise.
395
- # Guarded by defined? so the streams subsystem stays usable in
396
- # non-Rails contexts. AR's NullTransaction yields immediately from
397
- # after_commit, so we have to check #open? explicitly — otherwise
398
- # every call path would hit the "deferred" branch and we'd lose the
399
- # msg_id return value.
400
- #
401
- # The probe must only inspect a connection the calling thread/fiber
402
- # ALREADY leases — `connection_pool.active_connection?`, never
403
- # `ActiveRecord::Base.connection`. On Rails 7.2+ `.connection` takes a
404
- # sticky executor-scoped lease: on a non-executor thread (the
405
- # Coalescer's flush thread, app worker threads) it is never released —
406
- # one pool connection pinned per thread — and inside
407
- # `with_connection` the sticky flag defeats the block-exit release, so
408
- # the CALLER's connection leaks when its thread dies. Both variants
409
- # exhausted an exactly-sized pool deterministically (Zazu fan-out
410
- # incident, 2026-08-05). Semantics are unchanged: a transaction is
411
- # per-lease, so a thread holding no connection can have no open
412
- # transaction to defer on — the old code's fresh checkout always
413
- # answered nil anyway, at the price of the leak.
394
+ # The caller's open AR transaction, or nil (Pgbus::OpenTransaction.current
395
+ # explains the lease-safe probe).
414
396
  def current_open_transaction
415
- return nil unless defined?(::ActiveRecord::Base)
416
-
417
- connection = ::ActiveRecord::Base.connection_pool.active_connection?
418
- return nil unless connection
419
-
420
- transaction = connection.current_transaction
421
- transaction if transaction.open?
422
- rescue StandardError => e
423
- # Defensive: if AR is loaded but not yet connected (e.g. a
424
- # Rake task invoked before Rails boot), don't let the transaction
425
- # probe break the broadcast. Debug-logged so a misconfigured
426
- # app can diagnose "why aren't my transactional broadcasts
427
- # deferring?" without impacting production performance
428
- # (debug is off by default).
429
- Pgbus.logger.debug do
430
- "[Pgbus::Streams::Stream] transaction probe failed (#{e.class}: #{e.message}); " \
431
- "falling back to synchronous broadcast"
432
- end
433
- nil
397
+ OpenTransaction.current
434
398
  end
435
399
  end
436
400
  end
@@ -25,6 +25,7 @@ module Pgbus
25
25
  def before_setup
26
26
  Pgbus::Testing.fake!
27
27
  Pgbus::Testing.store.clear!
28
+ Pgbus::Testing.clear_signals!
28
29
  super
29
30
  end
30
31
  end
data/lib/pgbus/testing.rb CHANGED
@@ -14,6 +14,11 @@ module Pgbus
14
14
  # :fake — capture published events in an in-memory store (default for tests)
15
15
  # :inline — capture AND immediately dispatch to matching handlers
16
16
  # :disabled — pass through to the real publisher (production behavior)
17
+ #
18
+ # Process signals (Pgbus.signal, issue #674) follow the same modes: :fake
19
+ # records them in `Pgbus::Testing.signals`, :inline records them and runs the
20
+ # process's on_signal blocks synchronously (at the COMMIT of an open
21
+ # transaction, as the NOTIFY would be sent), :disabled sends the NOTIFY.
17
22
  module Testing
18
23
  MODES = %i[fake inline disabled].freeze
19
24
  MODE_KEY = :__pgbus_test_mode
@@ -68,8 +73,15 @@ module Pgbus
68
73
  end
69
74
  end
70
75
 
76
+ # One Pgbus.signal captured in fake or inline mode.
77
+ SignalRecord = Data.define(:name, :payload)
78
+
71
79
  # Eagerly initialize the store so concurrent access never races on creation.
72
80
  @store = EventStore.new
81
+ # Signals captured in fake/inline mode: a frozen Array replaced whole
82
+ # under its own lock.
83
+ @signals_lock = Mutex.new
84
+ @signals = [].freeze
73
85
 
74
86
  # The process-wide mode (`fake!` with no block). A module ivar under a lock
75
87
  # built at load, not `Thread.main[]`: that reads the main thread's CURRENT
@@ -120,6 +132,30 @@ module Pgbus
120
132
 
121
133
  attr_reader :store
122
134
 
135
+ # The signals Pgbus.signal captured in fake or inline mode, oldest first.
136
+ def signals
137
+ @signals_lock.synchronize { @signals }
138
+ end
139
+
140
+ def clear_signals!
141
+ @signals_lock.synchronize { @signals = [].freeze }
142
+ end
143
+
144
+ # Called by Pgbus::Signals.publish instead of a NOTIFY when the mode is
145
+ # :fake or :inline. Recorded (and, inline, delivered) when the NOTIFY
146
+ # would be sent: at the COMMIT of an open joinable transaction, never on
147
+ # its rollback. Inline delivery runs on the caller's thread without the
148
+ # Rails executor, so the caller's CurrentAttributes survive it.
149
+ def record_signal(name, payload)
150
+ record = SignalRecord.new(name: name.to_s, payload: payload)
151
+ inline = inline?
152
+ commit = lambda do
153
+ @signals_lock.synchronize { @signals = [*@signals, record].freeze }
154
+ Pgbus::Signals.deliver(record.name, payload, executor: false) if inline
155
+ end
156
+ commit.call unless Pgbus::OpenTransaction.defer(&commit)
157
+ end
158
+
123
159
  private
124
160
 
125
161
  def default_mode
data/lib/pgbus/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pgbus
4
- VERSION = "0.26.0"
4
+ VERSION = "0.27.0"
5
5
  end
@@ -21,12 +21,28 @@ module Pgbus
21
21
  # relies on it. ensure_listening NEVER raises to the dispatcher: on a
22
22
  # double failure (hub dead AND local build failing — e.g. DB down) it
23
23
  # logs and returns nil, matching the Listener's own ack-timeout
24
- # contract, which the dispatcher already tolerates.
24
+ # contract, which the dispatcher already tolerates, and a background
25
+ # thread retries the local build every `rebuild_interval` seconds until
26
+ # it succeeds or #stop (issue #674: a process signal has no later
27
+ # ensure_listening call to retry it).
28
+ #
29
+ # Process signal channels (issue #674) are recorded and replayed the
30
+ # same way. NOTIFYs sent between the hub's death and the local LISTEN
31
+ # are lost, so once a failover has re-LISTENed a signal channel it calls
32
+ # `on_gap` (the worker's signal delivery runs every on_gap block).
25
33
  class FailoverListener
26
- def initialize(hub_client:, local_listener_factory:, logger: Pgbus.logger)
34
+ REBUILD_INTERVAL_SECONDS = 5
35
+ REBUILD_JOIN_SECONDS = 2
36
+
37
+ def initialize(hub_client:, local_listener_factory:, on_gap: nil,
38
+ rebuild_interval: REBUILD_INTERVAL_SECONDS, logger: Pgbus.logger)
27
39
  @hub_client = hub_client
28
40
  @local_listener_factory = local_listener_factory
41
+ @on_gap = on_gap
42
+ @rebuild_interval = rebuild_interval
29
43
  @logger = logger
44
+ # #stop wakes the rebuild thread's wait through this queue.
45
+ @stop_signal = Queue.new
30
46
  # @state_mutex guards the cheap shared state (@subscriptions, @impl,
31
47
  # @failed_over) and is only ever held for constant-time work — the
32
48
  # dispatcher's ensure/remove path must never wait behind a failover
@@ -36,8 +52,12 @@ module Pgbus
36
52
  @state_mutex = Mutex.new
37
53
  @failover_mutex = Mutex.new
38
54
  @subscriptions = Set.new
55
+ @signal_subscriptions = Set.new
39
56
  @impl = hub_client
40
57
  @failed_over = false
58
+ # Guarded by @state_mutex.
59
+ @stopped = false
60
+ @rebuild_thread = nil
41
61
  end
42
62
 
43
63
  # Interface parity with Listener for Instance#start: the hub client
@@ -60,6 +80,19 @@ module Pgbus
60
80
  end
61
81
  end
62
82
 
83
+ # Same failover contract as ensure_listening, for a signal channel.
84
+ def ensure_signal_listening(channel)
85
+ @state_mutex.synchronize { @signal_subscriptions.add(channel) }
86
+ current_impl.ensure_signal_listening(channel)
87
+ rescue HubClient::HubUnavailableError
88
+ fail_over!
89
+ begin
90
+ current_impl.ensure_signal_listening(channel)
91
+ rescue HubClient::HubUnavailableError
92
+ nil
93
+ end
94
+ end
95
+
63
96
  def remove_listening(queue)
64
97
  @state_mutex.synchronize { @subscriptions.delete(queue) }
65
98
  current_impl.remove_listening(queue)
@@ -79,55 +112,127 @@ module Pgbus
79
112
  # The blocking build + replay runs OUTSIDE @state_mutex so concurrent
80
113
  # ensure/remove/stop calls never stall behind it.
81
114
  def fail_over!
82
- local = nil
115
+ signals = nil
83
116
  @failover_mutex.synchronize do
84
117
  return if @state_mutex.synchronize { @failed_over }
85
118
 
86
- local = @local_listener_factory.call
87
- @state_mutex.synchronize { @subscriptions.dup }.each { |q| local.ensure_listening(q) }
88
- # Subscriptions recorded between the snapshot and this swap arrive
89
- # via their own retried ensure_listening call on the new impl.
90
- @state_mutex.synchronize do
91
- @impl = local
92
- @failed_over = true
93
- end
94
- # Ownership transferred to @impl — the rescue must not stop it.
95
- local = nil
119
+ signals = swap_in_local!
96
120
  end
121
+ report_gap if signals == true
97
122
  rescue StandardError => e
98
- # A listener the factory STARTED but that never swapped in (the
99
- # replay raised) would otherwise leak its thread and LISTEN
100
- # connection alongside the dead hub client.
101
- begin
102
- local&.stop
103
- rescue StandardError
104
- nil
105
- end
106
123
  # Hub dead AND the local listener can't be built (DB down, config
107
- # broken). Mark failed-over so callers stop rebuilding; @impl stays
108
- # on the dead client — every ensure_listening resolves nil and the
109
- # dispatcher rides its existing timeout tolerance until the worker
110
- # recycles.
124
+ # broken). Mark failed-over so callers stop rebuilding
125
+ # synchronously; @impl stays on the dead client — every
126
+ # ensure_listening resolves nil and the dispatcher rides its
127
+ # existing timeout tolerance — while the rebuild thread retries.
111
128
  @state_mutex.synchronize { @failed_over = true }
112
129
  @logger.error do
113
130
  "[Pgbus::Streamer::FailoverListener] fallback listener failed to build " \
114
- "(#{e.class}: #{e.message}) — streams degraded until this worker recycles"
131
+ "(#{e.class}: #{e.message}) — streams and process signals degraded; " \
132
+ "retrying every #{@rebuild_interval}s"
115
133
  end
134
+ start_rebuild
116
135
  end
117
136
 
118
137
  # Snapshot of this component's live thread(s). Instance#shutdown! captures
119
138
  # it BEFORE calling #stop so a join that timed out is still observable
120
139
  # after #stop has cleared the reference (issue #443).
121
140
  def threads
122
- current_impl.threads
141
+ rebuild = @state_mutex.synchronize { @rebuild_thread }
142
+ rebuild&.alive? ? [*current_impl.threads, rebuild] : current_impl.threads
123
143
  end
124
144
 
125
145
  def stop
146
+ rebuild = @state_mutex.synchronize do
147
+ @stopped = true
148
+ @rebuild_thread
149
+ end
150
+ @stop_signal << :stop
151
+ rebuild&.join(REBUILD_JOIN_SECONDS)
152
+ # Never waits on a connect in flight: a rebuild that finishes after
153
+ # this sees @stopped and stops its own listener instead of swapping.
126
154
  current_impl.stop
127
155
  end
128
156
 
129
157
  private
130
158
 
159
+ # Builds a started local listener, replays every subscription on it
160
+ # and swaps it in. Returns true when it re-LISTENed a signal channel
161
+ # (the caller reports the gap), false when it re-LISTENed none, and
162
+ # :discarded when #stop came first or another build already swapped
163
+ # in (the listener is stopped, not swapped: only the hub client is
164
+ # ever replaced, so a live local listener is never orphaned). Raises when the build or the replay fails, after stopping
165
+ # a listener that never swapped in (it would leak its thread and
166
+ # LISTEN connection beside the dead client). Holds no lock across the
167
+ # build or the replay.
168
+ def swap_in_local!
169
+ local = @local_listener_factory.call
170
+ queues, signal_channels = @state_mutex.synchronize { [@subscriptions.dup, @signal_subscriptions.dup] }
171
+ queues.each { |q| local.ensure_listening(q) }
172
+ signal_channels.each { |channel| local.ensure_signal_listening(channel) }
173
+ swapped = @state_mutex.synchronize do
174
+ next false if @stopped || !@impl.equal?(@hub_client)
175
+
176
+ @impl = local
177
+ @failed_over = true
178
+ end
179
+ unless swapped
180
+ local.stop
181
+ return :discarded
182
+ end
183
+ # Subscriptions recorded during the replay went to the old impl;
184
+ # replay them on the new one.
185
+ late_queues, late_signals = @state_mutex.synchronize do
186
+ [@subscriptions - queues, @signal_subscriptions - signal_channels]
187
+ end
188
+ late_queues.each { |q| local.ensure_listening(q) }
189
+ late_signals.each { |channel| local.ensure_signal_listening(channel) }
190
+ signal_channels.any? || late_signals.any?
191
+ rescue StandardError
192
+ begin
193
+ local&.stop
194
+ rescue StandardError
195
+ nil
196
+ end
197
+ raise
198
+ end
199
+
200
+ def start_rebuild
201
+ @state_mutex.synchronize do
202
+ return if @stopped || @rebuild_thread&.alive?
203
+
204
+ # The retry thread, owned by this object: it ends once a local
205
+ # listener swaps in or #stop signals it; #stop joins it.
206
+ @rebuild_thread = Thread.new { rebuild_loop } # rubocop:disable ThreadSafety/NewThread
207
+ end
208
+ end
209
+
210
+ def rebuild_loop
211
+ loop do
212
+ break if @stop_signal.pop(timeout: @rebuild_interval)
213
+
214
+ # No @failover_mutex here: a connect in flight must not hold up
215
+ # #stop, nor fail_over! (which finds @failed_over set and returns).
216
+ result = swap_in_local!
217
+ break if result == :discarded
218
+
219
+ report_gap if result
220
+ @logger.info { "[Pgbus::Streamer::FailoverListener] fallback listener built; streams and process signals restored" }
221
+ break
222
+ rescue StandardError => e
223
+ @logger.warn do
224
+ "[Pgbus::Streamer::FailoverListener] fallback listener still failing to build (#{e.class}: #{e.message})"
225
+ end
226
+ end
227
+ end
228
+
229
+ # Signals sent while the hub was dying never reached this worker.
230
+ def report_gap
231
+ @on_gap&.call
232
+ rescue StandardError => e
233
+ @logger.error { "[Pgbus::Streamer::FailoverListener] on_gap raised: #{e.class}: #{e.message}" }
234
+ end
235
+
131
236
  def current_impl
132
237
  @state_mutex.synchronize { @impl }
133
238
  end