|
| 1 | +require 'securerandom' |
| 2 | +require 'sidekiq' |
| 3 | + |
| 4 | +require 'sidekiq/batch/callback' |
| 5 | +require 'sidekiq/batch/middleware' |
| 6 | +require 'sidekiq/batch/status' |
| 7 | +require 'sidekiq/batch/version' |
| 8 | + |
| 9 | +module Sidekiq |
| 10 | + class Batch |
| 11 | + class NoBlockGivenError < StandardError; end |
| 12 | + |
| 13 | + attr_reader :bid, :description, :callback_queue |
| 14 | + |
| 15 | + def initialize(existing_bid = nil) |
| 16 | + @bid = existing_bid || SecureRandom.urlsafe_base64(10) |
| 17 | + Sidekiq.redis { |r| r.set("#{bid}-to_process", 0) } |
| 18 | + end |
| 19 | + |
| 20 | + def description=(description) |
| 21 | + @description = description |
| 22 | + Sidekiq.redis { |r| r.hset(bid, 'description', description) } |
| 23 | + end |
| 24 | + |
| 25 | + def callback_queue=(callback_queue) |
| 26 | + @callback_queue = callback_queue |
| 27 | + Sidekiq.redis { |r| r.hset(bid, 'callback_queue', callback_queue) } |
| 28 | + end |
| 29 | + |
| 30 | + def on(event, callback, options = {}) |
| 31 | + return unless %w(success complete).include?(event.to_s) |
| 32 | + Sidekiq.redis do |r| |
| 33 | + r.hset(bid, "callback_#{event}", callback) |
| 34 | + r.hset(bid, "callback_#{event}_opts", options.to_json) |
| 35 | + end |
| 36 | + end |
| 37 | + |
| 38 | + def jobs |
| 39 | + raise NoBlockGivenError unless block_given? |
| 40 | + |
| 41 | + Batch.increment_job_queue(bid) |
| 42 | + Thread.current[:bid] = bid |
| 43 | + yield |
| 44 | + Batch.process_successful_job(bid) |
| 45 | + end |
| 46 | + |
| 47 | + class << self |
| 48 | + def process_failed_job(bid, jid) |
| 49 | + to_process = Sidekiq.redis do |r| |
| 50 | + r.multi do |
| 51 | + r.sadd("#{bid}-failed", jid) |
| 52 | + r.scard("#{bid}-failed") |
| 53 | + r.get("#{bid}-to_process") |
| 54 | + end |
| 55 | + end |
| 56 | + if to_process[2].to_i == to_process[1].to_i |
| 57 | + Callback.call_if_needed(:complete, bid) |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + def process_successful_job(bid) |
| 62 | + to_process = Sidekiq.redis do |r| |
| 63 | + r.multi do |
| 64 | + r.decr("#{bid}-to_process") |
| 65 | + r.get("#{bid}-to_process") |
| 66 | + end |
| 67 | + end |
| 68 | + if to_process[1].to_i == 0 |
| 69 | + Callback.call_if_needed(:success, bid) |
| 70 | + Callback.call_if_needed(:complete, bid) |
| 71 | + end |
| 72 | + end |
| 73 | + |
| 74 | + def increment_job_queue(bid) |
| 75 | + Sidekiq.redis { |r| r.incr("#{bid}-to_process") } |
| 76 | + end |
| 77 | + end |
| 78 | + end |
| 79 | +end |
0 commit comments