pgbus 0.27.1 → 1.0.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.
@@ -5,33 +5,192 @@ require "active_job"
5
5
  module Pgbus
6
6
  module ActiveJob
7
7
  class Adapter
8
+ # Inside Pgbus.coalesce a bulk-eligible job is serialized now and held,
9
+ # then sent with the rest when the scope ends (issue #682); everything
10
+ # else is sent now. With no scope open this costs one fiber-local read.
8
11
  def enqueue(active_job)
9
- queue = active_job.queue_name || Pgbus.configuration.default_queue
10
- payload_hash = Serializer.serialize_job_hash(active_job)
11
- payload_hash = Concurrency.inject_metadata(active_job, payload_hash)
12
- payload_hash = Uniqueness.inject_metadata(active_job, payload_hash)
13
- payload_hash = FairShare.inject_metadata(active_job, payload_hash)
14
- payload_hash = inject_batch_metadata(payload_hash, active_job)
15
- note_deploy_task_run_enqueued(active_job, false)
12
+ scope = Coalesce.current
13
+ return active_job if scope && coalesce(scope, active_job)
16
14
 
17
- if uniqueness_rejected?(active_job, payload_hash, queue: queue)
18
- uncount_batch_job(payload_hash, active_job)
19
- return active_job
15
+ enqueue_job(active_job)
16
+ end
17
+
18
+ # A future job is held too inside Pgbus.coalesce (issue #686); its delay
19
+ # is worked out at the flush, from +timestamp+.
20
+ def enqueue_at(active_job, timestamp)
21
+ scope = Coalesce.current
22
+ return active_job if scope && coalesce(scope, active_job, due_at: timestamp)
23
+
24
+ enqueue_job(active_job, delay: delay_until(timestamp))
25
+ end
26
+
27
+ # Sets successfully_enqueued on every job, as ActiveJob.perform_all_later
28
+ # reads it (issue #679): true for a job sent or parked behind its
29
+ # concurrency limit, false for one dropped or never reached because an
30
+ # error raised. Returns the number marked, so the enqueue_all.active_job
31
+ # notification's enqueued_count agrees with the jobs.
32
+ def enqueue_all(active_jobs)
33
+ active_jobs.each do |j|
34
+ j.successfully_enqueued = false
35
+ j.enqueue_error = nil
20
36
  end
21
37
 
22
- enqueue_with_concurrency(active_job, queue, payload_hash)
23
- ensure
24
- forget_enqueue_batch_id(active_job)
38
+ # Jobs with uniqueness or concurrency must go through individual enqueue
39
+ # to acquire locks/semaphores — the bulk path cannot (issue #413)
40
+ individual, bulk = active_jobs.partition { |j| Uniqueness.uniqueness_config(j) || concurrency_config(j) }
41
+ individual.each { |j| enqueue_one_of_all(j) }
42
+
43
+ # Group by priority too: send_batch routes through the queue strategy,
44
+ # so a mixed-priority bulk send needs one produce_batch per level. And
45
+ # by delay (issue #686): PGMQ's batch send takes one delay, so jobs
46
+ # scheduled for the same second go out together, a staggered fan-out
47
+ # as one send per slice.
48
+ bulk.group_by { |j| [j.queue_name || Pgbus.configuration.default_queue, j.try(:priority), job_delay(j)] }
49
+ .each do |(queue, priority, delay), jobs|
50
+ enqueue_immediate(queue, jobs, priority: priority, delay: delay)
51
+ end
52
+
53
+ active_jobs.count(&:successfully_enqueued?)
25
54
  end
26
55
 
27
- def enqueue_at(active_job, timestamp)
56
+ # Sends what a Coalesce scope held, as [job, payload, due_at] entries
57
+ # with the payload serialized at perform_later (issue #682): one
58
+ # send_batch per (queue, priority, delay) group (issue #686), through
59
+ # the bulk path enqueue_all uses, then
60
+ # each job left unsent on its own. Queue and priority are the payload's,
61
+ # so a job changed after perform_later goes where it was sent. Never
62
+ # raises: what still fails is the result's +failed+, for on_failure.
63
+ # +counted+: a batch scope already counted the entries into their batch
64
+ # (issue #683), so the send does not count them again.
65
+ def deliver_coalesced(entries, counted: false)
66
+ jobs = entries.map(&:first)
67
+ jobs.each do |job|
68
+ job.successfully_enqueued = false
69
+ job.enqueue_error = nil
70
+ end
71
+ error = nil
72
+ standing = {}.compare_by_identity
73
+ entries.each { |job, payload, _| standing[job] = true if payload[Batch::METADATA_KEY] } if counted
74
+ groups = entries.group_by do |_, payload, due_at|
75
+ [payload["queue_name"] || Pgbus.configuration.default_queue, payload["priority"], due_delay(due_at)]
76
+ end
77
+ groups.each do |(queue, priority, delay), group|
78
+ enqueue_immediate(queue, group.map(&:first), priority: priority, delay: delay, payloads: group.map { _1[1] },
79
+ counted: standing, tracked: counted)
80
+ rescue StandardError => e
81
+ error = e
82
+ end
83
+ sent = jobs.count(&:successfully_enqueued?)
84
+ unsent = entries.reject { |job, *| job.successfully_enqueued? }
85
+ retried, failed, error = retry_coalesced(unsent, standing, error)
86
+ Coalesce::Result.new(buffered: entries.size, sent: sent, retried: retried, failed: failed, error: error)
87
+ end
88
+
89
+ private
90
+
91
+ # Holds +active_job+ in +scope+, serialized now, when the bulk path can
92
+ # send it, a future one included (+due_at+, its scheduled time: the delay is
93
+ # what is left at the flush, issue #686). Sent at once instead:
94
+ # uniqueness and concurrency (their lock or slot, and its lease over the
95
+ # delay, is taken at enqueue), a retry re-enqueue (#424) and a deploy task run's job (#660), which need the
96
+ # single path's bookkeeping, a batch member outside its own batch's
97
+ # scope (Pgbus.batch opens one for its block, issue #683; an outer
98
+ # scope's flush could come after the sweep reads the batch as stalled),
99
+ # and a pgbus class that opts out (Workflow::StepJob, whose enqueue failure
100
+ # is reported and swept, never raised; pgbus_coalesce? is internal).
101
+ # Serializing now raises an unserializable argument here, as outside a
102
+ # scope, and keeps a later change to the job or its arguments out of
103
+ # the message.
104
+ def coalesce(scope, active_job, due_at: nil)
105
+ return false if Uniqueness.uniqueness_config(active_job) || concurrency_config(active_job)
106
+ return false if active_job.executions.to_i.positive?
107
+ return false if active_job.is_a?(DeployTaskRunId) && active_job.deploy_task_run_id
108
+ return false if member_batch_id(active_job) != scope.batch_id
109
+ return false if active_job.class.respond_to?(:pgbus_coalesce?) && !active_job.class.pgbus_coalesce?
110
+
111
+ payload = tag_bulk_member(FairShare.inject_metadata(active_job, Serializer.serialize_job_hash(active_job)), active_job)
112
+ scope.push(self, active_job, payload, due_at)
113
+ end
114
+
115
+ # Whole seconds until +job+ is due, 0 for a job due now.
116
+ def job_delay(job)
117
+ scheduled_in_future?(job) ? delay_until(job.scheduled_at.to_f) : 0
118
+ end
119
+
120
+ # Whole seconds until +due_at+ (a scheduled time held by a coalesce
121
+ # scope), counted from now, the flush: 0 for none or a time past.
122
+ def due_delay(due_at)
123
+ due_at ? delay_until(due_at.to_f) : 0
124
+ end
125
+
126
+ # Each held job the bulk left unsent, on its own: for a job coalesce
127
+ # admitted, the single path is the plain send, plus a batch member's
128
+ # count and backfill. Returns [retried count, failed jobs, the last error].
129
+ def retry_coalesced(entries, counted, error)
130
+ retried = 0
131
+ failed = []
132
+ entries.each do |job, payload, due_at|
133
+ if resend_coalesced(job, payload, counted: counted.key?(job), delay: due_delay(due_at))
134
+ retried += 1
135
+ else
136
+ failed << job
137
+ end
138
+ rescue StandardError => e
139
+ error = e
140
+ failed << job
141
+ end
142
+ [retried, failed, error]
143
+ end
144
+
145
+ # A batch member not +counted+ is counted in first, as a single
146
+ # enqueue is, and uncounted when its send fails before any message can
147
+ # exist; one the bulk counted keeps that count (its send's outcome is
148
+ # unknown) and is only sent.
149
+ def resend_coalesced(job, payload, counted:, delay: 0) # rubocop:disable Naming/PredicateMethod -- sends; the result says whether
150
+ queue = payload["queue_name"] || Pgbus.configuration.default_queue
151
+ priority = payload["priority"]
152
+ member = payload[Batch::METADATA_KEY]
153
+ Batch.track_enqueue(payload) if member && !counted
154
+ begin
155
+ msg_id = Pgbus.client.send_message(queue, payload, delay: delay, priority: priority)
156
+ rescue StandardError => e
157
+ Batch.untrack_enqueue(payload) if member && !counted && !ambiguous_delivery?(e)
158
+ raise
159
+ end
160
+ unless msg_id
161
+ Batch.untrack_enqueue(payload) if member && !counted
162
+ return false
163
+ end
164
+
165
+ job.provider_job_id = msg_id
166
+ job.successfully_enqueued = true
167
+ Batch.backfill_executions([payload], [msg_id], physical_queue(queue, priority)) if member
168
+ true
169
+ end
170
+
171
+ # One job of an enqueue_all that cannot take the bulk path.
172
+ # enqueue_with_concurrency marks it once it is live, as enqueue_immediate
173
+ # marks the bulk; on perform_later the adapter never sets
174
+ # successfully_enqueued, ActiveJob sets it around enqueue/enqueue_at.
175
+ def enqueue_one_of_all(active_job)
176
+ delay = scheduled_in_future?(active_job) ? delay_until(active_job.scheduled_at.to_f) : 0
177
+ enqueue_job(active_job, delay: delay, mark_enqueued: true)
178
+ end
179
+
180
+ def delay_until(timestamp)
181
+ [(timestamp - Time.current.to_f).ceil, 0].max
182
+ end
183
+
184
+ # Returns the job. With mark_enqueued (enqueue_all), sets
185
+ # successfully_enqueued once the job is live: sent, or parked behind its
186
+ # concurrency limit to run later.
187
+ def enqueue_job(active_job, delay: 0, mark_enqueued: false)
28
188
  queue = active_job.queue_name || Pgbus.configuration.default_queue
29
189
  payload_hash = Serializer.serialize_job_hash(active_job)
30
190
  payload_hash = Concurrency.inject_metadata(active_job, payload_hash)
31
191
  payload_hash = Uniqueness.inject_metadata(active_job, payload_hash)
32
192
  payload_hash = FairShare.inject_metadata(active_job, payload_hash)
33
193
  payload_hash = inject_batch_metadata(payload_hash, active_job)
34
- delay = [(timestamp - Time.current.to_f).ceil, 0].max
35
194
  note_deploy_task_run_enqueued(active_job, false)
36
195
 
37
196
  if uniqueness_rejected?(active_job, payload_hash, queue: queue)
@@ -39,38 +198,12 @@ module Pgbus
39
198
  return active_job
40
199
  end
41
200
 
42
- enqueue_with_concurrency(active_job, queue, payload_hash, delay: delay)
201
+ enqueue_with_concurrency(active_job, queue, payload_hash, delay: delay, mark_enqueued: mark_enqueued)
43
202
  ensure
44
203
  forget_enqueue_batch_id(active_job)
45
204
  end
46
205
 
47
- def enqueue_all(active_jobs)
48
- # Jobs with uniqueness or concurrency must go through individual enqueue
49
- # to acquire locks/semaphores — the bulk path cannot (issue #413)
50
- individual, bulk = active_jobs.partition { |j| Uniqueness.uniqueness_config(j) || concurrency_config(j) }
51
- individual.each do |j|
52
- if scheduled_in_future?(j)
53
- enqueue_at(j, j.scheduled_at.to_f)
54
- else
55
- enqueue(j)
56
- end
57
- end
58
-
59
- # Group by priority too: send_batch routes through the queue strategy,
60
- # so a mixed-priority bulk send needs one produce_batch per level.
61
- bulk.group_by { |j| [j.queue_name || Pgbus.configuration.default_queue, j.try(:priority)] }
62
- .each do |(queue, priority), jobs|
63
- immediate, scheduled = jobs.partition { |j| !scheduled_in_future?(j) }
64
- enqueue_immediate(queue, immediate, priority: priority)
65
- scheduled.each { |j| enqueue_at(j, j.scheduled_at.to_f) }
66
- end
67
-
68
- active_jobs.count
69
- end
70
-
71
- private
72
-
73
- def enqueue_with_concurrency(active_job, queue, payload_hash, delay: 0)
206
+ def enqueue_with_concurrency(active_job, queue, payload_hash, delay: 0, mark_enqueued: false)
74
207
  key = Concurrency.extract_key(payload_hash)
75
208
  concurrency = concurrency_config(active_job)
76
209
  priority = active_job.try(:priority)
@@ -117,6 +250,10 @@ module Pgbus
117
250
  active_job.provider_job_id = msg_id
118
251
  end
119
252
 
253
+ # Marked before any bookkeeping below can raise: the job is live
254
+ # whatever happens next (issue #679).
255
+ active_job.successfully_enqueued = true if mark_enqueued && (msg_id || blocked)
256
+
120
257
  # Bind before backfill so a live message is never left with an unbound
121
258
  # uniqueness row if execution-row bookkeeping raises.
122
259
  bind_acquired_uniqueness_lock(queue, msg_id) if msg_id
@@ -453,35 +590,81 @@ module Pgbus
453
590
  batch_id ? payload_hash.merge(Batch::METADATA_KEY => batch_id) : payload_hash
454
591
  end
455
592
 
456
- def enqueue_immediate(queue, jobs, priority: nil)
593
+ # +payloads+: already built (a Coalesce scope serialized them at push).
594
+ # +counted+ (deliver_coalesced) collects the batch members whose count
595
+ # stands after a failure, so their retry does not count them twice.
596
+ # The bookkeeping around the send is one statement per group (issue
597
+ # #683): track_bulk's insert, the backfill, or the untrack on a failure.
598
+ # +tracked+: the payloads are already counted into their batch.
599
+ # +delay+: whole seconds every job of the group waits (issue #686).
600
+ def enqueue_immediate(queue, jobs, priority: nil, delay: 0, payloads: nil, counted: nil, tracked: false)
457
601
  return if jobs.empty?
458
602
 
459
- payloads = jobs.map do |j|
603
+ payloads ||= jobs.map do |j|
460
604
  tag_bulk_member(FairShare.inject_metadata(j, Serializer.serialize_job_hash(j)), j)
461
605
  end
462
- track_bulk(payloads)
606
+ track_bulk(payloads) unless tracked
607
+ tracked = true
463
608
  physical = physical_queue(queue, priority)
464
609
  msg_ids = nil
465
- msg_ids = Pgbus.client.send_batch(queue, payloads, priority: priority)
610
+ sending = true
611
+ msg_ids = if delay.positive?
612
+ Pgbus.client.send_batch(queue, payloads, delay: delay, priority: priority)
613
+ else
614
+ Pgbus.client.send_batch(queue, payloads, priority: priority)
615
+ end
616
+ sent = true
466
617
 
467
618
  unless msg_ids.is_a?(Array) && msg_ids.size == jobs.size
468
619
  raise Pgbus::EnqueueError, "Pgbus batch enqueue failed: expected #{jobs.size} ids, got #{msg_ids&.size || 0}"
469
620
  end
470
621
 
471
- jobs.zip(msg_ids).each { |job, id| job.provider_job_id = id }
472
- payloads.zip(msg_ids).each { |payload, id| Batch.backfill_execution(payload, id, physical) }
473
- rescue Pgbus::EnqueueError
474
- Array(payloads).each_with_index do |payload, index|
475
- Batch.untrack_enqueue(payload) if msg_ids.nil? || msg_ids[index].nil?
622
+ jobs.zip(msg_ids).each do |job, id|
623
+ job.provider_job_id = id
624
+ job.successfully_enqueued = true
476
625
  end
626
+ Batch.backfill_executions(payloads, msg_ids, physical)
627
+ rescue Pgbus::EnqueueError
628
+ unsent = Array(payloads).each_index.select { |index| msg_ids.nil? || msg_ids[index].nil? }
629
+ # Noted before the untrack, which can raise: a member with an id keeps
630
+ # its count either way.
631
+ note_counted(counted, jobs, payloads, Array(payloads).each_index.to_a - unsent)
632
+ # The unsent ones are uncounted here: their retry counts them again.
633
+ unsent.each { |index| counted&.delete(jobs[index]) }
634
+ Batch.untrack_enqueue_all(payloads.values_at(*unsent))
477
635
  raise
478
- rescue Pgbus::SchemaNotReady => e
479
- Pgbus.logger.error { "[Pgbus] #{e.message}" }
636
+ rescue StandardError => e
637
+ Pgbus.logger.error { "[Pgbus] #{e.message}" } if e.is_a?(Pgbus::SchemaNotReady)
638
+ # After the send returned, its messages are live: the counts stand.
639
+ settle_counted(counted, jobs, payloads, ambiguous: sent || (sending && ambiguous_delivery?(e))) if tracked
480
640
  raise
481
641
  ensure
482
642
  jobs.each { |j| forget_enqueue_batch_id(j) }
483
643
  end
484
644
 
645
+ # A coalesce delivery's members after a failed send (+counted+ set):
646
+ # when the send may have committed, their counts stand and the retry
647
+ # does not count them again; when no message can exist, they are
648
+ # uncounted now and the retry counts each again, so a member that
649
+ # fails twice leaves no row behind. Without +counted+ (enqueue_all) the
650
+ # counts stand, as they always did.
651
+ def settle_counted(counted, jobs, payloads, ambiguous:)
652
+ return unless counted
653
+ return note_counted(counted, jobs, payloads, Array(payloads).each_index.to_a) if ambiguous
654
+
655
+ jobs.each { |job| counted.delete(job) }
656
+ Batch.untrack_enqueue_all(payloads)
657
+ end
658
+
659
+ # The members at +indexes+ stay counted in their batch (their send's
660
+ # outcome is unknown, or it returned their id): a retry sends them
661
+ # without counting them again.
662
+ def note_counted(counted, jobs, payloads, indexes)
663
+ return unless counted
664
+
665
+ indexes.each { |index| counted[jobs[index]] = true if payloads[index][Batch::METADATA_KEY] }
666
+ end
667
+
485
668
  # One guarded increment per batch for the whole bulk, not one per job.
486
669
  # When a later batch refuses (finished), the batches already counted are
487
670
  # uncounted before the error goes up: nothing has been sent yet.
@@ -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