|
| 1 | +class BatchProcessor < ApplicationRecord |
| 2 | + validates :batch_key, presence: true, uniqueness: true |
| 3 | + validates :job_class, presence: true |
| 4 | + validates :pending_count, presence: true, numericality: { greater_than_or_euqal_to: 0 } |
| 5 | + |
| 6 | + # Generic batching configuration |
| 7 | + DEFAULT_BATCH_SIZE = 100 |
| 8 | + DEFAULT_BATCH_WINDOW_IN_SECONDS = 30.seconds |
| 9 | + |
| 10 | + # JSON serialization for SQLite compatibility |
| 11 | + def shared_args |
| 12 | + JSON.parse(shared_args_json || "{}") |
| 13 | + end |
| 14 | + |
| 15 | + def shared_args=(value) |
| 16 | + self.shared_args_json = value.to_json |
| 17 | + end |
| 18 | + |
| 19 | + def pending_items |
| 20 | + JSON.parse(pending_items_json || "[]") |
| 21 | + end |
| 22 | + |
| 23 | + def pending_items=(value) |
| 24 | + self.pending_items_json = value.to_json |
| 25 | + end |
| 26 | + |
| 27 | + def self.add_to_batch(batch_key, job_class, item_data, shared_args = {}, batch_size: DEFAULT_BATCH_SIZE, batch_window: DEFAULT_BATCH_WINDOW_IN_SECONDS) |
| 28 | + batch = find_or_create_by(batch_key: batch_key) do |b| |
| 29 | + b.job_class = job_class |
| 30 | + b.shared_args = shared_args |
| 31 | + b.pending_items = [] |
| 32 | + b.pending_count = 0 |
| 33 | + b.batch_size = batch_size |
| 34 | + b.batch_window_in_seconds = batch_window.to_i |
| 35 | + b.last_processed_at = Time.current |
| 36 | + end |
| 37 | + |
| 38 | + current_items = batch.pending_items |
| 39 | + current_items << item_data |
| 40 | + batch.pending_items = current_items |
| 41 | + batch.pending_count = current_items.size |
| 42 | + batch.save! |
| 43 | + |
| 44 | + # Trigger processing ONLY if the batch is full |
| 45 | + if batch.pending_count >= batch.batch_size |
| 46 | + process_batch(batch) |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + def self.process_pending_batches |
| 51 | + where("pending_count > 0") |
| 52 | + .find_each do |batch| |
| 53 | + if batch.last_processed_at < batch.batch_window_in_seconds.seconds.ago |
| 54 | + process_batch(batch) |
| 55 | + end |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + private |
| 60 | + def self.should_process_batch?(batch) |
| 61 | + batch.pending_count >= batch.batch_size || batch.last_processed_at < batch.batch_window_in_seconds.seconds.ago |
| 62 | + end |
| 63 | + |
| 64 | + def self.process_batch(batch) |
| 65 | + return if batch.pending_items.blank? |
| 66 | + |
| 67 | + job_class = batch.job_class.constantize |
| 68 | + job_class.perform_later(batch.pending_items, **batch.shared_args.symbolize_keys) |
| 69 | + |
| 70 | + batch.update!( |
| 71 | + pending_items: [], |
| 72 | + pending_count: 0, |
| 73 | + last_processed_at: Time.current |
| 74 | + ) |
| 75 | + end |
| 76 | +end |
0 commit comments