Class: Pgbus::BatchEntry

Inherits:
BusRecord
  • Object
show all
Defined in:
app/models/pgbus/batch_entry.rb

Constant Summary collapse

COUNTER_COLUMNS =
%w[completed_jobs discarded_jobs].freeze

Class Method Summary collapse

Class Method Details

.increment_counter!(batch_id, column) ⇒ Object

Atomically increment the counter and detect if this update caused the batch to finish. Uses row-level locking to prevent duplicate callbacks. Returns { just_finished:, record: } or nil if batch not found.

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/pgbus/batch_entry.rb', line 15

def self.increment_counter!(batch_id, column)
  raise ArgumentError, "Invalid column: #{column}" unless COUNTER_COLUMNS.include?(column)

  transaction do
    record = lock.find_by(batch_id: batch_id)
    return nil unless record

    record.increment!(column)

    just_finished = record.completed_jobs + record.discarded_jobs == record.total_jobs
    record.update!(status: "finished", finished_at: Time.current) if just_finished && record.status != "finished"

    { record: record, just_finished: just_finished && record.status == "finished" }
  end
end