2012-01-21 19:42:21 -05:00
require 'multi_json'
2012-02-08 20:04:02 -05:00
require 'sidekiq/middleware/chain'
require 'sidekiq/middleware/client/unique_jobs'
2012-01-21 19:42:21 -05:00
module Sidekiq
class Client
2012-02-10 23:20:01 -05:00
2012-02-19 16:02:32 -05:00
def self . default_middleware
Middleware :: Chain . new do | m |
end
end
2012-02-15 14:28:19 -05:00
def self . registered_workers
2012-03-14 12:56:13 -04:00
Sidekiq . redis { | x | x . smembers ( 'workers' ) }
2012-02-15 14:28:19 -05:00
end
def self . registered_queues
2012-03-14 12:56:13 -04:00
Sidekiq . redis { | x | x . smembers ( 'queues' ) }
2012-02-15 14:28:19 -05:00
end
2012-04-01 22:53:45 -04:00
# DEPRECATED
2012-02-15 14:28:19 -05:00
def self . queue_mappings
@queue_mappings || = { }
2012-02-07 06:29:09 -05:00
end
2012-01-21 19:42:21 -05:00
# Example usage:
2012-04-01 22:53:45 -04:00
# Sidekiq::Client.push('queue' => 'my_queue', 'class' => MyWorker, 'args' => ['foo', 1, :bat => 'bar'])
def self . push ( item )
raise ( ArgumentError , " Message must be a Hash of the form: { 'class' => SomeWorker, 'args' => ['bob', 1, :foo => 'bar'] } " ) unless item . is_a? ( Hash )
2012-01-23 15:56:49 -05:00
raise ( ArgumentError , " Message must include a class and set of arguments: #{ item . inspect } " ) if ! item [ 'class' ] || ! item [ 'args' ]
2012-04-01 22:53:45 -04:00
raise ( ArgumentError , " Message must include a Sidekiq::Worker class, not class name: #{ item [ 'class' ] . ancestors . inspect } " ) if ! item [ 'class' ] . is_a? ( Class ) || ! item [ 'class' ] . respond_to? ( 'get_sidekiq_options' )
2012-01-21 19:42:21 -05:00
2012-04-01 22:53:45 -04:00
item [ 'retry' ] = ! ! item [ 'class' ] . get_sidekiq_options [ 'retry' ]
queue = item [ 'queue' ] || item [ 'class' ] . get_sidekiq_options [ 'queue' ] || queue_mappings [ item [ 'class' ] . to_s ] || 'default'
worker_class = item [ 'class' ]
item [ 'class' ] = item [ 'class' ] . to_s
2012-02-10 23:20:01 -05:00
pushed = false
2012-04-01 22:53:45 -04:00
Sidekiq . client_middleware . invoke ( worker_class , item , queue ) do
2012-04-18 17:57:24 -04:00
payload = MultiJson . encode ( item )
2012-03-14 12:56:13 -04:00
Sidekiq . redis do | conn |
2012-04-11 16:17:44 -04:00
_ , pushed = conn . multi do
2012-03-10 16:07:19 -05:00
conn . sadd ( 'queues' , queue )
conn . rpush ( " queue: #{ queue } " , payload )
end
end
2012-02-07 06:29:09 -05:00
end
2012-04-11 16:17:44 -04:00
! ! pushed
2012-01-21 19:42:21 -05:00
end
2012-04-01 22:53:45 -04:00
# Redis compatibility helper. Example usage:
2012-01-21 19:42:21 -05:00
#
# Sidekiq::Client.enqueue(MyWorker, 'foo', 1, :bat => 'bar')
#
2012-02-09 23:32:59 -05:00
# Messages are enqueued to the 'default' queue.
2012-01-21 19:42:21 -05:00
#
def self . enqueue ( klass , * args )
2012-04-01 22:53:45 -04:00
push ( 'class' = > klass , 'args' = > args )
2012-01-21 19:42:21 -05:00
end
end
end