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
|
@@ -18,6 +18,13 @@ module Pgbus
|
|
|
18
18
|
# the FailoverListener's cue to swap in a per-worker Listener. One-way:
|
|
19
19
|
# once a worker has fallen back it stays local until it recycles
|
|
20
20
|
# (settled on #382 — no flap-back complexity).
|
|
21
|
+
#
|
|
22
|
+
# Process signals (issue #674): ensure_signal_listening subscribes a
|
|
23
|
+
# signal channel with the same ack contract ("ssub" → "sack"); the
|
|
24
|
+
# master's "signal" and "gap" frames go to the `signal_sink:` (the
|
|
25
|
+
# worker's SignalDelivery). A master from before signals never acks an
|
|
26
|
+
# "ssub", so the ack deadline fails this worker over to its own LISTEN:
|
|
27
|
+
# mixed versions during a rolling restart degrade, they do not go deaf.
|
|
21
28
|
class HubClient
|
|
22
29
|
class HubUnavailableError < StandardError; end
|
|
23
30
|
|
|
@@ -25,9 +32,10 @@ module Pgbus
|
|
|
25
32
|
# NotifyListener: a just-connected worker isn't treated as degraded
|
|
26
33
|
# before the hub has said anything.
|
|
27
34
|
def initialize(socket_path:, dispatch_queue:, ack_timeout: 2.0,
|
|
28
|
-
on_failure: nil, logger: Pgbus.logger)
|
|
35
|
+
on_failure: nil, signal_sink: nil, logger: Pgbus.logger)
|
|
29
36
|
@socket_path = socket_path
|
|
30
37
|
@dispatch_queue = dispatch_queue
|
|
38
|
+
@signal_sink = signal_sink
|
|
31
39
|
@ack_timeout = ack_timeout
|
|
32
40
|
@on_failure = on_failure
|
|
33
41
|
@logger = logger
|
|
@@ -73,21 +81,12 @@ module Pgbus
|
|
|
73
81
|
# transport — a hub that can't ack in time can't be trusted with the
|
|
74
82
|
# no-lost-broadcast contract either).
|
|
75
83
|
def ensure_listening(queue)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
waiter = Queue.new
|
|
79
|
-
@ack_mutex.synchronize { @pending_acks[queue] << waiter }
|
|
80
|
-
write_frame({ "t" => "sub", "q" => queue })
|
|
81
|
-
|
|
82
|
-
result = waiter.pop(timeout: @ack_timeout)
|
|
83
|
-
if result.nil?
|
|
84
|
-
discard_waiter(queue, waiter)
|
|
85
|
-
mark_dead("sub ack for #{queue} not received within #{@ack_timeout}s")
|
|
86
|
-
raise HubUnavailableError, "master hub ack timeout for #{queue}"
|
|
87
|
-
end
|
|
88
|
-
raise HubUnavailableError, "master hub died while awaiting ack for #{queue}" if result == :dead
|
|
84
|
+
await_ack(queue, { "t" => "sub", "q" => queue }, queue)
|
|
85
|
+
end
|
|
89
86
|
|
|
90
|
-
|
|
87
|
+
# The same contract for a process signal channel (issue #674).
|
|
88
|
+
def ensure_signal_listening(channel)
|
|
89
|
+
await_ack([:signal, channel], { "t" => "ssub", "c" => channel }, "signal #{channel}")
|
|
91
90
|
end
|
|
92
91
|
|
|
93
92
|
# Lazy GC, fire-and-forget — no correctness path waits on UNLISTEN
|
|
@@ -118,6 +117,24 @@ module Pgbus
|
|
|
118
117
|
|
|
119
118
|
private
|
|
120
119
|
|
|
120
|
+
def await_ack(key, frame, label)
|
|
121
|
+
raise HubUnavailableError, "master hub transport is dead" if @dead
|
|
122
|
+
|
|
123
|
+
waiter = Queue.new
|
|
124
|
+
@ack_mutex.synchronize { @pending_acks[key] << waiter }
|
|
125
|
+
write_frame(frame)
|
|
126
|
+
|
|
127
|
+
result = waiter.pop(timeout: @ack_timeout)
|
|
128
|
+
if result.nil?
|
|
129
|
+
discard_waiter(key, waiter)
|
|
130
|
+
mark_dead("sub ack for #{label} not received within #{@ack_timeout}s")
|
|
131
|
+
raise HubUnavailableError, "master hub ack timeout for #{label}"
|
|
132
|
+
end
|
|
133
|
+
raise HubUnavailableError, "master hub died while awaiting ack for #{label}" if result == :dead
|
|
134
|
+
|
|
135
|
+
:done
|
|
136
|
+
end
|
|
137
|
+
|
|
121
138
|
def reader_loop
|
|
122
139
|
loop do
|
|
123
140
|
frame = HubProtocol.read_frame(@sock)
|
|
@@ -143,6 +160,12 @@ module Pgbus
|
|
|
143
160
|
@dispatch_queue << Listener::WakeMessage.new(queue_name: frame["q"], payload: frame["p"])
|
|
144
161
|
when "ack"
|
|
145
162
|
@ack_mutex.synchronize { @pending_acks[frame["q"]].shift }&.push(:ack)
|
|
163
|
+
when "sack"
|
|
164
|
+
@ack_mutex.synchronize { @pending_acks[[:signal, frame["c"]]].shift }&.push(:ack)
|
|
165
|
+
when "signal"
|
|
166
|
+
to_signal_sink { |sink| sink.signal(frame["c"], frame["p"]) }
|
|
167
|
+
when "gap"
|
|
168
|
+
to_signal_sink(&:gap)
|
|
146
169
|
when "status"
|
|
147
170
|
@hub_healthy = frame["healthy"]
|
|
148
171
|
else
|
|
@@ -150,6 +173,14 @@ module Pgbus
|
|
|
150
173
|
end
|
|
151
174
|
end
|
|
152
175
|
|
|
176
|
+
# A raising sink must not reach reader_loop's rescue, which would mark
|
|
177
|
+
# a healthy transport dead.
|
|
178
|
+
def to_signal_sink
|
|
179
|
+
yield @signal_sink if @signal_sink
|
|
180
|
+
rescue StandardError => e
|
|
181
|
+
@logger.error { "[Pgbus::Streamer::HubClient] signal sink raised: #{e.class}: #{e.message}" }
|
|
182
|
+
end
|
|
183
|
+
|
|
153
184
|
# Frames must never interleave — all writes go through one mutex
|
|
154
185
|
# (writers: dispatcher thread via ensure/remove; no writer thread
|
|
155
186
|
# needed client-side, sub/unsub frames are tiny). Bounded: a master
|
|
@@ -15,9 +15,15 @@ module Pgbus
|
|
|
15
15
|
# Message shapes (JSON objects; "t" is the discriminator):
|
|
16
16
|
# worker → master: {t:"sub", q:} subscribe, synchronous — master acks
|
|
17
17
|
# {t:"unsub", q:} unsubscribe, fire-and-forget
|
|
18
|
+
# {t:"ssub", c:} subscribe a process signal channel (issue #674), master sacks
|
|
18
19
|
# master → worker: {t:"ack", q:} sub acknowledged (LISTEN active)
|
|
19
20
|
# {t:"wake", q:, p: <String|nil>} durable (p:nil) or ephemeral wake
|
|
20
21
|
# {t:"status", healthy: <bool>} listener health broadcast
|
|
22
|
+
# {t:"sack", c:} ssub acknowledged (LISTEN active)
|
|
23
|
+
# {t:"signal", c:, p: <String|nil>} a process signal, never dropped by the
|
|
24
|
+
# backpressure policy (an evicted worker
|
|
25
|
+
# loses its socket, fails over, and reports a gap)
|
|
26
|
+
# {t:"gap"} the hub's LISTEN reconnected: signals may be lost
|
|
21
27
|
#
|
|
22
28
|
# Reads are blocking (each side owns a dedicated reader thread); a short
|
|
23
29
|
# read means the peer died mid-frame and is reported as EOF (nil), never
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "concurrent/atomic/atomic_boolean"
|
|
4
|
+
|
|
3
5
|
module Pgbus
|
|
4
6
|
module Web
|
|
5
7
|
module Streamer
|
|
@@ -22,7 +24,7 @@ module Pgbus
|
|
|
22
24
|
# defaults from the configuration.
|
|
23
25
|
class Instance
|
|
24
26
|
attr_reader :registry, :listener, :dispatcher, :heartbeat, :dispatch_queue, :stream_counter, :pump,
|
|
25
|
-
:autoscaler, :peer_close_watcher
|
|
27
|
+
:autoscaler, :peer_close_watcher, :signal_delivery
|
|
26
28
|
|
|
27
29
|
def initialize(
|
|
28
30
|
client: Pgbus.client,
|
|
@@ -50,6 +52,14 @@ module Pgbus
|
|
|
50
52
|
if @config.streams_pool_autoscale && !@client.shared_connection?
|
|
51
53
|
Pgbus::Streams::PoolAutoscaler.new(client: @client, config: @config, logger: @logger)
|
|
52
54
|
end
|
|
55
|
+
# Runs process-signal subscribers (issue #674) on a thread of its
|
|
56
|
+
# own, started by the first signal: the listener and the hub client
|
|
57
|
+
# only hand it NOTIFYs and gaps.
|
|
58
|
+
@signal_delivery = SignalDelivery.new(logger: @logger)
|
|
59
|
+
# Set once #start has run its first-LISTEN gap: a hub failover
|
|
60
|
+
# during #start (an old master never acks "ssub") is covered by that
|
|
61
|
+
# gap, so it reports none of its own.
|
|
62
|
+
@signals_listening = Concurrent::AtomicBoolean.new(false)
|
|
53
63
|
@listener = build_listener(pg_connection, connection_factory)
|
|
54
64
|
# Off-thread durable fanout writer (issue #321). Built only when
|
|
55
65
|
# streams_writer_threads > 0; nil means fanout writes stay inline on
|
|
@@ -95,9 +105,29 @@ module Pgbus
|
|
|
95
105
|
@dispatcher.start
|
|
96
106
|
@heartbeat.start
|
|
97
107
|
@peer_close_watcher&.start
|
|
108
|
+
# Every process signal registered so far (issue #674); one
|
|
109
|
+
# registered later arrives through #listen_signal. Signals sent
|
|
110
|
+
# before this first LISTEN never reached the process (it may have
|
|
111
|
+
# cached since boot, or since a fork under preload_app!): that is a
|
|
112
|
+
# gap like any other, so every on_gap runs once.
|
|
113
|
+
channels = Pgbus::Signals.channels
|
|
114
|
+
channels.each { |channel| @listener.ensure_signal_listening(channel) }
|
|
115
|
+
# The gate first: a failover gap from here on is reported (and
|
|
116
|
+
# coalesces with this one while it is still queued).
|
|
117
|
+
@signals_listening.make_true
|
|
118
|
+
@signal_delivery.gap if channels.any?
|
|
98
119
|
self
|
|
99
120
|
end
|
|
100
121
|
|
|
122
|
+
# LISTEN on a process signal channel registered after #start (issue
|
|
123
|
+
# #674). Before #start, or after #shutdown!, nothing: #start
|
|
124
|
+
# subscribes every registered channel.
|
|
125
|
+
def listen_signal(channel)
|
|
126
|
+
return unless @shutdown_mutex.synchronize { @started }
|
|
127
|
+
|
|
128
|
+
@listener.ensure_signal_listening(channel)
|
|
129
|
+
end
|
|
130
|
+
|
|
101
131
|
# Enqueue a new SSE client. The dispatcher picks this up on its next
|
|
102
132
|
# iteration and runs the 5-step race-free replay sequence. The StreamApp
|
|
103
133
|
# calls this right after hijacking the socket.
|
|
@@ -161,6 +191,7 @@ module Pgbus
|
|
|
161
191
|
safely { @listener.stop }
|
|
162
192
|
safely { @dispatcher.stop }
|
|
163
193
|
safely { @pump&.stop }
|
|
194
|
+
safely { @signal_delivery.stop }
|
|
164
195
|
leaked = threads.select { |_, list| list.any?(&:alive?) }.keys
|
|
165
196
|
report_leaked_threads(leaked) if leaked.any?
|
|
166
197
|
close_all_connections
|
|
@@ -200,6 +231,7 @@ module Pgbus
|
|
|
200
231
|
# failover is assigned right below; a transport death in the gap
|
|
201
232
|
# is caught by the FailoverListener's synchronous ensure path.
|
|
202
233
|
on_failure: -> { failover&.fail_over! },
|
|
234
|
+
signal_sink: @signal_delivery,
|
|
203
235
|
logger: @logger
|
|
204
236
|
)
|
|
205
237
|
client.connect
|
|
@@ -208,6 +240,7 @@ module Pgbus
|
|
|
208
240
|
local_listener_factory: lambda do
|
|
209
241
|
build_local_listener(build_pg_connection, connection_factory).tap(&:start)
|
|
210
242
|
end,
|
|
243
|
+
on_gap: -> { @signal_delivery.gap if @signals_listening.true? },
|
|
211
244
|
logger: @logger
|
|
212
245
|
)
|
|
213
246
|
rescue HubClient::HubUnavailableError => e
|
|
@@ -229,6 +262,7 @@ module Pgbus
|
|
|
229
262
|
# own prune_dead self-post never block.
|
|
230
263
|
dispatch_queue_limit: @config.streams_dispatch_queue_limit,
|
|
231
264
|
maintenance: build_autoscale_maintenance,
|
|
265
|
+
signal_sink: @signal_delivery,
|
|
232
266
|
logger: @logger,
|
|
233
267
|
# On reconnect the Listener rebuilds its OWN connection via this
|
|
234
268
|
# factory (fresh connect re-resolves DNS, converges on the promoted
|
|
@@ -256,7 +290,8 @@ module Pgbus
|
|
|
256
290
|
"peer_close_watcher" => @peer_close_watcher ? @peer_close_watcher.threads : [],
|
|
257
291
|
"listener" => @listener.threads,
|
|
258
292
|
"dispatcher" => @dispatcher.threads,
|
|
259
|
-
"pump" => @pump ? @pump.threads : []
|
|
293
|
+
"pump" => @pump ? @pump.threads : [],
|
|
294
|
+
"signal_delivery" => @signal_delivery.threads
|
|
260
295
|
}
|
|
261
296
|
end
|
|
262
297
|
|
|
@@ -43,6 +43,14 @@ module Pgbus
|
|
|
43
43
|
# PG_NOTIFY('pgmq.' || TG_TABLE_NAME || '.' || TG_OP, NULL)
|
|
44
44
|
# For a queue named `pgbus_stream_chat` the trigger table is
|
|
45
45
|
# `q_pgbus_stream_chat`, so the channel is `pgmq.q_pgbus_stream_chat.INSERT`.
|
|
46
|
+
#
|
|
47
|
+
# Process signals (issue #674) LISTEN on raw channels beside those
|
|
48
|
+
# (ensure_signal_listening, `<queue_prefix>_signal_<name>`). A NOTIFY on
|
|
49
|
+
# a channel outside the pgmq pattern goes to the `signal_sink:`, never to
|
|
50
|
+
# the dispatch queue and never dropped; a reconnect that re-LISTENed a
|
|
51
|
+
# signal channel tells the sink once (#gap), since NOTIFYs sent while the
|
|
52
|
+
# connection was down are lost. The sink runs on this thread: it only
|
|
53
|
+
# hands off (a queue push).
|
|
46
54
|
class Listener
|
|
47
55
|
# Kept Ractor-shareable (issue #527): the hand-off to the dispatcher
|
|
48
56
|
# is the seam a Ractor dispatcher would pass by reference. The Strings
|
|
@@ -64,6 +72,10 @@ module Pgbus
|
|
|
64
72
|
|
|
65
73
|
RECONNECT_BACKOFF_SECONDS = 0.5
|
|
66
74
|
|
|
75
|
+
# A process signal channel (issue #674): `<queue_prefix>_signal_<name>`,
|
|
76
|
+
# within PostgreSQL's 63-byte identifier limit.
|
|
77
|
+
SIGNAL_CHANNEL_PATTERN = /\A[a-z0-9_]{1,63}\z/
|
|
78
|
+
|
|
67
79
|
# Grace added to the ack budget when #stop joins the listener thread.
|
|
68
80
|
# See #stop_join_timeout.
|
|
69
81
|
STOP_JOIN_GRACE_SECONDS = 5
|
|
@@ -93,9 +105,12 @@ module Pgbus
|
|
|
93
105
|
# `ack_timeout_ms:` bounds how long ensure_listening waits for this
|
|
94
106
|
# thread's ack, and (plus a grace) how long #stop joins it
|
|
95
107
|
# (streams_listen_ack_timeout_ms; issue #664).
|
|
108
|
+
# `signal_sink:` receives process signals (issue #674): #signal(channel,
|
|
109
|
+
# payload) per NOTIFY on a signal channel and #gap after a reconnect
|
|
110
|
+
# that re-LISTENed one. nil: such NOTIFYs are ignored.
|
|
96
111
|
def initialize(pg_connection:, dispatch_queue:, health_check_ms:,
|
|
97
112
|
connection_factory:, ack_timeout_ms: DEFAULT_ACK_TIMEOUT_MS, dispatch_queue_limit: 0,
|
|
98
|
-
maintenance: nil, logger: Pgbus.logger, clock: nil)
|
|
113
|
+
maintenance: nil, signal_sink: nil, logger: Pgbus.logger, clock: nil)
|
|
99
114
|
raise ArgumentError, "connection_factory is required" unless connection_factory.respond_to?(:call)
|
|
100
115
|
|
|
101
116
|
@conn = pg_connection
|
|
@@ -106,6 +121,7 @@ module Pgbus
|
|
|
106
121
|
@connection_factory = connection_factory
|
|
107
122
|
@dispatch_queue_limit = dispatch_queue_limit
|
|
108
123
|
@maintenance = maintenance
|
|
124
|
+
@signal_sink = signal_sink
|
|
109
125
|
@clock = clock || -> { ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) }
|
|
110
126
|
@maintenance_last = nil
|
|
111
127
|
@dropped_wakes = 0
|
|
@@ -225,19 +241,21 @@ module Pgbus
|
|
|
225
241
|
# default 1.25 s; issue #664), so a stuck listener can't hang the
|
|
226
242
|
# dispatcher forever.
|
|
227
243
|
def ensure_listening(queue_name)
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
return nil if @stopped
|
|
244
|
+
request_listen(:listen, queue_name)
|
|
245
|
+
end
|
|
231
246
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
return nil if @stopped
|
|
247
|
+
# Synchronously LISTEN on a process signal's raw channel (issue #674),
|
|
248
|
+
# with ensure_listening's ack contract: once acked, a NOTIFY on it
|
|
249
|
+
# reaches the signal sink.
|
|
250
|
+
def ensure_signal_listening(channel)
|
|
251
|
+
request_listen(:listen_channel, validate_signal_channel!(channel))
|
|
252
|
+
end
|
|
239
253
|
|
|
240
|
-
|
|
254
|
+
# Asynchronous UNLISTEN of a signal channel (the master hub, when its
|
|
255
|
+
# last worker subscriber leaves).
|
|
256
|
+
def remove_signal_listening(channel)
|
|
257
|
+
@commands << [:unlisten_channel, validate_signal_channel!(channel)]
|
|
258
|
+
wake
|
|
241
259
|
end
|
|
242
260
|
|
|
243
261
|
# Asynchronous: lazy GC of LISTENs whose subscriber count
|
|
@@ -250,6 +268,36 @@ module Pgbus
|
|
|
250
268
|
|
|
251
269
|
private
|
|
252
270
|
|
|
271
|
+
# The channel is interpolated into LISTEN "…": only the identifier
|
|
272
|
+
# characters Pgbus::Signals.channel_for produces may reach it (a hub
|
|
273
|
+
# worker's frame included).
|
|
274
|
+
def validate_signal_channel!(channel)
|
|
275
|
+
return channel if channel.is_a?(String) && SIGNAL_CHANNEL_PATTERN.match?(channel)
|
|
276
|
+
|
|
277
|
+
raise ArgumentError, "invalid signal channel #{channel.inspect}"
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
def request_listen(kind, name)
|
|
281
|
+
# A connect the dispatcher drains during shutdown (Instance#shutdown!
|
|
282
|
+
# stops the listener first) must not wait out the ack budget.
|
|
283
|
+
return nil if @stopped
|
|
284
|
+
|
|
285
|
+
ack = Queue.new
|
|
286
|
+
@commands << [kind, name, ack]
|
|
287
|
+
wake
|
|
288
|
+
# A stop that landed between the check above and the push may have
|
|
289
|
+
# let the thread release its queue and exit before the push: no ack
|
|
290
|
+
# would ever come. Pushed before that release, the command is acked.
|
|
291
|
+
return nil if @stopped
|
|
292
|
+
|
|
293
|
+
result = ack.pop(timeout: ack_timeout)
|
|
294
|
+
# Abandoned: the thread sees the closed queue when it gets to the
|
|
295
|
+
# command, and a signal LISTEN that lands this late reports a gap
|
|
296
|
+
# (the caller already went on as if it were listening).
|
|
297
|
+
ack.close if result.nil?
|
|
298
|
+
result
|
|
299
|
+
end
|
|
300
|
+
|
|
253
301
|
def run_loop
|
|
254
302
|
schedule_health_check
|
|
255
303
|
loop do
|
|
@@ -369,7 +417,7 @@ module Pgbus
|
|
|
369
417
|
# Acks held back by a LISTEN that raised: the reconnect that
|
|
370
418
|
# re-LISTENed their channel is done (or the thread is exiting).
|
|
371
419
|
def release_held_acks
|
|
372
|
-
@acks_after_reconnect.each { |ack| ack
|
|
420
|
+
@acks_after_reconnect.each { |ack| release_ack(ack) }
|
|
373
421
|
@acks_after_reconnect.clear
|
|
374
422
|
end
|
|
375
423
|
|
|
@@ -379,7 +427,7 @@ module Pgbus
|
|
|
379
427
|
def release_pending_acks
|
|
380
428
|
loop do
|
|
381
429
|
cmd = @commands.pop(true)
|
|
382
|
-
cmd[2]
|
|
430
|
+
release_ack(cmd[2]) if cmd[2] && %i[listen listen_channel].include?(cmd[0])
|
|
383
431
|
end
|
|
384
432
|
rescue ThreadError
|
|
385
433
|
nil
|
|
@@ -399,10 +447,11 @@ module Pgbus
|
|
|
399
447
|
run_health_check unless (@health_check_due_at - @clock.call).positive?
|
|
400
448
|
cmd = @commands.pop(true)
|
|
401
449
|
case cmd[0]
|
|
402
|
-
when :listen
|
|
450
|
+
when :listen, :listen_channel
|
|
403
451
|
ack = cmd[2]
|
|
404
452
|
begin
|
|
405
|
-
|
|
453
|
+
do_listen_channel(cmd[0] == :listen ? channel_for(cmd[1]) : cmd[1])
|
|
454
|
+
report_late_signal_listen if cmd[0] == :listen_channel && ack&.closed?
|
|
406
455
|
rescue StandardError
|
|
407
456
|
# The connection failed under the LISTEN. run_loop
|
|
408
457
|
# reconnects, and reconnect! re-LISTENs this channel with the
|
|
@@ -412,9 +461,10 @@ module Pgbus
|
|
|
412
461
|
ack = nil
|
|
413
462
|
raise
|
|
414
463
|
ensure
|
|
415
|
-
ack
|
|
464
|
+
release_ack(ack) if ack
|
|
416
465
|
end
|
|
417
|
-
when :unlisten then
|
|
466
|
+
when :unlisten then do_unlisten_channel(channel_for(cmd[1]))
|
|
467
|
+
when :unlisten_channel then do_unlisten_channel(cmd[1])
|
|
418
468
|
end
|
|
419
469
|
rescue ThreadError
|
|
420
470
|
# empty queue
|
|
@@ -447,8 +497,7 @@ module Pgbus
|
|
|
447
497
|
# no-second-wait rule rests on that, issue #630). The exception is a
|
|
448
498
|
# thread on its way out (stop, or an unexpected error): run_loop's
|
|
449
499
|
# ensure releases every waiting caller with nothing LISTENed.
|
|
450
|
-
def
|
|
451
|
-
channel = channel_for(queue_name)
|
|
500
|
+
def do_listen_channel(channel)
|
|
452
501
|
return if @listening_to.include?(channel)
|
|
453
502
|
|
|
454
503
|
@listening_to.add(channel)
|
|
@@ -457,8 +506,7 @@ module Pgbus
|
|
|
457
506
|
|
|
458
507
|
# The channel leaves @listening_to BEFORE the exec, so a reconnect
|
|
459
508
|
# after a failed UNLISTEN does not LISTEN it again.
|
|
460
|
-
def
|
|
461
|
-
channel = channel_for(queue_name)
|
|
509
|
+
def do_unlisten_channel(channel)
|
|
462
510
|
return unless @listening_to.include?(channel)
|
|
463
511
|
|
|
464
512
|
@listening_to.delete(channel)
|
|
@@ -467,7 +515,7 @@ module Pgbus
|
|
|
467
515
|
|
|
468
516
|
def handle_notify(channel, payload = nil)
|
|
469
517
|
queue_name = queue_name_from(channel)
|
|
470
|
-
return unless queue_name
|
|
518
|
+
return handle_signal(channel, payload) unless queue_name
|
|
471
519
|
|
|
472
520
|
# Backpressure applies ONLY to durable wakes (payload nil): they
|
|
473
521
|
# self-heal because the next durable wake for the stream re-reads
|
|
@@ -492,6 +540,42 @@ module Pgbus
|
|
|
492
540
|
@dispatch_queue << WakeMessage.new(queue_name: queue_name, payload: payload)
|
|
493
541
|
end
|
|
494
542
|
|
|
543
|
+
# A waiter that timed out closed its queue (request_listen).
|
|
544
|
+
def release_ack(ack)
|
|
545
|
+
ack.push(:done) unless ack.closed?
|
|
546
|
+
rescue ClosedQueueError
|
|
547
|
+
nil
|
|
548
|
+
end
|
|
549
|
+
|
|
550
|
+
# ensure_signal_listening timed out before this LISTEN ran, so its
|
|
551
|
+
# caller went on as if the channel were live: whatever was sent in
|
|
552
|
+
# between is a gap.
|
|
553
|
+
def report_late_signal_listen
|
|
554
|
+
@signal_sink&.gap
|
|
555
|
+
rescue StandardError => e
|
|
556
|
+
@logger.error { "[Pgbus::Streamer::Listener] signal sink gap raised: #{e.class}: #{e.message}" }
|
|
557
|
+
end
|
|
558
|
+
|
|
559
|
+
# A NOTIFY outside the pgmq pattern: only signal channels are LISTENed
|
|
560
|
+
# besides those. Never dropped, and a raising sink never stops the loop.
|
|
561
|
+
def handle_signal(channel, payload)
|
|
562
|
+
@signal_sink&.signal(channel, payload)
|
|
563
|
+
rescue StandardError => e
|
|
564
|
+
@logger.error { "[Pgbus::Streamer::Listener] signal sink raised: #{e.class}: #{e.message}" }
|
|
565
|
+
end
|
|
566
|
+
|
|
567
|
+
# After a reconnect: NOTIFYs on a signal channel sent while the
|
|
568
|
+
# connection was down are lost, so the sink hears about the gap once
|
|
569
|
+
# the new LISTENs are in place. Stream channels need no such report
|
|
570
|
+
# (a durable wake re-reads from the cursor).
|
|
571
|
+
def report_gap(channels)
|
|
572
|
+
return unless @signal_sink && channels.any? { |channel| !pgmq_channel?(channel) }
|
|
573
|
+
|
|
574
|
+
@signal_sink.gap
|
|
575
|
+
rescue StandardError => e
|
|
576
|
+
@logger.error { "[Pgbus::Streamer::Listener] signal sink gap raised: #{e.class}: #{e.message}" }
|
|
577
|
+
end
|
|
578
|
+
|
|
495
579
|
# The next keepalive is due one cycle after this one ENDS: scheduled
|
|
496
580
|
# from its start, a keepalive slower than a cycle would leave every
|
|
497
581
|
# pass overdue and the loop running SELECT 1 back to back without ever
|
|
@@ -561,6 +645,7 @@ module Pgbus
|
|
|
561
645
|
|
|
562
646
|
@conn = new_conn
|
|
563
647
|
@listening_to = Set.new(channels)
|
|
648
|
+
report_gap(channels)
|
|
564
649
|
return
|
|
565
650
|
end
|
|
566
651
|
ensure
|
|
@@ -579,8 +664,12 @@ module Pgbus
|
|
|
579
664
|
"#{CHANNEL_PREFIX}#{queue_name}#{CHANNEL_SUFFIX}"
|
|
580
665
|
end
|
|
581
666
|
|
|
667
|
+
def pgmq_channel?(channel)
|
|
668
|
+
channel.start_with?(CHANNEL_PREFIX) && channel.end_with?(CHANNEL_SUFFIX)
|
|
669
|
+
end
|
|
670
|
+
|
|
582
671
|
def queue_name_from(channel)
|
|
583
|
-
return nil unless
|
|
672
|
+
return nil unless pgmq_channel?(channel)
|
|
584
673
|
|
|
585
674
|
channel[CHANNEL_PREFIX.length..-(CHANNEL_SUFFIX.length + 1)]
|
|
586
675
|
end
|
|
@@ -41,7 +41,38 @@ module Pgbus
|
|
|
41
41
|
# is guarded by @table_mutex; each worker's outbox by its own mutex.
|
|
42
42
|
# All socket WRITES go through that worker's writer thread (frames must
|
|
43
43
|
# never interleave).
|
|
44
|
+
#
|
|
45
|
+
# Process signals (issue #674): a worker subscribes a signal channel
|
|
46
|
+
# with an "ssub" frame (register first, LISTEN second, "sack" last, as
|
|
47
|
+
# for a stream), refcounted per channel like the queues. The listener
|
|
48
|
+
# hands each signal NOTIFY and each reconnect gap to a SignalForwarder,
|
|
49
|
+
# which queues them for the fanout thread beside the wakes: "signal"
|
|
50
|
+
# frames go to the channel's subscribers and "gap" frames to every
|
|
51
|
+
# worker with a signal subscription, never dropped. The master runs no
|
|
52
|
+
# subscriber blocks itself; the workers subscribe what their own
|
|
53
|
+
# registries hold.
|
|
44
54
|
class MasterHub
|
|
55
|
+
# A signal NOTIFY the hub's listener received, for the fanout thread.
|
|
56
|
+
SignalMessage = Data.define(:channel, :payload)
|
|
57
|
+
# The hub listener reconnected with signal channels: tell the workers.
|
|
58
|
+
SIGNAL_GAP = :signal_gap
|
|
59
|
+
|
|
60
|
+
# The hub listener's signal sink: queue pushes only (it runs on the
|
|
61
|
+
# listener thread).
|
|
62
|
+
class SignalForwarder
|
|
63
|
+
def initialize(dispatch_queue)
|
|
64
|
+
@dispatch_queue = dispatch_queue
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def signal(channel, payload)
|
|
68
|
+
@dispatch_queue << SignalMessage.new(channel: channel, payload: payload)
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def gap
|
|
72
|
+
@dispatch_queue << SIGNAL_GAP
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
45
76
|
DEFAULT_DURABLE_QUEUE_LIMIT = 256
|
|
46
77
|
DEFAULT_HARD_QUEUE_LIMIT = 1024
|
|
47
78
|
# Status is rebroadcast every REBROADCAST_TICKS status intervals even
|
|
@@ -76,6 +107,8 @@ module Pgbus
|
|
|
76
107
|
# already-unsubscribed channel (in-flight NOTIFYs after the last
|
|
77
108
|
# unsub, per-record stream names → unbounded, review on #384).
|
|
78
109
|
@queue_refs = {}
|
|
110
|
+
# channel → Set of worker ids, like @queue_refs (issue #674).
|
|
111
|
+
@signal_refs = {}
|
|
79
112
|
@stop_signal = Queue.new
|
|
80
113
|
@next_id = 0
|
|
81
114
|
@dropped_durable_wakes = 0
|
|
@@ -91,7 +124,9 @@ module Pgbus
|
|
|
91
124
|
@table_mutex.synchronize { @evicted_workers }
|
|
92
125
|
end
|
|
93
126
|
|
|
94
|
-
# The factory must return a STARTED listener wired to +dispatch_queue
|
|
127
|
+
# The factory must return a STARTED listener wired to +dispatch_queue+,
|
|
128
|
+
# with a SignalForwarder.new(dispatch_queue) as its signal_sink for
|
|
129
|
+
# process signals.
|
|
95
130
|
# If any step after the listener exists fails (bad socket path, chmod,
|
|
96
131
|
# thread spawn), the listener — and its dedicated LISTEN connection,
|
|
97
132
|
# the exact resource this hub conserves — is stopped before the error
|
|
@@ -172,6 +207,7 @@ module Pgbus
|
|
|
172
207
|
ack_timeout_ms: @config.streams_listen_ack_timeout_ms,
|
|
173
208
|
connection_factory: build_connection,
|
|
174
209
|
dispatch_queue_limit: @config.streams_dispatch_queue_limit,
|
|
210
|
+
signal_sink: SignalForwarder.new(dispatch_queue),
|
|
175
211
|
logger: @logger
|
|
176
212
|
).tap(&:start)
|
|
177
213
|
end
|
|
@@ -201,7 +237,7 @@ module Pgbus
|
|
|
201
237
|
|
|
202
238
|
def register_worker(sock)
|
|
203
239
|
entry = {
|
|
204
|
-
sock: sock, subs: Set.new, outbox: [], durable_count: 0, open: true,
|
|
240
|
+
sock: sock, subs: Set.new, signals: Set.new, outbox: [], durable_count: 0, open: true,
|
|
205
241
|
outbox_mutex: Mutex.new, outbox_cond: ConditionVariable.new
|
|
206
242
|
}
|
|
207
243
|
id = @table_mutex.synchronize do
|
|
@@ -240,6 +276,7 @@ module Pgbus
|
|
|
240
276
|
case frame["t"]
|
|
241
277
|
when "sub" then handle_sub(id, entry, frame["q"])
|
|
242
278
|
when "unsub" then handle_unsub(id, frame["q"])
|
|
279
|
+
when "ssub" then handle_signal_sub(id, entry, frame["c"])
|
|
243
280
|
else
|
|
244
281
|
@logger.warn { "[Pgbus::Streamer::MasterHub] worker #{id} sent unknown frame: #{frame["t"].inspect}" }
|
|
245
282
|
end
|
|
@@ -258,6 +295,16 @@ module Pgbus
|
|
|
258
295
|
enqueue_frame(id, entry, { "t" => "ack", "q" => queue }, droppable: false)
|
|
259
296
|
end
|
|
260
297
|
|
|
298
|
+
# The same ordering for a process signal channel.
|
|
299
|
+
def handle_signal_sub(id, entry, channel)
|
|
300
|
+
@table_mutex.synchronize do
|
|
301
|
+
entry[:signals].add(channel)
|
|
302
|
+
(@signal_refs[channel] ||= Set.new).add(id)
|
|
303
|
+
end
|
|
304
|
+
@listener.ensure_signal_listening(channel)
|
|
305
|
+
enqueue_frame(id, entry, { "t" => "sack", "c" => channel }, droppable: false)
|
|
306
|
+
end
|
|
307
|
+
|
|
261
308
|
def handle_unsub(id, queue)
|
|
262
309
|
release_queue_refs(id, [queue])
|
|
263
310
|
@table_mutex.synchronize { @workers[id]&.[](:subs)&.delete(queue) }
|
|
@@ -278,6 +325,9 @@ module Pgbus
|
|
|
278
325
|
end
|
|
279
326
|
|
|
280
327
|
def deliver(message)
|
|
328
|
+
return deliver_signal(message) if message.is_a?(SignalMessage)
|
|
329
|
+
return deliver_signal_gap if message == SIGNAL_GAP
|
|
330
|
+
|
|
281
331
|
frame = { "t" => "wake", "q" => message.queue_name, "p" => message.payload }
|
|
282
332
|
droppable = message.payload.nil?
|
|
283
333
|
targets = @table_mutex.synchronize do
|
|
@@ -287,6 +337,20 @@ module Pgbus
|
|
|
287
337
|
targets.each { |id, entry| enqueue_frame(id, entry, frame, droppable: droppable) }
|
|
288
338
|
end
|
|
289
339
|
|
|
340
|
+
def deliver_signal(message)
|
|
341
|
+
frame = { "t" => "signal", "c" => message.channel, "p" => message.payload }
|
|
342
|
+
targets = @table_mutex.synchronize do
|
|
343
|
+
refs = @signal_refs[message.channel]
|
|
344
|
+
refs ? refs.filter_map { |id| [id, @workers[id]] if @workers[id] } : []
|
|
345
|
+
end
|
|
346
|
+
targets.each { |id, entry| enqueue_frame(id, entry, frame, droppable: false) }
|
|
347
|
+
end
|
|
348
|
+
|
|
349
|
+
def deliver_signal_gap
|
|
350
|
+
targets = @table_mutex.synchronize { @workers.select { |_, entry| entry[:signals].any? }.to_a }
|
|
351
|
+
targets.each { |id, entry| enqueue_frame(id, entry, { "t" => "gap" }, droppable: false) }
|
|
352
|
+
end
|
|
353
|
+
|
|
290
354
|
# Non-blocking enqueue with the drop/evict policy. Never blocks the
|
|
291
355
|
# fanout thread on one slow worker (the head-of-line lesson from
|
|
292
356
|
# issue #315 item 3, applied cross-process).
|
|
@@ -397,6 +461,7 @@ module Pgbus
|
|
|
397
461
|
end
|
|
398
462
|
close_quietly(entry[:sock])
|
|
399
463
|
release_queue_refs(id, entry[:subs].to_a)
|
|
464
|
+
release_signal_refs(id, entry[:signals].to_a)
|
|
400
465
|
end
|
|
401
466
|
|
|
402
467
|
# Decrement refcounts; UNLISTEN queues that hit zero (async — no
|
|
@@ -414,6 +479,26 @@ module Pgbus
|
|
|
414
479
|
released.each { |q| @listener.remove_listening(q) }
|
|
415
480
|
end
|
|
416
481
|
|
|
482
|
+
# The UNLISTEN is queued under @table_mutex, with the last ref's
|
|
483
|
+
# removal: a new "ssub" for the channel registers under the same
|
|
484
|
+
# mutex and queues its LISTEN after it, so an acked subscriber can
|
|
485
|
+
# never be UNLISTENed by a cleanup that lost the race (the listener
|
|
486
|
+
# runs its commands in order). remove_signal_listening only queues.
|
|
487
|
+
def release_signal_refs(id, channels)
|
|
488
|
+
@table_mutex.synchronize do
|
|
489
|
+
channels.each do |channel|
|
|
490
|
+
refs = @signal_refs[channel]
|
|
491
|
+
next unless refs
|
|
492
|
+
|
|
493
|
+
refs.delete(id)
|
|
494
|
+
next unless refs.empty?
|
|
495
|
+
|
|
496
|
+
@signal_refs.delete(channel)
|
|
497
|
+
@listener.remove_signal_listening(channel)
|
|
498
|
+
end
|
|
499
|
+
end
|
|
500
|
+
end
|
|
501
|
+
|
|
417
502
|
def close_quietly(io)
|
|
418
503
|
io.close if io && !io.closed?
|
|
419
504
|
rescue IOError, Errno::EBADF
|