pgbus 0.16.6 → 0.16.7
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 +4 -0
- data/README.md +8 -0
- data/lib/pgbus/event_bus/claim_beat.rb +80 -0
- data/lib/pgbus/event_bus/handler.rb +123 -34
- data/lib/pgbus/event_bus/publisher.rb +1 -1
- data/lib/pgbus/event_bus/registry.rb +24 -1
- data/lib/pgbus/instrumentation.rb +4 -0
- data/lib/pgbus/metrics/subscriber.rb +14 -0
- data/lib/pgbus/process/consumer.rb +71 -4
- data/lib/pgbus/testing.rb +1 -1
- data/lib/pgbus/version.rb +1 -1
- data/lib/pgbus/visibility_heartbeat.rb +23 -4
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 82a6db71dd099a9b4fa24cb0a278184a3aed8bbee7acfb3f3cc6ef6b55064038
|
|
4
|
+
data.tar.gz: ad7034ee934aee91afdb4a6278200f8178caf0da609d49e57bc6bbcf27d3b7b5
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 86977d3f705b8e3732211956582334f6e49a60e426af1082fdf585a175c9a189c9dc9ec83d5ceeaac2f0be7dcee40c1414e55a99225fcc90ac955537d8b4f01c
|
|
7
|
+
data.tar.gz: 3af2ae55db88774c89f3082b70e5456201c9a85ffd994d43beb197fe0f52d282209fc5de57db66c44de10afe34b37d37fa5404522eabb97d4eb2e91cbfc80da7
|
data/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
|
|
11
11
|
### Fixed
|
|
12
12
|
|
|
13
|
+
- **A still-running event handler is no longer re-run as if it had crashed, and a slow one is no longer redelivered mid-run.** Two halves of one hole, follow-up to #469. First: `Process::Consumer` had no equivalent of `ActiveJob::Executor#with_visibility_heartbeat`, so an event message's visibility timeout was never re-armed — a handler slower than `visibility_timeout` (30s by default) was redelivered *while it was still running*, `read_ct` climbed on every redelivery, and after `max_retries` the event was dead-lettered without the handler ever raising. Workers have been protected from this since the heartbeat landed; event consumers never were. The consumer now tracks each message through `VisibilityHeartbeat` for exactly as long as its handlers run, releasing the entry before the archive so a beat can never re-arm a message that is already gone. Second: `Handler#claim_idempotency?` read a `pgbus_processed_events` row with `completed_at IS NULL` as proof that the previous holder had been killed mid-handler, and re-ran. That state equally describes a handler that is simply still running — on another thread, another fork or another host — so a second delivery (a genuine redelivery, or a duplicate envelope, whose independent visibility timeouts no heartbeat can serialize) executed the handler *concurrently with* the live one, which is precisely the double-execution `idempotent!` exists to prevent. The claim now carries liveness rather than only a claim instant: `EventBus::ClaimBeat` refreshes every in-flight claim's `processed_at` from the same beat that re-arms the message's visibility timeout, so message visibility and claim liveness go quiet together when a process dies. A pending claim silent for longer than twice the heartbeat interval is abandoned and re-runs, exactly as before; a fresher one is owned and the delivery skips, deferring to the holder — which either completes (nothing is lost) or fails, leaving its own message for visibility-timeout redelivery to recover. A skip is also no longer silent: `pgbus.event_skipped` carries the reason (`:completed`, `:cached` or `:owned`), the claim's age in seconds and the delivery's `read_ct`, and the metrics subscriber counts it as `pgbus_event_count` with `status: "skipped"` and the reason as a tag. No migration, no new column, and no change on a table that has not run `pgbus:add_processed_event_completion` — a single-phase claim has no pending state and therefore no ownership question. Closes #470.
|
|
14
|
+
|
|
15
|
+
- **An event is no longer handed to every handler whose pattern matches it, so a wildcard handler ran once per subscriber on the topic.** Each subscriber gets its own queue (`Subscriber#setup!` creates and binds one), so a topic with N matching subscribers puts N copies of every event on the bus — but `Consumer#handle_message` resolved handlers with `Registry#handlers_for(routing_key)`, a pattern match that ignored which queue the message had just been read from, and ran every match. Each of the N copies therefore fanned out to all N handlers: **every handler ran N times per event**, with four `"#"` subscribers meaning four invocations of each handler for every event on the bus. `idempotent!` was the only thing hiding it, and it hides it imperfectly by design: the two-phase claim (#385) deliberately *re-runs* when the existing claim is still pending, on the theory that the prior holder crashed — but a pending claim is also exactly what a handler still running on another host looks like. So one event could have host A win the claim and start a 700ms handler while host B, reading a different subscriber's copy of the same event a few hundred milliseconds later, dispatched to that same handler, lost the claim insert, read `completed_at IS NULL` as "crashed, re-run", and executed it concurrently. In one host app that meant a "task completed" record written twice and the user emailed twice, with a single row in `pgbus_processed_events`, `read_ct = 1` on every archived copy, and the second execution's side effects timestamped inside the first's window — dispatch, not redelivery. A non-idempotent handler simply ran N times with no guard at all. `handlers_for` now takes a required `queue_name:` and selects on ownership *and* pattern, so a message read from queue Q goes to Q's owner(s) alone and each handler runs exactly once per event; duplicate execution again requires a real redelivery, which is the at-least-once contract the docs describe. The keyword is required rather than defaulted precisely so a keyword-less call cannot silently restore the fan-out — the two callers that genuinely want the pattern view (the `Testing.inline!` publish path and `Testing::EventStore#drain!`, neither of which has a queue, since the event never reaches PGMQ) moved to an explicitly named `Registry#subscribers_matching`, where per-subscriber delivery counts already match what owner-only dispatch now produces in production. Two handlers registered against the same explicit `queue_name:` still both run on that queue's delivery. The pattern check is kept alongside the ownership check because a routing key the owner's pattern does not match means a stale `pgmq.topic_bindings` row, and a stale binding must not run the handler. A message on a queue no subscriber in this process owns is still archived rather than looped through visibility-timeout redelivery into the DLQ — that was already the behavior when `handlers_for` returned `[]` — but it is no longer silent: it logs a warning naming the queue and routing key, rate-limited to once per queue per process so a permanently stale binding cannot flood the log, and emits `pgbus.event_unrouted` on every occurrence so the real rate stays visible in metrics. The pending-claim re-run in `Handler#claim_idempotency?` is deliberately untouched here; it is a separate question now that dispatch no longer manufactures the concurrency it was misreading. Closes #469.
|
|
16
|
+
|
|
13
17
|
- **A dropped ActiveRecord socket no longer pages the host app for an event that was handled successfully.** EventBus consumers are long-lived threads holding a leased AR connection, and a pooler restart, an admin disconnect or a brief failover can kill that socket at any point. Rails reconnects most statements transparently, but `Relation#update_all` is marked `allow_retry: false` — and that is exactly the phase-2 claim stamp in `Handler#complete_claim!`, the one AR write that happens *after* `handle` has already returned. A drop there surfaced as `ActiveRecord::ConnectionFailed` ("PQconsumeInput() SSL error: unexpected eof while reading") on a message whose work was done, so the host app's exception tracker paged for a false failure and PGMQ redelivered the event for a re-run. `EventBus::StaleConnectionRetry` now reconnects this thread's lease (via `ConnectionPool#active_connection?`, the accessor that exists across the supported Rails range) and repeats the stamp once; a second drop still raises, leaving the message to VT redelivery. Only the leased connections are reconnected — `clear_all_connections!` would yank sockets out from under sibling consumers in the same process, turning one recoverable drop into many. The retryable patterns are deliberately *broader* than `Client::STALE_CONNECTION_PATTERNS` and for the opposite reason: that list excludes mid-flight drops because a half-committed enqueue would duplicate a message, whereas this only ever repeats an idempotent `SET completed_at = <now>`. Phase 1 (`claim_idempotency?`) is deliberately not wrapped — its INSERT may have committed before the socket died, and on a legacy schema the retry's empty `result.rows` would read as "another consumer owns this claim", turning a recoverable drop into a silently skipped event.
|
|
14
18
|
|
|
15
19
|
|
data/README.md
CHANGED
|
@@ -221,6 +221,14 @@ Pgbus::EventBus::Registry.instance.subscribe(
|
|
|
221
221
|
)
|
|
222
222
|
```
|
|
223
223
|
|
|
224
|
+
Each subscriber gets its own queue, and a queue is consumed only by the
|
|
225
|
+
handler(s) registered against it: one published event matching N subscribers
|
|
226
|
+
becomes N deliveries, one per handler, so every handler runs exactly once per
|
|
227
|
+
event. (Two handlers sharing an explicit `queue_name:` both run on that queue's
|
|
228
|
+
delivery.) A message on a queue no subscriber in this process owns — a stale
|
|
229
|
+
topic binding left by a renamed or removed handler — is archived, logged once
|
|
230
|
+
per queue, and reported as `pgbus.event_unrouted`.
|
|
231
|
+
|
|
224
232
|
`idempotent!` uses a **two-phase claim**: a *pending* row in
|
|
225
233
|
`pgbus_processed_events` is inserted before `handle` runs, and only stamped
|
|
226
234
|
`completed_at` after `handle` returns. Deduplication applies to **completed**
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
module EventBus
|
|
5
|
+
# Liveness for the idempotency claims in flight for one PGMQ message.
|
|
6
|
+
#
|
|
7
|
+
# A two-phase claim (issue #385) is a `pgbus_processed_events` row with
|
|
8
|
+
# `completed_at IS NULL`. That state says "claimed, not finished" — it does
|
|
9
|
+
# NOT say whether the claimer is dead or simply still running (issue #470).
|
|
10
|
+
# Handler resolves the ambiguity by age: a claim whose `processed_at` has
|
|
11
|
+
# gone quiet for longer than the ownership window is abandoned, anything
|
|
12
|
+
# fresher is owned. For that age to mean "silence" rather than
|
|
13
|
+
# "time since the claim was taken", something has to keep stamping it while
|
|
14
|
+
# the handler runs. This is that something.
|
|
15
|
+
#
|
|
16
|
+
# One beat per message, created by Process::Consumer and handed to every
|
|
17
|
+
# handler dispatched for it. A handler registers its claim for exactly the
|
|
18
|
+
# duration of `handle` and the consumer's VisibilityHeartbeat `on_beat` hook
|
|
19
|
+
# drives #touch! on the same cadence that re-arms the message's visibility
|
|
20
|
+
# timeout — so the claim and the message go quiet together when the process
|
|
21
|
+
# dies, and both stay fresh while it lives.
|
|
22
|
+
#
|
|
23
|
+
# #touch! runs on the heartbeat ticker thread while #register / #release run
|
|
24
|
+
# on a pool thread, hence the mutex.
|
|
25
|
+
class ClaimBeat
|
|
26
|
+
def initialize
|
|
27
|
+
@mutex = Mutex.new
|
|
28
|
+
@claims = []
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def register(event_id, handler_class)
|
|
32
|
+
claim = [event_id, handler_class]
|
|
33
|
+
@mutex.synchronize { @claims << claim unless @claims.include?(claim) }
|
|
34
|
+
self
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def release(event_id, handler_class)
|
|
38
|
+
@mutex.synchronize { @claims.delete([event_id, handler_class]) }
|
|
39
|
+
self
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def size
|
|
43
|
+
@mutex.synchronize { @claims.size }
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def empty?
|
|
47
|
+
size.zero?
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Refresh every registered claim's liveness stamp. Returns the number of
|
|
51
|
+
# claims touched. No-op on a legacy schema: without `completed_at` there
|
|
52
|
+
# are no pending claims to keep alive, and Handler's single-phase
|
|
53
|
+
# fallback never consults the age.
|
|
54
|
+
#
|
|
55
|
+
# A claim that fails to update is logged and skipped rather than raised:
|
|
56
|
+
# this runs inside the visibility heartbeat's beat, and one unwritable
|
|
57
|
+
# row must not cost every other in-flight message its VT extension.
|
|
58
|
+
def touch!
|
|
59
|
+
return 0 unless ProcessedEvent.completion_column?
|
|
60
|
+
|
|
61
|
+
now = Time.now.utc
|
|
62
|
+
@mutex.synchronize { @claims.dup }.count { |event_id, handler_class| touch(event_id, handler_class, now) }
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
private
|
|
66
|
+
|
|
67
|
+
def touch(event_id, handler_class, now)
|
|
68
|
+
ProcessedEvent
|
|
69
|
+
.where(event_id: event_id, handler_class: handler_class, completed_at: nil)
|
|
70
|
+
.update_all(processed_at: now)
|
|
71
|
+
true
|
|
72
|
+
rescue StandardError => e
|
|
73
|
+
Pgbus.logger.warn do
|
|
74
|
+
"[Pgbus] Could not refresh idempotency claim #{handler_class}/#{event_id}: #{e.class}: #{e.message}"
|
|
75
|
+
end
|
|
76
|
+
false
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
@@ -17,8 +17,20 @@ module Pgbus
|
|
|
17
17
|
end
|
|
18
18
|
end
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
# Outcome of the two-phase claim. `age` is how long the losing delivery
|
|
21
|
+
# found the existing claim to have been silent, in seconds (nil unless
|
|
22
|
+
# the claim was pending).
|
|
23
|
+
ClaimResult = Data.define(:status, :age) do
|
|
24
|
+
def granted?
|
|
25
|
+
status == :claimed
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# @param claim_beat [ClaimBeat, nil] the message's claim-liveness beat,
|
|
30
|
+
# supplied by Process::Consumer. Absent for a hand-rolled caller: the
|
|
31
|
+
# handler still runs, its claim simply ages from the claim instant.
|
|
32
|
+
def process(message, claim_beat: nil)
|
|
33
|
+
with_rails_executor { process!(message, claim_beat) }
|
|
22
34
|
end
|
|
23
35
|
|
|
24
36
|
def handle(event)
|
|
@@ -27,12 +39,18 @@ module Pgbus
|
|
|
27
39
|
|
|
28
40
|
private
|
|
29
41
|
|
|
30
|
-
def process!(message)
|
|
42
|
+
def process!(message, claim_beat = nil)
|
|
31
43
|
raw = JSON.parse(message.message)
|
|
32
44
|
event = build_event(raw)
|
|
33
45
|
routing_key = raw.dig("headers", "routing_key") || raw["routing_key"]
|
|
34
46
|
|
|
35
|
-
|
|
47
|
+
if self.class.idempotent?
|
|
48
|
+
claim = claim_idempotency(event.event_id)
|
|
49
|
+
unless claim.granted?
|
|
50
|
+
instrument_skip(claim, event, message, routing_key)
|
|
51
|
+
return :skipped
|
|
52
|
+
end
|
|
53
|
+
end
|
|
36
54
|
|
|
37
55
|
instrument_payload = {
|
|
38
56
|
event_id: event.event_id,
|
|
@@ -42,11 +60,13 @@ module Pgbus
|
|
|
42
60
|
read_ct: message.read_ct.to_i,
|
|
43
61
|
msg_id: message.msg_id.to_i
|
|
44
62
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
63
|
+
with_claim_beat(claim_beat, event.event_id) do
|
|
64
|
+
Instrumentation.instrument("pgbus.event_processed", instrument_payload) do
|
|
65
|
+
# Publisher's Current attributes (issue #431) are set for the handler
|
|
66
|
+
# and reverted after (CurrentAttributes#set semantics); the Rails
|
|
67
|
+
# executor wrap above additionally resets at completion.
|
|
68
|
+
Pgbus::CurrentAttributes.restore(event.context) { handle(event) }
|
|
69
|
+
end
|
|
50
70
|
end
|
|
51
71
|
complete_claim!(event.event_id) if self.class.idempotent?
|
|
52
72
|
:handled
|
|
@@ -64,7 +84,7 @@ module Pgbus
|
|
|
64
84
|
|
|
65
85
|
# Mirrors Pgbus::ActiveJob::Executor#execute_job: wrap the handler
|
|
66
86
|
# invocation in Rails.application.executor (or the reloader in dev)
|
|
67
|
-
# so AR connections leased by `claim_idempotency
|
|
87
|
+
# so AR connections leased by `claim_idempotency` and `handle` are
|
|
68
88
|
# released back to the pool when this method returns. Without the
|
|
69
89
|
# wrap, every consumed event leaks one AR connection on the consumer
|
|
70
90
|
# thread — in dev that wedges `clear_reloadable_connections!`,
|
|
@@ -113,24 +133,32 @@ module Pgbus
|
|
|
113
133
|
|
|
114
134
|
# Two-phase idempotency claim (issue #385). Phase 1: atomically claim
|
|
115
135
|
# via INSERT ... ON CONFLICT DO NOTHING with completed_at NULL — a
|
|
116
|
-
# *pending* claim. Returns
|
|
136
|
+
# *pending* claim. Returns a ClaimResult whose status is one of:
|
|
117
137
|
#
|
|
118
|
-
#
|
|
119
|
-
#
|
|
120
|
-
#
|
|
121
|
-
#
|
|
122
|
-
#
|
|
123
|
-
#
|
|
138
|
+
# :claimed — insert won (fresh claim), or the row was purged between
|
|
139
|
+
# the losing insert and the read, or an existing pending
|
|
140
|
+
# claim has gone silent for longer than the ownership
|
|
141
|
+
# window: the holder is dead by the heartbeat's own
|
|
142
|
+
# definition, so re-run rather than silently drop the
|
|
143
|
+
# execution a SIGKILL interrupted.
|
|
144
|
+
# :completed — the execution already finished. Skip.
|
|
145
|
+
# :owned — pending, and its liveness stamp is fresh: the holder is
|
|
146
|
+
# still running (issue #470). Skip — running `handle`
|
|
147
|
+
# concurrently with the holder is exactly the
|
|
148
|
+
# double-execution `idempotent!` promises not to do. The
|
|
149
|
+
# holder either completes (nothing lost) or fails, leaving
|
|
150
|
+
# its own message for VT redelivery to recover.
|
|
151
|
+
# :cached — a completed execution already in this process's memory.
|
|
124
152
|
#
|
|
125
|
-
#
|
|
126
|
-
#
|
|
127
|
-
# the in-memory dedup cache.
|
|
153
|
+
# Phase 2 is complete_claim! after handle returns; only completed
|
|
154
|
+
# executions enter the in-memory dedup cache.
|
|
128
155
|
#
|
|
129
156
|
# Legacy fallback: without the completed_at column (upgraded gem,
|
|
130
|
-
# not-yet-migrated table) this degrades to the old single-phase claim
|
|
131
|
-
|
|
157
|
+
# not-yet-migrated table) this degrades to the old single-phase claim,
|
|
158
|
+
# which has no pending state and therefore no ownership question.
|
|
159
|
+
def claim_idempotency(event_id)
|
|
132
160
|
cache_key = dedup_key(event_id)
|
|
133
|
-
return
|
|
161
|
+
return ClaimResult.new(status: :cached, age: nil) if self.class.dedup_cache.seen?(cache_key)
|
|
134
162
|
|
|
135
163
|
result = ProcessedEvent.insert(
|
|
136
164
|
{ event_id: event_id, handler_class: self.class.name, processed_at: Time.now.utc },
|
|
@@ -139,18 +167,79 @@ module Pgbus
|
|
|
139
167
|
|
|
140
168
|
unless ProcessedEvent.completion_column?
|
|
141
169
|
self.class.dedup_cache.mark!(cache_key)
|
|
142
|
-
return result.rows.any?
|
|
170
|
+
return ClaimResult.new(status: result.rows.any? ? :claimed : :completed, age: nil)
|
|
143
171
|
end
|
|
144
172
|
|
|
145
|
-
return
|
|
173
|
+
return ClaimResult.new(status: :claimed, age: nil) if result.rows.any?
|
|
174
|
+
|
|
175
|
+
inspect_existing_claim(event_id, cache_key)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# The insert lost, so a row exists (or existed). `pick` returns nil for
|
|
179
|
+
# the whole row when it has since been purged — not a pending claim,
|
|
180
|
+
# nothing is running, so claim it.
|
|
181
|
+
def inspect_existing_claim(event_id, cache_key)
|
|
182
|
+
completed_at, processed_at = ProcessedEvent
|
|
183
|
+
.where(event_id: event_id, handler_class: self.class.name)
|
|
184
|
+
.pick(:completed_at, :processed_at)
|
|
185
|
+
|
|
186
|
+
if completed_at
|
|
187
|
+
self.class.dedup_cache.mark!(cache_key)
|
|
188
|
+
return ClaimResult.new(status: :completed, age: nil)
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
return ClaimResult.new(status: :claimed, age: nil) if processed_at.nil?
|
|
192
|
+
|
|
193
|
+
age = Time.now.utc - processed_at.to_time.utc
|
|
194
|
+
return ClaimResult.new(status: :owned, age: age) if age < claim_ownership_window
|
|
195
|
+
|
|
196
|
+
ClaimResult.new(status: :claimed, age: age)
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
# How long a pending claim may stay silent before its holder counts as
|
|
200
|
+
# dead. ClaimBeat refreshes a live claim from the visibility heartbeat,
|
|
201
|
+
# which lands every extension inside [interval, 1.5 * interval] of the
|
|
202
|
+
# previous one — two intervals leaves margin for a late beat without
|
|
203
|
+
# stretching the window past the visibility timeout it rides on.
|
|
204
|
+
#
|
|
205
|
+
# With the heartbeat disabled a claim is never refreshed, so the window
|
|
206
|
+
# degrades to "roughly the first two thirds of one visibility timeout
|
|
207
|
+
# after the claim" — a redelivery, which cannot arrive before the VT has
|
|
208
|
+
# lapsed, still re-runs exactly as it did before issue #470.
|
|
209
|
+
def claim_ownership_window
|
|
210
|
+
Pgbus.configuration.effective_visibility_heartbeat_interval * 2
|
|
211
|
+
end
|
|
146
212
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
213
|
+
# Register this claim with the message's beat for exactly the duration of
|
|
214
|
+
# handle: before it, there is nothing to keep alive; after it,
|
|
215
|
+
# complete_claim! owns the row and a beat touching processed_at would
|
|
216
|
+
# race the completion stamp.
|
|
217
|
+
def with_claim_beat(claim_beat, event_id)
|
|
218
|
+
return yield unless claim_beat && self.class.idempotent? && ProcessedEvent.completion_column?
|
|
219
|
+
|
|
220
|
+
claim_beat.register(event_id, self.class.name)
|
|
221
|
+
begin
|
|
222
|
+
yield
|
|
223
|
+
ensure
|
|
224
|
+
claim_beat.release(event_id, self.class.name)
|
|
225
|
+
end
|
|
226
|
+
end
|
|
151
227
|
|
|
152
|
-
|
|
153
|
-
|
|
228
|
+
# A skip used to be silent, which made an over-eager re-run (issue #470)
|
|
229
|
+
# invisible in production: nothing distinguished "deduplicated" from
|
|
230
|
+
# "deferred to a live holder". The claim age and read_ct are what tell
|
|
231
|
+
# an operator which one happened.
|
|
232
|
+
def instrument_skip(claim, event, message, routing_key)
|
|
233
|
+
Instrumentation.instrument(
|
|
234
|
+
"pgbus.event_skipped",
|
|
235
|
+
event_id: event.event_id,
|
|
236
|
+
handler: self.class.name,
|
|
237
|
+
routing_key: routing_key,
|
|
238
|
+
reason: claim.status,
|
|
239
|
+
claim_age: claim.age,
|
|
240
|
+
read_ct: message.read_ct.to_i,
|
|
241
|
+
msg_id: message.msg_id.to_i
|
|
242
|
+
)
|
|
154
243
|
end
|
|
155
244
|
|
|
156
245
|
# Phase 2: stamp the claim completed and only then admit it to the
|
|
@@ -165,11 +254,11 @@ module Pgbus
|
|
|
165
254
|
# The stamp is an idempotent `SET completed_at = <now>`, so repeating a
|
|
166
255
|
# statement that may already have committed is safe.
|
|
167
256
|
#
|
|
168
|
-
# Phase 1 (claim_idempotency
|
|
257
|
+
# Phase 1 (claim_idempotency) is deliberately NOT wrapped. Its INSERT
|
|
169
258
|
# may have committed before the socket died, and on a legacy schema the
|
|
170
259
|
# retry's empty `result.rows` would read as "someone else owns this
|
|
171
|
-
# claim" and
|
|
172
|
-
# skipped event. VT redelivery is the correct recovery there.
|
|
260
|
+
# claim" and report :completed — turning a recoverable drop into a
|
|
261
|
+
# silently skipped event. VT redelivery is the correct recovery there.
|
|
173
262
|
def complete_claim!(event_id)
|
|
174
263
|
return unless ProcessedEvent.completion_column?
|
|
175
264
|
|
|
@@ -25,7 +25,7 @@ module Pgbus
|
|
|
25
25
|
Pgbus::Testing.store.push_event(event)
|
|
26
26
|
|
|
27
27
|
if Pgbus::Testing.inline? && delay.to_i <= 0
|
|
28
|
-
Pgbus::EventBus::Registry.instance.
|
|
28
|
+
Pgbus::EventBus::Registry.instance.subscribers_matching(routing_key).each do |subscriber|
|
|
29
29
|
Pgbus::CurrentAttributes.restore(event.context) { subscriber.handler_class.new.handle(event) }
|
|
30
30
|
end
|
|
31
31
|
end
|
|
@@ -62,7 +62,30 @@ module Pgbus
|
|
|
62
62
|
end
|
|
63
63
|
end
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
# Subscribers a message read from +queue_name+ must be dispatched to
|
|
66
|
+
# (issue #469). Every subscriber gets its own queue, so a topic with N
|
|
67
|
+
# matching subscribers produces N queue copies of each event; selecting by
|
|
68
|
+
# pattern alone fanned every copy out to every match, running each handler
|
|
69
|
+
# N times per event — and, across hosts, concurrently. Ownership is the
|
|
70
|
+
# primary filter; the pattern check still applies because a routing key
|
|
71
|
+
# the owner's pattern does not match means a stale pgmq.topic_bindings
|
|
72
|
+
# row, and a stale binding must not run the handler.
|
|
73
|
+
#
|
|
74
|
+
# +queue_name+ is required on purpose: a keyword-less call would silently
|
|
75
|
+
# restore the fan-out this closed. Callers that genuinely want the
|
|
76
|
+
# pattern view (the Testing inline/drain paths, which never touch a
|
|
77
|
+
# queue) use #subscribers_matching.
|
|
78
|
+
def handlers_for(routing_key, queue_name:)
|
|
79
|
+
@subscribers.select do |s|
|
|
80
|
+
s.queue_name == queue_name && matches?(s.pattern, routing_key)
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Pattern-only selection, with no queue in play. Used by the Testing
|
|
85
|
+
# inline/drain paths, where the event never reaches PGMQ and each matching
|
|
86
|
+
# subscriber is invoked exactly once — the same per-subscriber delivery
|
|
87
|
+
# count owner-only dispatch produces in production.
|
|
88
|
+
def subscribers_matching(routing_key)
|
|
66
89
|
@subscribers.select { |s| matches?(s.pattern, routing_key) }
|
|
67
90
|
end
|
|
68
91
|
|
|
@@ -20,6 +20,10 @@ module Pgbus
|
|
|
20
20
|
# payload: queue, job_class, msg_id, vt, extensions
|
|
21
21
|
# pgbus.event_processed — event handler succeeded
|
|
22
22
|
# pgbus.event_failed — event handler raised; carries :exception_object
|
|
23
|
+
# pgbus.event_unrouted — a consumer read an event from a queue no
|
|
24
|
+
# subscriber in this process owns (stale topic
|
|
25
|
+
# binding); the message is archived
|
|
26
|
+
# payload: queue_name, routing_key
|
|
23
27
|
# pgbus.stream.broadcast — stream broadcast (sync or deferred)
|
|
24
28
|
# pgbus.outbox.publish — outbox row created
|
|
25
29
|
# pgbus.recurring.enqueue — scheduler enqueued a due recurring task
|
|
@@ -33,6 +33,7 @@ module Pgbus
|
|
|
33
33
|
subscribe("pgbus.job_visibility_extended") { |event| on_job_visibility_extended(event) },
|
|
34
34
|
subscribe("pgbus.event_processed") { |event| on_event_processed(event) },
|
|
35
35
|
subscribe("pgbus.event_failed") { |event| on_event_failed(event) },
|
|
36
|
+
subscribe("pgbus.event_skipped") { |event| on_event_skipped(event) },
|
|
36
37
|
subscribe("pgbus.client.send_message") { |event| on_send_message(event) },
|
|
37
38
|
subscribe("pgbus.client.send_batch") { |event| on_send_batch(event) },
|
|
38
39
|
subscribe("pgbus.client.read_batch") { |event| on_read_batch(event) },
|
|
@@ -139,6 +140,19 @@ module Pgbus
|
|
|
139
140
|
)
|
|
140
141
|
end
|
|
141
142
|
|
|
143
|
+
# An idempotent handler that did not run this delivery. `reason` is what
|
|
144
|
+
# makes the skip readable: :completed/:cached is deduplication working,
|
|
145
|
+
# :owned means a second delivery arrived while the holder was still
|
|
146
|
+
# running and was deferred to it (issue #470).
|
|
147
|
+
def on_event_skipped(event)
|
|
148
|
+
payload = event.payload
|
|
149
|
+
backend.increment(
|
|
150
|
+
"#{METRIC_PREFIX}event_count", 1,
|
|
151
|
+
compact(handler: payload[:handler], routing_key: payload[:routing_key],
|
|
152
|
+
status: "skipped", reason: payload[:reason])
|
|
153
|
+
)
|
|
154
|
+
end
|
|
155
|
+
|
|
142
156
|
# ── Client (PGMQ wrapper) ─────────────────────────────────────────
|
|
143
157
|
|
|
144
158
|
def on_send_message(event)
|
|
@@ -78,6 +78,11 @@ module Pgbus
|
|
|
78
78
|
)
|
|
79
79
|
@registry = EventBus::Registry.instance
|
|
80
80
|
@circuit_breaker = Pgbus::CircuitBreaker.new(config: config)
|
|
81
|
+
# Queues already warned about for an unroutable message (issue #469).
|
|
82
|
+
# handle_message runs on the execution pool, so this is touched from
|
|
83
|
+
# several threads — Concurrent::Set makes add? the atomic
|
|
84
|
+
# test-and-set the once-per-queue guarantee needs.
|
|
85
|
+
@unrouted_queues = Concurrent::Set.new
|
|
81
86
|
# stat_buffer: :default means "build one iff config.stats_enabled";
|
|
82
87
|
# passing an explicit value (including nil) overrides that for tests.
|
|
83
88
|
@stat_buffer =
|
|
@@ -222,10 +227,12 @@ module Pgbus
|
|
|
222
227
|
raw = JSON.parse(message.message)
|
|
223
228
|
routing_key = raw.dig("headers", "routing_key") || raw["routing_key"]
|
|
224
229
|
|
|
225
|
-
handlers = @registry.handlers_for(routing_key || "")
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
230
|
+
handlers = @registry.handlers_for(routing_key || "", queue_name: queue_name)
|
|
231
|
+
|
|
232
|
+
if handlers.empty?
|
|
233
|
+
report_unrouted(queue_name, routing_key)
|
|
234
|
+
else
|
|
235
|
+
dispatch(handlers, message, queue_name)
|
|
229
236
|
end
|
|
230
237
|
|
|
231
238
|
Pgbus.client.archive_message(queue_name, message.msg_id.to_i)
|
|
@@ -247,6 +254,65 @@ module Pgbus
|
|
|
247
254
|
@jobs_processed.increment
|
|
248
255
|
end
|
|
249
256
|
|
|
257
|
+
# Run every handler that owns this message, with the message's visibility
|
|
258
|
+
# timeout held open for as long as they take (issue #470).
|
|
259
|
+
#
|
|
260
|
+
# Without this the consumer had no equivalent of
|
|
261
|
+
# ActiveJob::Executor#with_visibility_heartbeat: an event handler slower
|
|
262
|
+
# than config.visibility_timeout (30s by default) was redelivered *while
|
|
263
|
+
# still running*, a second consumer read the same envelope, and the
|
|
264
|
+
# holder's pending idempotency claim was indistinguishable from a claim
|
|
265
|
+
# left by a crash — so the handler ran twice, concurrently.
|
|
266
|
+
#
|
|
267
|
+
# The beat also refreshes the claims the handlers register, which is what
|
|
268
|
+
# lets Handler tell "holder still running" from "holder died": message
|
|
269
|
+
# visibility and claim liveness go quiet together when this process does.
|
|
270
|
+
#
|
|
271
|
+
# Tracking ends before the caller archives — a beat must never re-arm the
|
|
272
|
+
# VT of a message that is already gone (same rule as the executor's).
|
|
273
|
+
def dispatch(handlers, message, queue_name)
|
|
274
|
+
claim_beat = EventBus::ClaimBeat.new
|
|
275
|
+
|
|
276
|
+
VisibilityHeartbeat.track(
|
|
277
|
+
client: Pgbus.client,
|
|
278
|
+
queue_name: queue_name,
|
|
279
|
+
msg_id: message.msg_id.to_i,
|
|
280
|
+
job_class: "EventConsumer",
|
|
281
|
+
config: config,
|
|
282
|
+
on_beat: -> { claim_beat.touch! }
|
|
283
|
+
) do
|
|
284
|
+
handlers.each { |subscriber| subscriber.handler_class.new.process(message, claim_beat: claim_beat) }
|
|
285
|
+
end
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
# No subscriber in this process owns +queue_name+ (a stale
|
|
289
|
+
# pgmq.topic_bindings row left by a renamed or removed handler, another
|
|
290
|
+
# app bound to the same bus), or the owner's pattern no longer matches the
|
|
291
|
+
# routing key. The message is archived by the caller either way — looping
|
|
292
|
+
# it through VT redelivery would only walk it into the DLQ — but that used
|
|
293
|
+
# to happen in total silence. The warning is rate-limited to once per
|
|
294
|
+
# queue per process so a permanently stale binding cannot flood the log;
|
|
295
|
+
# the instrumentation fires on every message, so the real rate stays
|
|
296
|
+
# visible in metrics (issue #469).
|
|
297
|
+
def report_unrouted(queue_name, routing_key)
|
|
298
|
+
first_for_queue = @unrouted_queues.add?(queue_name)
|
|
299
|
+
|
|
300
|
+
if first_for_queue
|
|
301
|
+
Pgbus.logger.warn do
|
|
302
|
+
"[Pgbus] Consumer read an unroutable event from queue #{queue_name} " \
|
|
303
|
+
"(routing_key=#{routing_key.inspect}): no subscriber in this process owns that queue. " \
|
|
304
|
+
"Archiving. This usually means a stale topic binding — a handler was renamed or removed " \
|
|
305
|
+
"without unbinding its queue. Further unrouted messages on this queue are not logged."
|
|
306
|
+
end
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
Pgbus::Instrumentation.instrument(
|
|
310
|
+
"pgbus.event_unrouted",
|
|
311
|
+
queue_name: queue_name,
|
|
312
|
+
routing_key: routing_key
|
|
313
|
+
)
|
|
314
|
+
end
|
|
315
|
+
|
|
250
316
|
# Record a job stat for the handled message, mirroring the shape the
|
|
251
317
|
# executor pushes (Executor#record_stat) so consumer and worker throughput
|
|
252
318
|
# land in the same pgbus_job_stats table. No-op unless stats are enabled.
|
|
@@ -521,6 +587,7 @@ module Pgbus
|
|
|
521
587
|
# wait IS its drain window — bound it by the same knob workers use
|
|
522
588
|
# instead of a hardcoded 30s (issue #386).
|
|
523
589
|
@pool.wait_for_termination(config.drain_timeout)
|
|
590
|
+
VisibilityHeartbeat.stop
|
|
524
591
|
@stat_buffer&.stop
|
|
525
592
|
@heartbeat&.stop
|
|
526
593
|
restore_signals
|
data/lib/pgbus/testing.rb
CHANGED
|
@@ -58,7 +58,7 @@ module Pgbus
|
|
|
58
58
|
event = @mutex.synchronize { @events.first }
|
|
59
59
|
break unless event
|
|
60
60
|
|
|
61
|
-
Pgbus::EventBus::Registry.instance.
|
|
61
|
+
Pgbus::EventBus::Registry.instance.subscribers_matching(event.routing_key).each do |subscriber|
|
|
62
62
|
# Restore the publisher's Current (issue #431) like the consumer does.
|
|
63
63
|
Pgbus::CurrentAttributes.restore(event.context) { subscriber.handler_class.new.handle(event) }
|
|
64
64
|
end
|
data/lib/pgbus/version.rb
CHANGED
|
@@ -25,9 +25,15 @@ module Pgbus
|
|
|
25
25
|
# out with `pgbus_visibility_heartbeat false`.
|
|
26
26
|
module VisibilityHeartbeat
|
|
27
27
|
# `concurrency` is `[key, duration]` for a concurrency-limited job, else
|
|
28
|
-
# nil
|
|
28
|
+
# nil. `on_beat` is an optional callable run on every extension — the event
|
|
29
|
+
# consumer uses it to refresh its handlers' idempotency claims (issue #470).
|
|
30
|
+
#
|
|
31
|
+
# The ninth member takes the struct out of the 80-byte slot it used to fit
|
|
32
|
+
# (measured: 80 → 160). That is paid at most once per in-flight message, so
|
|
33
|
+
# the whole table is bounded by the execution pool's capacity — a handful of
|
|
34
|
+
# entries per process, not one per enqueued job.
|
|
29
35
|
Entry = Struct.new(:client, :queue_name, :prefixed, :msg_id, :job_class, :extended_at, :extensions,
|
|
30
|
-
:concurrency, keyword_init: true)
|
|
36
|
+
:concurrency, :on_beat, keyword_init: true)
|
|
31
37
|
|
|
32
38
|
# Per-job opt-out, included on ActiveJob::Base by the engine:
|
|
33
39
|
#
|
|
@@ -59,13 +65,14 @@ module Pgbus
|
|
|
59
65
|
# @param config [Pgbus::Configuration]
|
|
60
66
|
# @param concurrency [Array(String, Numeric), nil] semaphore key to keep alive alongside
|
|
61
67
|
# the message and how far to push its expiry on each beat
|
|
68
|
+
# @param on_beat [#call, nil] run after each extension; its failures are contained
|
|
62
69
|
def track(client:, queue_name:, msg_id:, prefixed: true, job_class: nil, config: Pgbus.configuration,
|
|
63
|
-
concurrency: nil)
|
|
70
|
+
concurrency: nil, on_beat: nil)
|
|
64
71
|
return yield unless config.visibility_heartbeat
|
|
65
72
|
|
|
66
73
|
entry = Entry.new(client: client, queue_name: queue_name, prefixed: prefixed, msg_id: msg_id.to_i,
|
|
67
74
|
job_class: job_class, extended_at: monotonic_now, extensions: 0,
|
|
68
|
-
concurrency: concurrency)
|
|
75
|
+
concurrency: concurrency, on_beat: on_beat)
|
|
69
76
|
register(entry, config)
|
|
70
77
|
begin
|
|
71
78
|
yield
|
|
@@ -130,6 +137,7 @@ module Pgbus
|
|
|
130
137
|
entry.extended_at = now
|
|
131
138
|
entry.extensions += 1
|
|
132
139
|
touch_semaphore(entry)
|
|
140
|
+
run_on_beat(entry)
|
|
133
141
|
Instrumentation.instrument(
|
|
134
142
|
"pgbus.job_visibility_extended",
|
|
135
143
|
queue: entry.queue_name, job_class: entry.job_class, msg_id: entry.msg_id, vt: vt,
|
|
@@ -186,6 +194,17 @@ module Pgbus
|
|
|
186
194
|
end
|
|
187
195
|
end
|
|
188
196
|
|
|
197
|
+
# Same containment as touch_semaphore: a lease the beat keeps alive
|
|
198
|
+
# alongside the message must never cost the message its extension.
|
|
199
|
+
def run_on_beat(entry)
|
|
200
|
+
entry.on_beat&.call
|
|
201
|
+
rescue StandardError => e
|
|
202
|
+
Pgbus.logger.warn do
|
|
203
|
+
"[Pgbus::VisibilityHeartbeat] on_beat hook failed for msg_id=#{entry.msg_id} " \
|
|
204
|
+
"queue=#{entry.queue_name}: #{e.class}: #{e.message}"
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
|
|
189
208
|
def forget_parent_entries!
|
|
190
209
|
return if @pid == ::Process.pid
|
|
191
210
|
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: pgbus
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.16.
|
|
4
|
+
version: 0.16.7
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Mikael Henriksson
|
|
@@ -291,6 +291,7 @@ files:
|
|
|
291
291
|
- lib/pgbus/engine.rb
|
|
292
292
|
- lib/pgbus/error_reporter.rb
|
|
293
293
|
- lib/pgbus/event.rb
|
|
294
|
+
- lib/pgbus/event_bus/claim_beat.rb
|
|
294
295
|
- lib/pgbus/event_bus/handler.rb
|
|
295
296
|
- lib/pgbus/event_bus/publisher.rb
|
|
296
297
|
- lib/pgbus/event_bus/registry.rb
|