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
|
@@ -28,6 +28,26 @@ module Pgbus
|
|
|
28
28
|
# sweep picks up whatever is left on its next pass.
|
|
29
29
|
PROMOTE_CAP = 100
|
|
30
30
|
|
|
31
|
+
# The metrics of a queue whose chunk could not be read (issue #677):
|
|
32
|
+
# unknown, so nil rather than zero, next to metrics_unavailable: true.
|
|
33
|
+
UNAVAILABLE_METRICS = %i[queue_length queue_visible_length parked_length oldest_msg_age_sec
|
|
34
|
+
oldest_claimable_age_sec newest_msg_age_sec total_messages max_read_ct
|
|
35
|
+
visible_unread_length oldest_unread_claimable_age_sec].to_h { |k| [k, nil] }.freeze
|
|
36
|
+
|
|
37
|
+
# Timed-out metrics chunks after which queues_with_metrics stops reading
|
|
38
|
+
# (issue #677): the rest of the queues come back unavailable, so a
|
|
39
|
+
# database where every chunk times out costs a few statement_timeouts,
|
|
40
|
+
# not one per chunk.
|
|
41
|
+
MAX_FAILED_METRICS_CHUNKS = 3
|
|
42
|
+
|
|
43
|
+
# The chunk failures that cost time (a cancelled statement, a lock wait,
|
|
44
|
+
# a deadlock, which PostgreSQL detects only after deadlock_timeout, a
|
|
45
|
+
# connection that cannot be established) and so count toward MAX_FAILED_METRICS_CHUNKS. A
|
|
46
|
+
# failure that returns at once (a queue whose table is gone) does not:
|
|
47
|
+
# it must never stop the healthy queues after it from being read.
|
|
48
|
+
SLOW_METRICS_FAILURES = [ActiveRecord::QueryCanceled, ActiveRecord::LockWaitTimeout, ActiveRecord::Deadlocked,
|
|
49
|
+
ActiveRecord::ConnectionNotEstablished].freeze
|
|
50
|
+
|
|
31
51
|
def initialize(client: Pgbus.client)
|
|
32
52
|
@client = client
|
|
33
53
|
@last_throughput_snapshot = nil
|
|
@@ -37,10 +57,12 @@ module Pgbus
|
|
|
37
57
|
# Dashboard summary
|
|
38
58
|
def summary_stats
|
|
39
59
|
queues = queues_with_metrics
|
|
40
|
-
|
|
41
|
-
|
|
60
|
+
# A queue with metrics_unavailable (issue #677) has nil counts: it adds
|
|
61
|
+
# nothing it cannot vouch for.
|
|
62
|
+
total_depth = queues.sum { |q| q[:queue_length].to_i }
|
|
63
|
+
total_visible = queues.sum { |q| q[:queue_visible_length].to_i }
|
|
42
64
|
dlq_suffix = Pgbus::DEAD_LETTER_SUFFIX
|
|
43
|
-
dlq_depth = queues.select { |q| q[:name].end_with?(dlq_suffix) }.sum { |q| q[:queue_length] }
|
|
65
|
+
dlq_depth = queues.select { |q| q[:name].end_with?(dlq_suffix) }.sum { |q| q[:queue_length].to_i }
|
|
44
66
|
|
|
45
67
|
throughput = compute_throughput(queues)
|
|
46
68
|
|
|
@@ -67,7 +89,9 @@ module Pgbus
|
|
|
67
89
|
# responses would freeze at the first read. Both call this per iteration
|
|
68
90
|
# / per tool call.
|
|
69
91
|
def reset_cache!
|
|
92
|
+
@queue_names = nil
|
|
70
93
|
@queues_with_metrics = nil
|
|
94
|
+
@queue_metrics_errors = nil
|
|
71
95
|
@concurrency_summary = nil
|
|
72
96
|
@queue_health_stats = nil
|
|
73
97
|
@process_rows = nil
|
|
@@ -75,6 +99,19 @@ module Pgbus
|
|
|
75
99
|
self
|
|
76
100
|
end
|
|
77
101
|
|
|
102
|
+
# Every queue's physical name, from pgmq.meta alone: no queue table is
|
|
103
|
+
# read (issue #677). Callers that need only names (the job list scope,
|
|
104
|
+
# the DLQ selection, priority siblings) use this instead of paying for
|
|
105
|
+
# queues_with_metrics. Memoized like it, cleared by reset_cache!, and
|
|
106
|
+
# shared with it, so a page that wants both reads pgmq.meta once. A
|
|
107
|
+
# failed read is logged and answers [] without memoizing.
|
|
108
|
+
def queue_names
|
|
109
|
+
@queue_names ||= read_queue_names
|
|
110
|
+
rescue StandardError => e
|
|
111
|
+
Pgbus.logger.error { "[Pgbus::Web] Error reading queue names: #{e.class}: #{e.message}" }
|
|
112
|
+
[]
|
|
113
|
+
end
|
|
114
|
+
|
|
78
115
|
# Queues — query via ActiveRecord for reliability in web processes
|
|
79
116
|
# (avoids PGMQ client connection issues when the web server uses a
|
|
80
117
|
# different connection lifecycle than the worker processes).
|
|
@@ -84,24 +121,57 @@ module Pgbus
|
|
|
84
121
|
# message rows and the total count); without the memo each call re-runs
|
|
85
122
|
# the meta query + batched metrics. Mutations redirect to a fresh request
|
|
86
123
|
# with a new instance, so a per-request memo never serves stale data.
|
|
124
|
+
#
|
|
125
|
+
# A queue whose metrics could not be read (its chunk failed or hit
|
|
126
|
+
# statement_timeout, issue #677) stays in the list with
|
|
127
|
+
# metrics_unavailable: true and nil counts; queue_metrics_errors says why.
|
|
87
128
|
def queues_with_metrics
|
|
88
129
|
@queues_with_metrics ||= fetch_queues_with_metrics
|
|
89
130
|
end
|
|
90
131
|
|
|
132
|
+
# Why the last queues_with_metrics read is incomplete: [] when every
|
|
133
|
+
# queue reported, else one { queues: [names], error: "Class: message" }
|
|
134
|
+
# per failed statement (queues: [] when pgmq.meta itself could not be
|
|
135
|
+
# read). Runs that read when none has run yet. An empty
|
|
136
|
+
# queues_with_metrics with no errors is an empty system; with errors it
|
|
137
|
+
# is an unknown one.
|
|
138
|
+
def queue_metrics_errors
|
|
139
|
+
queues_with_metrics
|
|
140
|
+
@queue_metrics_errors || []
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# queues: [] in queue_metrics_errors means pgmq.meta itself could not be
|
|
144
|
+
# read; a failure after it answered keeps the names, flagged.
|
|
91
145
|
def fetch_queues_with_metrics
|
|
92
|
-
|
|
93
|
-
|
|
146
|
+
@queue_metrics_errors = []
|
|
147
|
+
names = @queue_names ||= read_queue_names
|
|
148
|
+
return [] if names.empty?
|
|
94
149
|
|
|
95
150
|
paused_queues = paused_queue_names.to_set
|
|
96
|
-
batched_queue_metrics(
|
|
151
|
+
batched_queue_metrics(names).map do |q|
|
|
97
152
|
q.merge(paused: paused_queues.include?(logical_queue_name(q[:name])))
|
|
98
153
|
end
|
|
99
154
|
rescue StandardError => e
|
|
100
155
|
Pgbus.logger.error { "[Pgbus::Web] Error fetching queue metrics: #{e.class}: #{e.message}" }
|
|
156
|
+
return unavailable_queue_metrics(names, "#{e.class}: #{e.message}") if names
|
|
157
|
+
|
|
158
|
+
@queue_metrics_errors << { queues: [], error: "#{e.class}: #{e.message}" }
|
|
101
159
|
[]
|
|
102
160
|
end
|
|
103
161
|
private :fetch_queues_with_metrics
|
|
104
162
|
|
|
163
|
+
# A name sanitize_name rejects never reaches a caller: before #677 the
|
|
164
|
+
# metrics read dropped it, and every caller took its names from there.
|
|
165
|
+
def read_queue_names
|
|
166
|
+
connection.select_values("SELECT queue_name FROM pgmq.meta ORDER BY queue_name").select do |name|
|
|
167
|
+
sanitize_name(name)
|
|
168
|
+
rescue ArgumentError => e
|
|
169
|
+
Pgbus.logger.debug { "[Pgbus::Web] Skipping queue #{name.inspect}: #{e.message}" }
|
|
170
|
+
false
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
private :read_queue_names
|
|
174
|
+
|
|
105
175
|
# Physical queue names known to back streams: the pgbus_stream_queues
|
|
106
176
|
# registry plus any dormant pre-registry queues discovered by the
|
|
107
177
|
# archive msg_id index fingerprint (issue #366). Stream delivery is a
|
|
@@ -248,20 +318,20 @@ module Pgbus
|
|
|
248
318
|
def discard_all_enqueued
|
|
249
319
|
dlq_suffix = Pgbus::DEAD_LETTER_SUFFIX
|
|
250
320
|
handlers = handler_queue_physical_names
|
|
251
|
-
|
|
321
|
+
names = queue_names.reject { |n| n.end_with?(dlq_suffix) || handlers.include?(n) }
|
|
252
322
|
total = 0
|
|
253
323
|
|
|
254
|
-
|
|
255
|
-
messages = query_queue_messages_raw(
|
|
324
|
+
names.each do |name|
|
|
325
|
+
messages = query_queue_messages_raw(name, 10_000, 0)
|
|
256
326
|
next if messages.empty?
|
|
257
327
|
|
|
258
328
|
release_locks_for_messages(messages)
|
|
259
329
|
|
|
260
330
|
ids = messages.map { |m| m[:msg_id].to_i }
|
|
261
|
-
@client.archive_batch(
|
|
331
|
+
@client.archive_batch(name, ids, prefixed: false)
|
|
262
332
|
total += ids.size
|
|
263
333
|
rescue StandardError => e
|
|
264
|
-
Pgbus.logger.debug { "[Pgbus::Web] Error discarding enqueued messages from #{
|
|
334
|
+
Pgbus.logger.debug { "[Pgbus::Web] Error discarding enqueued messages from #{name}: #{e.message}" }
|
|
265
335
|
end
|
|
266
336
|
|
|
267
337
|
total
|
|
@@ -1280,8 +1350,7 @@ module Pgbus
|
|
|
1280
1350
|
|
|
1281
1351
|
def all_queue_messages(limit, offset)
|
|
1282
1352
|
dlq_suffix = Pgbus::DEAD_LETTER_SUFFIX
|
|
1283
|
-
|
|
1284
|
-
paginated_queue_messages(queues.map { |q| q[:name] }, limit, offset)
|
|
1353
|
+
paginated_queue_messages(queue_names.reject { |n| n.end_with?(dlq_suffix) }, limit, offset)
|
|
1285
1354
|
end
|
|
1286
1355
|
|
|
1287
1356
|
# Returns messages from multiple PGMQ queues in a single paginated
|
|
@@ -1324,53 +1393,98 @@ module Pgbus
|
|
|
1324
1393
|
end.join("\nUNION ALL\n")
|
|
1325
1394
|
end
|
|
1326
1395
|
|
|
1396
|
+
# Every queue's metrics, web_queue_metrics_chunk_size queues per
|
|
1397
|
+
# statement (issue #677). Each queue's table is scanned once, by one
|
|
1398
|
+
# aggregate, so a statement's cost grows with its chunk, not with the
|
|
1399
|
+
# whole fleet. Each chunk runs in its own savepoint: a chunk that fails
|
|
1400
|
+
# (statement_timeout included) rolls back to it, so a caller's open
|
|
1401
|
+
# transaction stays usable, and only that chunk's queues come back as
|
|
1402
|
+
# unavailable. Rows follow +queue_names+ order.
|
|
1403
|
+
#
|
|
1404
|
+
# Chunks run one after another, so a database where every chunk times
|
|
1405
|
+
# out would cost chunks × statement_timeout. After
|
|
1406
|
+
# MAX_FAILED_METRICS_CHUNKS failed chunks the rest are not run: their
|
|
1407
|
+
# queues come back unavailable at once.
|
|
1327
1408
|
def batched_queue_metrics(queue_names)
|
|
1328
|
-
|
|
1409
|
+
chunk_size = Pgbus.configuration.web_queue_metrics_chunk_size
|
|
1410
|
+
rows = []
|
|
1411
|
+
failed = 0
|
|
1412
|
+
queue_names.each_slice(chunk_size).with_index do |chunk, index|
|
|
1413
|
+
if failed >= MAX_FAILED_METRICS_CHUNKS
|
|
1414
|
+
skipped = queue_names.drop(index * chunk_size)
|
|
1415
|
+
rows.concat(unavailable_queue_metrics(skipped, "not read: #{failed} metrics chunks timed out before them"))
|
|
1416
|
+
break
|
|
1417
|
+
end
|
|
1329
1418
|
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
(SELECT count(*) FROM pgmq.#{qtable} WHERE vt <= NOW() AND read_ct = 0) AS visible_unread_length,
|
|
1344
|
-
(SELECT EXTRACT(epoch FROM (NOW() - min(vt)))::int FROM pgmq.#{qtable} WHERE vt <= NOW()) AS oldest_claimable_age_sec,
|
|
1345
|
-
(SELECT EXTRACT(epoch FROM (NOW() - min(vt)))::int FROM pgmq.#{qtable} WHERE vt <= NOW() AND read_ct = 0) AS oldest_unread_claimable_age_sec
|
|
1346
|
-
SQL
|
|
1347
|
-
rescue StandardError => e
|
|
1348
|
-
Pgbus.logger.debug { "[Pgbus::Web] Skipping queue metrics for #{name}: #{e.message}" }
|
|
1349
|
-
nil
|
|
1419
|
+
chunk_rows, error = chunk_queue_metrics(chunk)
|
|
1420
|
+
failed += 1 if SLOW_METRICS_FAILURES.any? { |klass| error.is_a?(klass) }
|
|
1421
|
+
rows.concat(chunk_rows)
|
|
1422
|
+
end
|
|
1423
|
+
rows
|
|
1424
|
+
end
|
|
1425
|
+
|
|
1426
|
+
# [rows, nil], or [unavailable rows, the error] for a failed chunk.
|
|
1427
|
+
# +chunk+ holds names read_queue_names already validated.
|
|
1428
|
+
def chunk_queue_metrics(chunk)
|
|
1429
|
+
sql = chunk.map { |name| "(#{queue_metrics_select(name)})" }.join("\nUNION ALL\n")
|
|
1430
|
+
rows = connection.transaction(requires_new: true) do
|
|
1431
|
+
connection.select_all(sql, "Pgbus Batched Queue Metrics").to_a
|
|
1350
1432
|
end
|
|
1433
|
+
by_name = rows.to_h { |row| [row["queue_name"], row] }
|
|
1434
|
+
[chunk.filter_map { |name| by_name[name] && queue_metrics_hash(name, by_name[name]) }, nil]
|
|
1435
|
+
rescue StandardError => e
|
|
1436
|
+
[unavailable_queue_metrics(chunk, "#{e.class}: #{e.message}"), e]
|
|
1437
|
+
end
|
|
1438
|
+
|
|
1439
|
+
# One row for one queue: a single aggregate over its table, plus the
|
|
1440
|
+
# msg_id sequence for the lifetime total. The same expressions as
|
|
1441
|
+
# queue_metrics_via_sql, so a queue reads the same on both paths.
|
|
1442
|
+
def queue_metrics_select(name)
|
|
1443
|
+
qtable = "q_#{sanitize_name(name)}"
|
|
1444
|
+
<<~SQL.strip
|
|
1445
|
+
SELECT #{connection.quote(name)} AS queue_name,
|
|
1446
|
+
m.queue_length, m.queue_visible_length, m.newest_msg_age_sec, m.oldest_msg_age_sec,
|
|
1447
|
+
(SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM pgmq.#{qtable}_msg_id_seq) AS total_messages,
|
|
1448
|
+
m.max_read_ct, m.visible_unread_length, m.oldest_claimable_age_sec, m.oldest_unread_claimable_age_sec
|
|
1449
|
+
FROM (
|
|
1450
|
+
SELECT count(*) AS queue_length,
|
|
1451
|
+
count(*) FILTER (WHERE vt <= NOW()) AS queue_visible_length,
|
|
1452
|
+
EXTRACT(epoch FROM (NOW() - max(enqueued_at)))::int AS newest_msg_age_sec,
|
|
1453
|
+
EXTRACT(epoch FROM (NOW() - min(enqueued_at)))::int AS oldest_msg_age_sec,
|
|
1454
|
+
max(read_ct) AS max_read_ct,
|
|
1455
|
+
count(*) FILTER (WHERE vt <= NOW() AND read_ct = 0) AS visible_unread_length,
|
|
1456
|
+
EXTRACT(epoch FROM (NOW() - min(vt) FILTER (WHERE vt <= NOW())))::int AS oldest_claimable_age_sec,
|
|
1457
|
+
EXTRACT(epoch FROM (NOW() - min(vt) FILTER (WHERE vt <= NOW() AND read_ct = 0)))::int AS oldest_unread_claimable_age_sec
|
|
1458
|
+
FROM pgmq.#{qtable}
|
|
1459
|
+
) AS m
|
|
1460
|
+
SQL
|
|
1461
|
+
end
|
|
1351
1462
|
|
|
1352
|
-
|
|
1463
|
+
def queue_metrics_hash(name, row)
|
|
1464
|
+
{
|
|
1465
|
+
name: name,
|
|
1466
|
+
queue_length: row["queue_length"].to_i,
|
|
1467
|
+
queue_visible_length: row["queue_visible_length"].to_i,
|
|
1468
|
+
parked_length: row["queue_length"].to_i - row["queue_visible_length"].to_i,
|
|
1469
|
+
oldest_msg_age_sec: row["oldest_msg_age_sec"]&.to_i,
|
|
1470
|
+
oldest_claimable_age_sec: row["oldest_claimable_age_sec"]&.to_i,
|
|
1471
|
+
newest_msg_age_sec: row["newest_msg_age_sec"]&.to_i,
|
|
1472
|
+
total_messages: row["total_messages"].to_i,
|
|
1473
|
+
max_read_ct: row["max_read_ct"]&.to_i,
|
|
1474
|
+
visible_unread_length: row["visible_unread_length"].to_i,
|
|
1475
|
+
oldest_unread_claimable_age_sec: row["oldest_unread_claimable_age_sec"]&.to_i
|
|
1476
|
+
}
|
|
1477
|
+
end
|
|
1353
1478
|
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
queue_visible_length: row["queue_visible_length"].to_i,
|
|
1361
|
-
parked_length: row["queue_length"].to_i - row["queue_visible_length"].to_i,
|
|
1362
|
-
oldest_msg_age_sec: row["oldest_msg_age_sec"]&.to_i,
|
|
1363
|
-
oldest_claimable_age_sec: row["oldest_claimable_age_sec"]&.to_i,
|
|
1364
|
-
newest_msg_age_sec: row["newest_msg_age_sec"]&.to_i,
|
|
1365
|
-
total_messages: row["total_messages"].to_i,
|
|
1366
|
-
max_read_ct: row["max_read_ct"]&.to_i,
|
|
1367
|
-
visible_unread_length: row["visible_unread_length"].to_i,
|
|
1368
|
-
oldest_unread_claimable_age_sec: row["oldest_unread_claimable_age_sec"]&.to_i
|
|
1369
|
-
}
|
|
1479
|
+
# A failed chunk keeps its queues, flagged, with every metric nil: a
|
|
1480
|
+
# count we could not read is unknown, not zero.
|
|
1481
|
+
def unavailable_queue_metrics(names, error)
|
|
1482
|
+
Pgbus.logger.error do
|
|
1483
|
+
"[Pgbus::Web] Queue metrics unavailable for #{names.size} queue(s) (#{names.first(3).join(", ")}" \
|
|
1484
|
+
"#{", …" if names.size > 3}): #{error}"
|
|
1370
1485
|
end
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
[]
|
|
1486
|
+
(@queue_metrics_errors ||= []) << { queues: names, error: error }
|
|
1487
|
+
names.map { |name| { name: name, **UNAVAILABLE_METRICS, metrics_unavailable: true } }
|
|
1374
1488
|
end
|
|
1375
1489
|
|
|
1376
1490
|
def queue_metrics_via_sql(queue_name)
|
|
@@ -1509,14 +1623,20 @@ module Pgbus
|
|
|
1509
1623
|
QueueNameValidator.sanitize!(name)
|
|
1510
1624
|
end
|
|
1511
1625
|
|
|
1626
|
+
# A read with a queue's metrics unavailable (issue #677) leaves the
|
|
1627
|
+
# snapshot alone: its lifetime total is unknown, and counting it as zero
|
|
1628
|
+
# would read as a drop now and a spike once it reports again.
|
|
1512
1629
|
def compute_throughput(queues)
|
|
1630
|
+
return 0.0 if queues.any? { |q| q[:metrics_unavailable] }
|
|
1631
|
+
|
|
1513
1632
|
current_totals = queues.sum { |q| q[:total_messages] }
|
|
1514
|
-
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
1633
|
+
now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
|
|
1515
1634
|
|
|
1516
1635
|
if @last_throughput_snapshot && @last_throughput_at
|
|
1517
1636
|
elapsed = now - @last_throughput_at
|
|
1518
1637
|
delta = current_totals - @last_throughput_snapshot
|
|
1519
|
-
|
|
1638
|
+
# A dropped queue lowers the lifetime total: never a negative rate.
|
|
1639
|
+
rate = elapsed.positive? ? [(delta / elapsed).round(1), 0.0].max : 0.0
|
|
1520
1640
|
end
|
|
1521
1641
|
|
|
1522
1642
|
@last_throughput_snapshot = current_totals
|
|
@@ -36,8 +36,13 @@ module Pgbus
|
|
|
36
36
|
private
|
|
37
37
|
|
|
38
38
|
def append_queue_metrics(lines)
|
|
39
|
-
|
|
40
|
-
return if
|
|
39
|
+
all = @data_source.queues_with_metrics
|
|
40
|
+
return append_queue_list_unavailable(lines) if all.empty?
|
|
41
|
+
|
|
42
|
+
# A queue whose metrics could not be read (issue #677) has nil counts:
|
|
43
|
+
# it gets no count sample (format_value would write a false 0), only
|
|
44
|
+
# its paused state and pgbus_queue_metrics_unavailable.
|
|
45
|
+
queues = all.reject { |q| q[:metrics_unavailable] }
|
|
41
46
|
|
|
42
47
|
gauge(lines, "pgbus_queue_depth", "Number of messages in the queue (including invisible)") do
|
|
43
48
|
queues.map { |q| [q[:queue_length], { queue: q[:name] }] }
|
|
@@ -69,12 +74,32 @@ module Pgbus
|
|
|
69
74
|
end
|
|
70
75
|
|
|
71
76
|
gauge(lines, "pgbus_queue_paused", "Whether the queue is paused (1) or active (0)") do
|
|
72
|
-
|
|
77
|
+
all.map { |q| [q[:paused] ? 1 : 0, { queue: q[:name] }] }
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
gauge(lines, "pgbus_queue_metrics_unavailable",
|
|
81
|
+
"Whether the queue's metrics could not be read this scrape (1) or were read (0)") do
|
|
82
|
+
all.map { |q| [q[:metrics_unavailable] ? 1 : 0, { queue: q[:name] }] }
|
|
73
83
|
end
|
|
74
84
|
rescue StandardError => e
|
|
75
85
|
Pgbus.logger.debug { "[Pgbus::Metrics] Error serializing queue metrics: #{e.message}" }
|
|
76
86
|
end
|
|
77
87
|
|
|
88
|
+
# No queue rows because pgmq.meta could not be read (issue #677): one
|
|
89
|
+
# unlabelled sample, so the scrape says so instead of going quiet.
|
|
90
|
+
def append_queue_list_unavailable(lines)
|
|
91
|
+
return unless queue_list_unavailable?
|
|
92
|
+
|
|
93
|
+
gauge(lines, "pgbus_queue_metrics_unavailable",
|
|
94
|
+
"Whether the queue's metrics could not be read this scrape (1) or were read (0)") { [[1]] }
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def queue_list_unavailable?
|
|
98
|
+
return false unless @data_source.respond_to?(:queue_metrics_errors)
|
|
99
|
+
|
|
100
|
+
@data_source.queue_metrics_errors.any? { |e| Array(e[:queues]).empty? }
|
|
101
|
+
end
|
|
102
|
+
|
|
78
103
|
def append_job_metrics(lines)
|
|
79
104
|
counts = @data_source.job_status_counts
|
|
80
105
|
unless counts.empty?
|
|
@@ -168,8 +193,12 @@ module Pgbus
|
|
|
168
193
|
[[stats[:failed_count]]]
|
|
169
194
|
end
|
|
170
195
|
|
|
171
|
-
|
|
172
|
-
|
|
196
|
+
# An unreadable queue list (issue #677) makes the DLQ total unknown,
|
|
197
|
+
# not 0: no sample, so a dlq_depth alert does not clear on it.
|
|
198
|
+
unless queue_list_unavailable?
|
|
199
|
+
gauge(lines, "pgbus_dlq_depth", "Total messages across all dead letter queues") do
|
|
200
|
+
[[stats[:dlq_depth]]]
|
|
201
|
+
end
|
|
173
202
|
end
|
|
174
203
|
rescue StandardError => e
|
|
175
204
|
Pgbus.logger.debug { "[Pgbus::Metrics] Error serializing summary metrics: #{e.message}" }
|
|
@@ -19,13 +19,18 @@ module Pgbus
|
|
|
19
19
|
|
|
20
20
|
module_function
|
|
21
21
|
|
|
22
|
+
# A queue whose metrics could not be read (issue #677) says so right
|
|
23
|
+
# after any pause, ahead of the drain line: "no worker — N claimable"
|
|
24
|
+
# would quote an unknown count as 0.
|
|
22
25
|
def present(detail, pause_state, drainers, max_retries:)
|
|
23
26
|
name = detail[:name].to_s
|
|
24
27
|
dlq = name.end_with?(Pgbus::DEAD_LETTER_SUFFIX)
|
|
28
|
+
unavailable = line("metrics_unavailable", :yellow) if detail[:metrics_unavailable]
|
|
25
29
|
[
|
|
26
30
|
pause_line(pause_state),
|
|
31
|
+
unavailable,
|
|
27
32
|
drain_line(dlq, detail, drainers, max_retries),
|
|
28
|
-
(backlog_line(detail) unless dlq || drainers[:stream]),
|
|
33
|
+
(backlog_line(detail) unless unavailable || dlq || drainers[:stream]),
|
|
29
34
|
priority_line(drainers)
|
|
30
35
|
].compact
|
|
31
36
|
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
|
-
|
|
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
|
-
|
|
115
|
+
signals = nil
|
|
83
116
|
@failover_mutex.synchronize do
|
|
84
117
|
return if @state_mutex.synchronize { @failed_over }
|
|
85
118
|
|
|
86
|
-
|
|
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
|
|
108
|
-
# on the dead client — every
|
|
109
|
-
#
|
|
110
|
-
#
|
|
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
|
|
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
|
-
|
|
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
|