Skip to content

Commit

Permalink
Initial implementation - missing status
Browse files Browse the repository at this point in the history
  • Loading branch information
nglx committed Aug 22, 2016
0 parents commit 3cdd369
Show file tree
Hide file tree
Showing 20 changed files with 527 additions and 0 deletions.
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/.bundle/
/.yardoc
/Gemfile.lock
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
dump.rdb
2 changes: 2 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
--format documentation
--color
5 changes: 5 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
sudo: false
language: ruby
rvm:
- 2.3.1
before_install: gem install bundler -v 1.12.5
4 changes: 4 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
source 'https://rubygems.org'

# Specify your gem's dependencies in sidekiq-batch.gemspec
gemspec
4 changes: 4 additions & 0 deletions Guardfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
guard 'rspec', cmd: 'rspec --color' do
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r|^spec/(.*)_spec\.rb|)
end
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Breamware

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Sidekiq::Batch

Simple Sidekiq Batch Job implementation.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'sidekiq-batch'
```

And then execute:

$ bundle

Or install it yourself as:

$ gem install sidekiq-batch

## Usage

Sidekiq Batch is drop-in replacement for the API from Sidekiq PRO. See https://github.com/mperham/sidekiq/wiki/Batches for usage.

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/breamware/sidekiq-batch.


## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
6 changes: 6 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

task :default => :spec
79 changes: 79 additions & 0 deletions lib/sidekiq/batch.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
require 'securerandom'
require 'sidekiq'

require 'sidekiq/batch/callback'
require 'sidekiq/batch/middleware'
require 'sidekiq/batch/status'
require 'sidekiq/batch/version'

module Sidekiq
class Batch
class NoBlockGivenError < StandardError; end

attr_reader :bid, :description, :callback_queue

def initialize(existing_bid = nil)
@bid = existing_bid || SecureRandom.urlsafe_base64(10)
Sidekiq.redis { |r| r.set("#{bid}-to_process", 0) }
end

def description=(description)
@description = description
Sidekiq.redis { |r| r.hset(bid, 'description', description) }
end

def callback_queue=(callback_queue)
@callback_queue = callback_queue
Sidekiq.redis { |r| r.hset(bid, 'callback_queue', callback_queue) }
end

def on(event, callback, options = {})
return unless %w(success complete).include?(event.to_s)
Sidekiq.redis do |r|
r.hset(bid, "callback_#{event}", callback)
r.hset(bid, "callback_#{event}_opts", options.to_json)
end
end

def jobs
raise NoBlockGivenError unless block_given?

Batch.increment_job_queue(bid)
Thread.current[:bid] = bid
yield
Batch.process_successful_job(bid)
end

class << self
def process_failed_job(bid, jid)
to_process = Sidekiq.redis do |r|
r.multi do
r.sadd("#{bid}-failed", jid)
r.scard("#{bid}-failed")
r.get("#{bid}-to_process")
end
end
if to_process[2].to_i == to_process[1].to_i
Callback.call_if_needed(:complete, bid)
end
end

def process_successful_job(bid)
to_process = Sidekiq.redis do |r|
r.multi do
r.decr("#{bid}-to_process")
r.get("#{bid}-to_process")
end
end
if to_process[1].to_i == 0
Callback.call_if_needed(:success, bid)
Callback.call_if_needed(:complete, bid)
end
end

def increment_job_queue(bid)
Sidekiq.redis { |r| r.incr("#{bid}-to_process") }
end
end
end
end
40 changes: 40 additions & 0 deletions lib/sidekiq/batch/callback.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
module Sidekiq
class Batch
module Callback
class Worker
include Sidekiq::Worker

def perform(clazz, event, opts, bid)
return unless %w(success complete).include?(event)
instance = clazz.constantize.send(:new) rescue nil
return unless instance
instance.send("on_#{event}", Status.new(bid), opts) rescue nil
end
end

class << self
def call_if_needed(event, bid)
needed = Sidekiq.redis do |r|
r.multi do
r.hget(bid, event)
r.hset(bid, event, true)
end
end
return if 'true' == needed[0]
callback, opts, queue = Sidekiq.redis do |r|
r.hmget(bid,
"callback_#{event}", "callback_#{event}_opts",
'callback_queue')
end
return unless callback
opts = JSON.parse(opts) if opts
opts ||= {}
queue ||= 'default'
Sidekiq::Client.push('class' => Sidekiq::Batch::Callback::Worker,
'args' => [callback, event, opts, bid],
'queue' => queue)
end
end
end
end
end
51 changes: 51 additions & 0 deletions lib/sidekiq/batch/middleware.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
module Sidekiq
class Batch
module Middleware
def self.extended(base)
base.class_eval do
register_middleware
end
end

def register_middleware
Sidekiq.configure_server do |config|
config.client_middleware do |chain|
chain.add ClientMiddleware
end
config.server_middleware do |chain|
chain.add ClientMiddleware
chain.add ServerMiddleware
end
end
end

class ClientMiddleware
def call(_worker, msg, _queue, _redis_pool = nil)
if (bid = Thread.current[:bid])
Batch.increment_job_queue(bid) if
msg[:bid] = bid
end
yield
end
end

class ServerMiddleware
def call(_worker, msg, _queue)
if (bid = msg['bid'])
begin
yield
Batch.process_successful_job(bid)
rescue
Batch.process_failed_job(bid, msg['jid'])
raise
end
else
yield
end
end
end
end
end
end

Sidekiq::Batch::Middleware.send(:extend, Sidekiq::Batch::Middleware)
34 changes: 34 additions & 0 deletions lib/sidekiq/batch/status.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module Sidekiq
class Batch
class Status
attr_reader :bid, :total, :failures, :created_at, :failure_info

def initialize(bid)
@bid = bid
end

def join
raise "Not supported"
end

def pending
Sidekiq.redis { |r| r.get("#{bid}-to_process") }.to_i
end

def complete?
'true' == Sidekiq.redis { |r| r.hget(bid, 'complete') }
end

def data
{
total: total,
failures: failures,
pending: pending,
created_at: created_at,
complete: complete?,
failure_info: failure_info
}
end
end
end
end
5 changes: 5 additions & 0 deletions lib/sidekiq/batch/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module Sidekiq
class Batch
VERSION = '0.1.0.pre'.freeze
end
end
27 changes: 27 additions & 0 deletions sidekiq-batch.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'sidekiq/batch/version'

Gem::Specification.new do |spec|
spec.name = "sidekiq-batch"
spec.version = Sidekiq::Batch::VERSION
spec.authors = ["Marcin Naglik"]
spec.email = ["[email protected]"]

spec.summary = "Sidekiq Batch Jobs"
spec.description = "Sidekiq Batch Jobs Implementation"
spec.homepage = "http://github.com/breamware/sidekiq-batch"
spec.license = "MIT"

spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]

spec.add_dependency "sidekiq", "~> 4"

spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
31 changes: 31 additions & 0 deletions spec/integration/integration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
require 'sidekiq/batch'

class TestWorker
include Sidekiq::Worker

def perform
end
end

class MyCallback
def on_success(status, options)
puts "Success #{options} #{status.data}"
end

def on_complete(status, options)
puts "Complete #{options} #{status.data}"
end
end

batch = Sidekiq::Batch.new
batch.description = 'Test batch'
batch.callback_queue = :default
batch.on(:success, MyCallback, to: '[email protected]')
batch.on(:complete, MyCallback, to: '[email protected]')

batch.jobs do
10.times do
TestWorker.perform_async
end
end
puts Sidekiq::Batch::Status.new(batch.bid).data
Loading

0 comments on commit 3cdd369

Please sign in to comment.