pgbus 0.27.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module ActiveJob
5
+ class Coalesce
6
+ # Whether a Pgbus.coalesce scope (the request middleware's, a batch's)
7
+ # may hold a job class (issue #689). Included on ActiveJob::Base by the
8
+ # engine:
9
+ #
10
+ # class ProcessItemJob < ApplicationJob
11
+ # pgbus_coalesce false # sent at its perform_later, inside a scope too
12
+ # end
13
+ #
14
+ # A class that declares nothing follows config.coalesce_default (true:
15
+ # held). With the default false, only classes that declare
16
+ # `pgbus_coalesce true` are held. Subclasses inherit the setting.
17
+ module JobMixin
18
+ extend ActiveSupport::Concern
19
+
20
+ included do
21
+ # A per-class setting the job's own class body writes at load
22
+ # (`pgbus_coalesce false`); the adapter only reads it at enqueue.
23
+ class_attribute :pgbus_coalesce_enabled, instance_writer: false, default: nil # rubocop:disable ThreadSafety/ClassAndModuleAttributes
24
+ end
25
+
26
+ class_methods do
27
+ def pgbus_coalesce(enabled = true) # rubocop:disable Style/OptionalBooleanParameter
28
+ self.pgbus_coalesce_enabled = enabled ? true : false
29
+ end
30
+
31
+ # The adapter's check: the class's own setting, else the configured default.
32
+ def pgbus_coalesce?
33
+ enabled = pgbus_coalesce_enabled
34
+ enabled.nil? ? Pgbus.configuration.coalesce_default : enabled
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module ActiveJob
5
+ class Coalesce
6
+ # Coalesces a request's enqueues (issue #682): the request runs inside
7
+ # Pgbus.coalesce, and the buffer is sent before the response tuple is
8
+ # returned, never after the response (rack.response_finished), so a
9
+ # crash once the client has its answer cannot lose a job. A job
10
+ # enqueued while a streaming body is iterated goes out at once.
11
+ #
12
+ # Opt-in: insert it after ActionDispatch::Executor, or set
13
+ # config.pgbus.coalesce_requests = true (Pgbus::Engine does the insert).
14
+ # With on_failure: :raise (the default) a job that cannot be sent fails
15
+ # the request; an endpoint that must not answer 500 after committing its
16
+ # writes passes :report or a callable. Inserted after the Executor, the
17
+ # error surfaces above ActionDispatch::ShowExceptions, so the client
18
+ # gets the server's bare 500, not the app's error page.
19
+ class Middleware
20
+ def initialize(app, on_failure: :raise)
21
+ Coalesce.validate_on_failure!(on_failure)
22
+ @app = app
23
+ @on_failure = on_failure
24
+ end
25
+
26
+ # A flush that raises (on_failure: :raise, or a callable that raises)
27
+ # closes the body first, as Rack requires of a response it will never
28
+ # send.
29
+ def call(env)
30
+ response = nil
31
+ Pgbus.coalesce(on_failure: @on_failure) { response = @app.call(env) }
32
+ rescue Exception # rubocop:disable Lint/RescueException -- closes, then re-raises
33
+ close_body(response&.at(2))
34
+ raise
35
+ end
36
+
37
+ private
38
+
39
+ # A body whose close raises must not hide the error being raised.
40
+ def close_body(body)
41
+ body.close if body.respond_to?(:close)
42
+ rescue StandardError => e
43
+ Pgbus.logger.warn { "[Pgbus] Closing the response body failed: #{e.class}: #{e.message}" }
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,307 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module ActiveJob
5
+ # A unit of work's enqueues, held at the adapter and sent together when
6
+ # the unit ends (issue #682): one send_batch per (queue, priority, delay) group
7
+ # instead of one send per perform_later. Opened by Pgbus.coalesce and the
8
+ # Rack Middleware.
9
+ #
10
+ # Only a bulk-eligible job is held (Adapter#enqueue / #enqueue_at
11
+ # decide), serialized at perform_later; a future one with its scheduled
12
+ # time, so its delay is what is left at the flush (issue #686). One with
13
+ # uniqueness or concurrency, a retry re-enqueue, a deploy task run's job,
14
+ # a batch member outside its own batch's scope, a Workflow::StepJob or a
15
+ # class the scope may not hold (`pgbus_coalesce false`, or no
16
+ # `pgbus_coalesce true` under config.coalesce_default false, issue #689)
17
+ # goes out at once, as it does outside a scope. Active Job's enqueue_after_transaction_commit runs before the
18
+ # adapter, so a job that defers reaches the buffer at commit, and a rolled
19
+ # back one never does.
20
+ #
21
+ # perform_later inside the scope returns the job with successfully_enqueued
22
+ # true and provider_job_id nil until the flush, the same optimistic answer
23
+ # Active Job gives a job deferred to after commit. The flush proves the
24
+ # delivery: Adapter#deliver_coalesced sends the buffer in bulk, retries
25
+ # every job it left unsent on its own, and what still fails goes to
26
+ # on_failure (:raise, :report, or a callable taking (jobs, error)).
27
+ #
28
+ # The scope is fiber-local (Thread.current, like the batch tag) and
29
+ # cleared before the flush starts, so a job enqueued on another thread or
30
+ # fiber, during the flush, or after the block, goes out at once. A nested
31
+ # scope joins the outer one, whose on_failure applies; only the outermost
32
+ # flushes.
33
+ #
34
+ # A batch scope (issue #683, opened by Pgbus.batch for a batch it builds,
35
+ # with +batch_id+ and +count_in+) holds only that batch's members and
36
+ # joins nothing: it replaces the current scope for the block, flushes
37
+ # when the block ends and puts the outer scope back. A plain scope opened
38
+ # inside it joins it. A batch scope counts each chunk in before sending
39
+ # it, with one call: count_in.call(payloads, final:). The final call
40
+ # (the block's end) also closes the batch's build, in the same
41
+ # transaction; see Batch#count_in. Before on_failure, a batch scope hands
42
+ # the jobs that were never sent to on_failed (Batch#record_enqueue_failures),
43
+ # so the batch counts them as failed. Every scope flushes early each
44
+ # config.coalesce_chunk_size held jobs, so a huge block stays bounded in
45
+ # memory (a batch scope only once no transaction is open on the batch's
46
+ # connection: until then it keeps holding); on_failure still runs once,
47
+ # at the end, for every chunk.
48
+ class Coalesce
49
+ KEY = :pgbus_coalesce
50
+ FAILURE_MODES = %i[raise report].freeze
51
+
52
+ Result = Data.define(:buffered, :sent, :retried, :failed, :error)
53
+
54
+ class << self
55
+ # The scope open on this thread or fiber, nil when there is none.
56
+ def current
57
+ Thread.current[KEY]
58
+ end
59
+
60
+ def open(on_failure: :raise, batch_id: nil, count_in: nil, on_failed: nil, &block)
61
+ raise ArgumentError, "Pgbus.coalesce needs a block" unless block
62
+
63
+ validate_on_failure!(on_failure)
64
+ return yield if current && batch_id.nil?
65
+
66
+ run(new(on_failure: on_failure, batch_id: batch_id, count_in: count_in, on_failed: on_failed), &block)
67
+ end
68
+
69
+ def validate_on_failure!(on_failure)
70
+ return if FAILURE_MODES.include?(on_failure) || on_failure.respond_to?(:call)
71
+
72
+ raise ArgumentError, "on_failure must be :raise, :report or a callable, got #{on_failure.inspect}"
73
+ end
74
+
75
+ private
76
+
77
+ def run(scope)
78
+ outer = current
79
+ Thread.current[KEY] = scope
80
+ error = nil
81
+ begin
82
+ yield
83
+ rescue Exception => e # rubocop:disable Lint/RescueException
84
+ error = e
85
+ raise
86
+ ensure
87
+ # No scope is current while this one flushes: an enqueue then
88
+ # goes out at once. The outer scope comes back afterwards.
89
+ Thread.current[KEY] = nil
90
+ begin
91
+ scope.finish!(block_error: error)
92
+ ensure
93
+ Thread.current[KEY] = outer
94
+ end
95
+ end
96
+ end
97
+ end
98
+
99
+ attr_reader :on_failure, :batch_id
100
+
101
+ def initialize(on_failure: :raise, batch_id: nil, count_in: nil, on_failed: nil,
102
+ chunk_size: Pgbus.configuration.coalesce_chunk_size)
103
+ @on_failure = on_failure
104
+ @batch_id = batch_id
105
+ @count_in = count_in
106
+ @on_failed = on_failed
107
+ @chunk_size = chunk_size
108
+ @mutex = Mutex.new
109
+ @entries = []
110
+ @totals = Result.new(buffered: 0, sent: 0, retried: 0, failed: [], error: nil)
111
+ @failed_entries = []
112
+ @closed = false
113
+ end
114
+
115
+ # Holds +job+ for +adapter+ with the +payload+ serialized at
116
+ # perform_later, and sends the buffer once it holds a chunk. Returns
117
+ # false once the flush has started: the caller sends it itself.
118
+ # +due_at+: the time a future job is due (enqueue_at, issue #686); the
119
+ # flush works its delay out from it.
120
+ def push(adapter, job, payload, due_at = nil) # rubocop:disable Naming/PredicateMethod -- holds; the result says whether
121
+ chunk = @mutex.synchronize do
122
+ return false if @closed
123
+
124
+ # A full chunk goes when the next job arrives, so a block of
125
+ # exactly chunk_size jobs is still one flush, at its end. A batch
126
+ # scope keeps holding while a transaction is open on the batch's
127
+ # connection: a chunk counted in there and sent on PGMQ's own
128
+ # connection would lose its count, not its messages, on a rollback.
129
+ full = drain if @entries.size >= @chunk_size && !hold_for_transaction?
130
+ @entries << [adapter, job, payload, due_at]
131
+ full
132
+ end
133
+ deliver_chunk(chunk) if chunk
134
+ true
135
+ end
136
+
137
+ # Closes the buffer, sends it, then applies on_failure to whatever could
138
+ # not be sent. With +block_error+ (the block raised) a callable still
139
+ # gets the jobs, but nothing raises: :raise becomes a report, and a
140
+ # callable that raises is reported, so the block's error propagates.
141
+ def finish!(block_error: nil)
142
+ started = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
143
+ deliver_chunk(close, final: true)
144
+ failed_entries, result = @mutex.synchronize { [@failed_entries, @totals] }
145
+ instrument(result, started) if result.buffered.positive?
146
+ if result.failed.any?
147
+ @on_failed&.call(result.failed)
148
+ handle_failure(result, failed_entries, block_error)
149
+ end
150
+ result
151
+ rescue StandardError => e
152
+ # The block's error is the one that propagates: anything the flush
153
+ # raises after it (a notification subscriber, say) is reported.
154
+ raise unless block_error
155
+
156
+ ErrorReporter.report(e, { pgbus_coalesce: :finish })
157
+ result
158
+ end
159
+
160
+ private
161
+
162
+ def close
163
+ @mutex.synchronize do
164
+ @closed = true
165
+ drain
166
+ end
167
+ end
168
+
169
+ # Takes the buffer; the caller holds the mutex.
170
+ def drain
171
+ entries = @entries
172
+ @entries = []
173
+ entries
174
+ end
175
+
176
+ # Sends +entries+ now and keeps their result for finish!. A batch
177
+ # scope counts them in first (count_in); the final chunk also closes
178
+ # the batch's build, so it runs even when the chunk is empty.
179
+ def deliver_chunk(entries, final: false)
180
+ counted = count_chunk_in(entries, final)
181
+ return if entries.empty?
182
+
183
+ results = entries.group_by(&:first).map do |adapter, group|
184
+ adapter.deliver_coalesced(group.map { |_, job, payload, due_at| [job, payload, due_at] }, counted: counted)
185
+ end
186
+ result = combine(entries.size, results)
187
+ failed = result.failed.to_set(&:object_id)
188
+ # Only the counts and the failed jobs are kept: a sent chunk's jobs
189
+ # and payloads go, so chunking bounds memory.
190
+ @mutex.synchronize do
191
+ @totals = combine(@totals.buffered + result.buffered, [@totals, result])
192
+ @failed_entries.concat(entries.select { |_, job, _| failed.include?(job.object_id) })
193
+ end
194
+ end
195
+
196
+ def hold_for_transaction?
197
+ return false unless @count_in
198
+
199
+ connection = Pgbus::BatchEntry.connection_pool.active_connection?
200
+ connection ? connection.transaction_open? : false
201
+ rescue StandardError => e
202
+ # Unknown is treated as open: holding a chunk to the block's end is
203
+ # safe, counting it inside a transaction that rolls back is not.
204
+ Pgbus.logger.debug { "[Pgbus] Coalesce could not read the batch connection's transaction (#{e.class}); holding the chunk" }
205
+ true
206
+ end
207
+
208
+ # True when the chunk was counted in. A count that fails (a batch the
209
+ # sweep reaped, a database error) sends nothing: every job of the chunk
210
+ # fails, with that error, through on_failure.
211
+ def count_chunk_in(entries, final)
212
+ return false unless @count_in
213
+
214
+ @count_in.call(entries.map { |_, _, payload, _| payload }, final: final)
215
+ true
216
+ rescue StandardError => e
217
+ raise if entries.empty?
218
+
219
+ jobs = entries.map { |_, job, _| job }
220
+ jobs.each { |job| job.successfully_enqueued = false }
221
+ @mutex.synchronize do
222
+ failed = Result.new(buffered: entries.size, sent: 0, retried: 0, failed: jobs, error: e)
223
+ @totals = combine(@totals.buffered + entries.size, [@totals, failed])
224
+ @failed_entries.concat(entries)
225
+ end
226
+ entries.clear
227
+ false
228
+ end
229
+
230
+ # The held jobs this scope still references, waiting for the flush or
231
+ # failed in it.
232
+ def retained_entries
233
+ @mutex.synchronize { @entries + @failed_entries }
234
+ end
235
+
236
+ def combine(buffered, results)
237
+ Result.new(
238
+ buffered: buffered,
239
+ sent: results.sum(&:sent), retried: results.sum(&:retried),
240
+ failed: results.flat_map(&:failed), error: results.filter_map(&:error).last
241
+ )
242
+ end
243
+
244
+ # A subscriber that raises is reported: the flush's outcome, and the
245
+ # failed jobs on_failure must still see, do not depend on it.
246
+ def instrument(result, started)
247
+ duration = (::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - started) * 1000.0
248
+ Instrumentation.instrument(
249
+ "pgbus.coalesce",
250
+ buffered: result.buffered, sent: result.sent, retried: result.retried,
251
+ failed: result.failed.size, duration: duration
252
+ )
253
+ rescue StandardError => e
254
+ ErrorReporter.report(e, { pgbus_coalesce: :instrument })
255
+ end
256
+
257
+ def handle_failure(result, entries, block_error)
258
+ error = failure_error(result)
259
+ payloads = failed_payloads(result.failed, entries)
260
+ case on_failure
261
+ when :raise then block_error ? report(payloads, error) : raise(error)
262
+ when :report then report(payloads, error)
263
+ else call_on_failure(result.failed, payloads, error, block_error)
264
+ end
265
+ end
266
+
267
+ def call_on_failure(jobs, payloads, error, block_error)
268
+ on_failure.call(jobs, error)
269
+ rescue StandardError => e
270
+ raise unless block_error
271
+
272
+ report(payloads, error)
273
+ ErrorReporter.report(e, { pgbus_coalesce_on_failure: on_failure.to_s })
274
+ end
275
+
276
+ # The payloads serialized at perform_later: a job that failed is never
277
+ # serialized again here.
278
+ def failed_payloads(jobs, entries)
279
+ failed = jobs.to_set(&:object_id)
280
+ entries.filter_map { |_, job, payload| payload if failed.include?(job.object_id) }
281
+ end
282
+
283
+ def failure_error(result)
284
+ names = result.failed.map { |job| "#{job.class.name} (#{job.job_id})" }
285
+ message = "Pgbus.coalesce could not enqueue #{names.size} job(s): #{names.join(", ")}"
286
+ message += " — #{result.error.class}: #{result.error.message}" if result.error
287
+ # Raised and rescued here so the error carries a backtrace and the
288
+ # send's own error as its cause.
289
+ begin
290
+ raise EnqueueError, message, cause: result.error
291
+ rescue EnqueueError => e
292
+ e
293
+ end
294
+ end
295
+
296
+ def report(payloads, error)
297
+ context = { pgbus_coalesce: payloads }
298
+ if defined?(::Rails) && ::Rails.respond_to?(:error)
299
+ Pgbus.logger.error { "[Pgbus] #{error.message}" }
300
+ ::Rails.error.report(error, context: context)
301
+ else
302
+ ErrorReporter.report(error, context)
303
+ end
304
+ end
305
+ end
306
+ end
307
+ end
@@ -43,7 +43,7 @@ module Pgbus
43
43
 
44
44
  def on_failure(job = nil, &) = set_callback(:on_failure, job, &)
45
45
 
46
- # Deprecated alias of #on_complete until 1.0.
46
+ # Deprecated alias of #on_complete, kept past 1.0; removed in 2.0.
47
47
  def on_finish(job = nil, &)
48
48
  Batch.warn_on_finish_deprecated
49
49
  set_callback(:on_complete, job, &)
@@ -14,8 +14,9 @@ module Pgbus
14
14
  return unless Batch.executions_migrated?
15
15
 
16
16
  payload = { stale_executions: 0, orphan_rows: 0, started_batches: 0, finished_batches: 0,
17
- stalled_for: stalled_for }
17
+ abandoned_builds: 0, stalled_for: stalled_for }
18
18
  Instrumentation.instrument("pgbus.batch_sweep", payload) do |p|
19
+ p[:abandoned_builds] = reap_abandoned_builds(batch_size: batch_size)
19
20
  p[:stale_executions] = sweep_stale_executions(batch_size: batch_size, client: client, stalled_for: stalled_for)
20
21
  p[:orphan_rows] = sweep_orphan_rows(stalled_for: stalled_for, batch_size: batch_size, client: client)
21
22
  p[:started_batches] = start_stalled_pending(stalled_for: stalled_for, batch_size: batch_size)
@@ -23,6 +24,46 @@ module Pgbus
23
24
  end
24
25
  end
25
26
 
27
+ # A building batch (issue #683) is reaped only when the process that
28
+ # builds it is dead: its pgbus_processes row is gone or has not
29
+ # heartbeat within Process::Heartbeat::ALIVE_THRESHOLD. A live
30
+ # owner's build is never touched, however long its block runs. One
31
+ # guarded statement per batch (status = 'building'), so the reaper
32
+ # and a block closing its build cannot both win.
33
+ #
34
+ # The abandoned build counts as one failed job (total_jobs and
35
+ # failed_jobs both + 1): whatever its block held was never sent, so
36
+ # the batch must not report success. It moves to processing; the
37
+ # members it did send still resolve, and the batch then finishes
38
+ # through the usual single-winner path, firing on_complete and
39
+ # on_failure, never on_success.
40
+ def reap_abandoned_builds(batch_size: 500, now: Time.current)
41
+ return 0 unless Batch.owner_migrated?
42
+
43
+ alive_since = now - Process::Heartbeat::ALIVE_THRESHOLD
44
+ reaped = BatchEntry.connection_pool.with_connection do |conn|
45
+ conn.exec_query(<<~SQL.squish, "Pgbus Batch Reap Build", [alive_since, batch_size]).rows.flatten
46
+ UPDATE #{BatchEntry.table_name} b
47
+ SET status = 'processing', total_jobs = b.total_jobs + 1, failed_jobs = b.failed_jobs + 1
48
+ WHERE b.id IN (
49
+ SELECT c.id FROM #{BatchEntry.table_name} c
50
+ WHERE c.status = 'building'
51
+ AND NOT EXISTS (
52
+ SELECT 1 FROM #{ProcessEntry.table_name} p
53
+ WHERE p.id = c.owner_process_id AND p.last_heartbeat_at >= $1
54
+ )
55
+ LIMIT $2
56
+ ) AND b.status = 'building'
57
+ RETURNING b.batch_id
58
+ SQL
59
+ end
60
+ reaped.each do |batch_id|
61
+ Pgbus.logger.warn { "[Pgbus] Batch #{batch_id} was being built by a process that stopped heartbeating; reaped" }
62
+ Batch.send(:finish_if_needed, Batch.try_finish!(batch_id))
63
+ end
64
+ reaped.size
65
+ end
66
+
26
67
  private
27
68
 
28
69
  def sweep_stale_executions(batch_size:, client:, stalled_for:)