pgbus 0.26.1 → 0.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +25 -0
- data/README.md +30 -1
- data/Rakefile +7 -1
- data/app/views/pgbus/dashboard/_queues_table.html.erb +9 -5
- data/app/views/pgbus/queues/_queues_list.html.erb +10 -6
- data/config/locales/da.yml +1 -0
- data/config/locales/de.yml +1 -0
- data/config/locales/en.yml +1 -0
- data/config/locales/es.yml +1 -0
- data/config/locales/fi.yml +1 -0
- data/config/locales/fr.yml +1 -0
- data/config/locales/it.yml +1 -0
- data/config/locales/ja.yml +1 -0
- data/config/locales/nb.yml +1 -0
- data/config/locales/nl.yml +1 -0
- data/config/locales/pt.yml +1 -0
- data/config/locales/sv.yml +1 -0
- data/lib/pgbus/client/notify_stream.rb +16 -0
- data/lib/pgbus/configuration.rb +11 -1
- data/lib/pgbus/dedicated_connection.rb +20 -7
- data/lib/pgbus/engine.rb +8 -0
- data/lib/pgbus/integrations/appsignal/probe.rb +20 -1
- data/lib/pgbus/mcp/health_analyzer.rb +32 -2
- data/lib/pgbus/mcp/tools/dlq_detail_tool.rb +11 -2
- data/lib/pgbus/mcp/tools/queues_tool.rb +3 -0
- data/lib/pgbus/open_transaction.rb +96 -0
- data/lib/pgbus/signals/middleware.rb +23 -0
- data/lib/pgbus/signals.rb +282 -0
- data/lib/pgbus/streams.rb +3 -39
- data/lib/pgbus/testing/minitest.rb +1 -0
- data/lib/pgbus/testing.rb +36 -0
- data/lib/pgbus/version.rb +1 -1
- data/lib/pgbus/web/data_source/dead_letter.rb +35 -16
- data/lib/pgbus/web/data_source/job_list.rb +1 -1
- data/lib/pgbus/web/data_source/queue_summary.rb +1 -1
- data/lib/pgbus/web/data_source.rb +176 -56
- data/lib/pgbus/web/metrics_serializer.rb +34 -5
- data/lib/pgbus/web/queue_summary.rb +6 -1
- data/lib/pgbus/web/streamer/failover_listener.rb +132 -27
- data/lib/pgbus/web/streamer/hub_client.rb +46 -15
- data/lib/pgbus/web/streamer/hub_protocol.rb +6 -0
- data/lib/pgbus/web/streamer/instance.rb +37 -2
- data/lib/pgbus/web/streamer/listener.rb +113 -24
- data/lib/pgbus/web/streamer/master_hub.rb +87 -2
- data/lib/pgbus/web/streamer/signal_delivery.rb +136 -0
- data/lib/pgbus/web/streamer.rb +10 -0
- data/lib/pgbus.rb +21 -0
- data/sig/pgbus/client.rbs +1 -0
- data/sig/pgbus/configuration.rbs +2 -0
- data/sig/pgbus.rbs +13 -0
- metadata +5 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
# The caller's open ActiveRecord transaction, for work that must wait for
|
|
5
|
+
# its COMMIT: a durable stream broadcast (Streams::Stream) and a process
|
|
6
|
+
# signal (Signals). Guarded by defined? so both stay usable without Rails.
|
|
7
|
+
module OpenTransaction
|
|
8
|
+
# Runs nothing itself: hands the commit hook a block that runs after
|
|
9
|
+
# the commit (and never on rollback).
|
|
10
|
+
#
|
|
11
|
+
# Duck-typed as a record for Rails 7.1, whose transactions have no public
|
|
12
|
+
# after_commit: ActiveRecord calls committed! / rolledback! on every record
|
|
13
|
+
# added to a transaction. 7.2+ use Transaction#after_commit instead.
|
|
14
|
+
class CommitHook
|
|
15
|
+
def initialize(block)
|
|
16
|
+
@block = block
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def before_committed!; end
|
|
20
|
+
|
|
21
|
+
# should_run_callbacks is false for a duplicate of a record already in
|
|
22
|
+
# the transaction; a hook is only ever equal to itself.
|
|
23
|
+
def committed!(should_run_callbacks: true, **)
|
|
24
|
+
@block.call if should_run_callbacks
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def rolledback!(*, **); end
|
|
28
|
+
|
|
29
|
+
def trigger_transactional_callbacks?
|
|
30
|
+
true
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
# Returns the current AR transaction if one is open, nil otherwise.
|
|
37
|
+
# AR's NullTransaction yields immediately from after_commit, so we have to
|
|
38
|
+
# check #open? explicitly — otherwise every call path would hit the
|
|
39
|
+
# "deferred" branch and the caller would lose its return value.
|
|
40
|
+
#
|
|
41
|
+
# The probe must only inspect a connection the calling thread/fiber
|
|
42
|
+
# ALREADY leases — `connection_pool.active_connection?`, never
|
|
43
|
+
# `ActiveRecord::Base.connection`. On Rails 7.2+ `.connection` takes a
|
|
44
|
+
# sticky executor-scoped lease: on a non-executor thread (the
|
|
45
|
+
# Coalescer's flush thread, app worker threads) it is never released —
|
|
46
|
+
# one pool connection pinned per thread — and inside
|
|
47
|
+
# `with_connection` the sticky flag defeats the block-exit release, so
|
|
48
|
+
# the CALLER's connection leaks when its thread dies. Both variants
|
|
49
|
+
# exhausted an exactly-sized pool deterministically (Zazu fan-out
|
|
50
|
+
# incident, 2026-08-05). Semantics are unchanged: a transaction is
|
|
51
|
+
# per-lease, so a thread holding no connection can have no open
|
|
52
|
+
# transaction to defer on — the old code's fresh checkout always
|
|
53
|
+
# answered nil anyway, at the price of the leak.
|
|
54
|
+
def current
|
|
55
|
+
return nil unless defined?(::ActiveRecord::Base)
|
|
56
|
+
|
|
57
|
+
connection = ::ActiveRecord::Base.connection_pool.active_connection?
|
|
58
|
+
return nil unless connection
|
|
59
|
+
|
|
60
|
+
transaction = connection.current_transaction
|
|
61
|
+
transaction if transaction.open?
|
|
62
|
+
rescue StandardError => e
|
|
63
|
+
# Defensive: if AR is loaded but not yet connected (e.g. a
|
|
64
|
+
# Rake task invoked before Rails boot), don't let the transaction
|
|
65
|
+
# probe break the caller. Debug-logged so a misconfigured
|
|
66
|
+
# app can diagnose "why isn't my work deferring?" without impacting
|
|
67
|
+
# production performance (debug is off by default).
|
|
68
|
+
Pgbus.logger.debug do
|
|
69
|
+
"[Pgbus::OpenTransaction] transaction probe failed (#{e.class}: #{e.message}); " \
|
|
70
|
+
"falling back to running now"
|
|
71
|
+
end
|
|
72
|
+
nil
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Registers +block+ to run after the COMMIT of the caller's open,
|
|
76
|
+
# joinable transaction and returns that transaction; returns nil (and
|
|
77
|
+
# registers nothing) when there is none, so the caller runs the work now.
|
|
78
|
+
#
|
|
79
|
+
# A transaction that is not joinable is not deferred on: in an app's
|
|
80
|
+
# transactional tests that is the fixture transaction, which never
|
|
81
|
+
# commits, so a model's `after_commit { Pgbus.signal(...) }` would never
|
|
82
|
+
# send. Inside it, a `transaction do … end` block is joinable and its
|
|
83
|
+
# commit runs the callbacks, as a production commit does.
|
|
84
|
+
def defer(&block)
|
|
85
|
+
transaction = current
|
|
86
|
+
return nil unless transaction&.joinable?
|
|
87
|
+
|
|
88
|
+
if transaction.respond_to?(:after_commit)
|
|
89
|
+
transaction.after_commit(&block)
|
|
90
|
+
else
|
|
91
|
+
::ActiveRecord::Base.connection_pool.active_connection?.add_transaction_record(CommitHook.new(block))
|
|
92
|
+
end
|
|
93
|
+
transaction
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
module Signals
|
|
5
|
+
# Starts this process's streamer, on a background thread, at its first
|
|
6
|
+
# request when a process signal is registered (issue #674), so a web
|
|
7
|
+
# process that never served an SSE connection still receives signals. The
|
|
8
|
+
# request does not wait for the LISTEN: what it (or anything before it)
|
|
9
|
+
# read before the LISTEN is covered by the on_gap the streamer runs once
|
|
10
|
+
# its first LISTEN is in place. After that it costs one atomic read.
|
|
11
|
+
# Installed by Pgbus::Engine when streams are enabled.
|
|
12
|
+
class Middleware
|
|
13
|
+
def initialize(app)
|
|
14
|
+
@app = app
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def call(env)
|
|
18
|
+
Pgbus::Signals.start_listening!
|
|
19
|
+
@app.call(env)
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -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
|
-
#
|
|
395
|
-
#
|
|
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
|
-
|
|
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
|
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
|
@@ -9,7 +9,7 @@ module Pgbus
|
|
|
9
9
|
# The header path the error-class filter reads (DeadLetterHeader::KEY).
|
|
10
10
|
ERROR_CLASS_SQL = "headers #>> '{#{Pgbus::DeadLetterHeader::KEY},error_class}'".freeze
|
|
11
11
|
|
|
12
|
-
# DLQ queue names from
|
|
12
|
+
# DLQ queue names from queue_names are already fully qualified
|
|
13
13
|
# (e.g., "pgbus_default_dlq"), so we use them directly without re-prefixing.
|
|
14
14
|
# dlq: one DLQ by its full name (unknown names list nothing);
|
|
15
15
|
# error_class: only messages whose dead-letter block names that class.
|
|
@@ -25,27 +25,37 @@ module Pgbus
|
|
|
25
25
|
[]
|
|
26
26
|
end
|
|
27
27
|
|
|
28
|
+
# From the cached metrics, unless a filter needs the rows or a DLQ's
|
|
29
|
+
# metrics are unavailable (issue #677): then a COUNT over the tables,
|
|
30
|
+
# so the pager does not read a DLQ that lists rows as empty (unless
|
|
31
|
+
# that COUNT fails too: then 0, logged as an error).
|
|
28
32
|
def dlq_total_count(dlq: nil, error_class: nil)
|
|
29
33
|
names = dlq_queue_names(dlq)
|
|
30
34
|
return 0 if names.empty?
|
|
31
|
-
return dlq_counts_by_queue.values_at(*names).sum unless error_class
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
return dlq_counts_by_queue.values_at(*names).sum unless error_class || dlq_unmeasured?(names)
|
|
36
|
+
|
|
37
|
+
# In a savepoint: the DLQ whose metrics timed out may time out here
|
|
38
|
+
# too, and that must not abort a caller's transaction.
|
|
39
|
+
where = "#{ERROR_CLASS_SQL} = $1" if error_class
|
|
40
|
+
connection.transaction(requires_new: true) do
|
|
41
|
+
connection.select_value(
|
|
42
|
+
"SELECT COUNT(*) FROM (#{queue_message_fragments(names, where)}) AS combined",
|
|
43
|
+
"Pgbus DLQ Count",
|
|
44
|
+
error_class ? [error_class] : []
|
|
45
|
+
).to_i
|
|
46
|
+
end
|
|
38
47
|
rescue StandardError => e
|
|
39
|
-
Pgbus.logger.
|
|
48
|
+
Pgbus.logger.error { "[Pgbus::Web] Error fetching DLQ count: #{e.class}: #{e.message}" }
|
|
40
49
|
0
|
|
41
50
|
end
|
|
42
51
|
|
|
43
|
-
# { "pgbus_default_dlq" => 12, ... } for the filter chips
|
|
44
|
-
# cached metrics (no query of its
|
|
52
|
+
# { "pgbus_default_dlq" => 12, ... } for the filter chips: every DLQ
|
|
53
|
+
# from queue_names, its count from the cached metrics (no query of its
|
|
54
|
+
# own). A DLQ whose metrics are unavailable (issue #677) stays listed
|
|
55
|
+
# and counts 0.
|
|
45
56
|
def dlq_counts_by_queue
|
|
46
|
-
queues_with_metrics
|
|
47
|
-
|
|
48
|
-
.to_h { |q| [q[:name], q[:queue_length].to_i] }
|
|
57
|
+
lengths = queues_with_metrics.to_h { |q| [q[:name], q[:queue_length].to_i] }
|
|
58
|
+
dlq_names.to_h { |name| [name, lengths.fetch(name, 0)] }
|
|
49
59
|
rescue StandardError => e
|
|
50
60
|
Pgbus.logger.debug { "[Pgbus::Web] Error fetching DLQ counts: #{e.message}" }
|
|
51
61
|
{}
|
|
@@ -140,11 +150,20 @@ module Pgbus
|
|
|
140
150
|
|
|
141
151
|
private
|
|
142
152
|
|
|
143
|
-
# Only names that are real DLQs ever reach sanitize_name and SQL.
|
|
153
|
+
# Only names that are real DLQs ever reach sanitize_name and SQL. Names
|
|
154
|
+
# only: listing or opening a DLQ message runs no metrics statement.
|
|
144
155
|
def dlq_queue_names(dlq)
|
|
145
|
-
names =
|
|
156
|
+
names = dlq_names
|
|
146
157
|
dlq.nil? ? names : names & [dlq]
|
|
147
158
|
end
|
|
159
|
+
|
|
160
|
+
def dlq_names
|
|
161
|
+
queue_names.select { |name| name.end_with?(Pgbus::DEAD_LETTER_SUFFIX) }
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def dlq_unmeasured?(names)
|
|
165
|
+
queues_with_metrics.any? { |q| q[:metrics_unavailable] && names.include?(q[:name]) }
|
|
166
|
+
end
|
|
148
167
|
end
|
|
149
168
|
end
|
|
150
169
|
end
|
|
@@ -136,7 +136,7 @@ module Pgbus
|
|
|
136
136
|
# exist. Excluded queues stay known, so their failed rows never show up
|
|
137
137
|
# as orphans of an unknown queue.
|
|
138
138
|
def job_list_scope(queue_name, queues: nil, exclude: nil)
|
|
139
|
-
names =
|
|
139
|
+
names = queue_names.reject { |n| n.end_with?(Pgbus::DEAD_LETTER_SUFFIX) }
|
|
140
140
|
names &= queues if queues
|
|
141
141
|
return nil if queues && names.empty?
|
|
142
142
|
|
|
@@ -112,7 +112,7 @@ module Pgbus
|
|
|
112
112
|
end
|
|
113
113
|
|
|
114
114
|
def priority_siblings(name, logical)
|
|
115
|
-
|
|
115
|
+
queue_names.select do |n|
|
|
116
116
|
n != name && n.match?(Pgbus::Web::QueueSummary::PRIORITY_LEVEL) && logical_queue_name(n) == logical
|
|
117
117
|
end
|
|
118
118
|
end
|