2012-02-08 20:04:19 -05:00
|
|
|
module Sidekiq
|
|
|
|
# Middleware is code configured to run before/after
|
|
|
|
# a message is processed. It is patterned after Rack
|
|
|
|
# middleware. Middleware exists for the client side
|
2012-02-09 23:32:59 -05:00
|
|
|
# (pushing jobs onto the queue) as well as the server
|
|
|
|
# side (when jobs are actually processed).
|
2012-02-08 20:04:19 -05:00
|
|
|
#
|
2012-02-18 15:12:05 -05:00
|
|
|
# To add middleware for the client:
|
2012-02-08 20:04:19 -05:00
|
|
|
#
|
2012-02-18 15:12:05 -05:00
|
|
|
# Sidekiq.client_middleware do |chain|
|
2012-02-18 16:08:53 -05:00
|
|
|
# chain.add MyClientHook
|
2012-02-08 20:04:19 -05:00
|
|
|
# end
|
|
|
|
#
|
2012-02-18 15:12:05 -05:00
|
|
|
# To modify middleware for the server, just call
|
|
|
|
# with another block:
|
2012-02-08 20:04:19 -05:00
|
|
|
#
|
2012-02-18 16:08:53 -05:00
|
|
|
# Sidekiq.server_middleware do |chain|
|
|
|
|
# chain.add MyServerHook
|
2012-02-18 15:12:05 -05:00
|
|
|
# chain.remove ActiveRecord
|
2012-02-08 20:04:19 -05:00
|
|
|
# end
|
|
|
|
#
|
2012-02-18 16:08:53 -05:00
|
|
|
# This is an example of a minimal server middleware:
|
2012-02-08 20:04:19 -05:00
|
|
|
#
|
2012-02-18 15:12:05 -05:00
|
|
|
# class MyServerHook
|
|
|
|
# def call(worker, msg, queue)
|
2012-02-08 20:04:19 -05:00
|
|
|
# puts "Before work"
|
|
|
|
# yield
|
|
|
|
# puts "After work"
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
#
|
2012-02-18 16:08:53 -05:00
|
|
|
# This is an example of a minimal client middleware:
|
|
|
|
#
|
|
|
|
# class MyClientHook
|
|
|
|
# def call(msg, queue)
|
|
|
|
# puts "Before push"
|
|
|
|
# yield
|
|
|
|
# puts "After push"
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
#
|
2012-02-08 20:04:19 -05:00
|
|
|
module Middleware
|
|
|
|
class Chain
|
|
|
|
attr_reader :entries
|
|
|
|
|
|
|
|
def initialize
|
|
|
|
@entries = []
|
|
|
|
end
|
|
|
|
|
2012-02-18 15:12:05 -05:00
|
|
|
def remove(klass)
|
2012-02-08 20:04:19 -05:00
|
|
|
entries.delete_if { |entry| entry.klass == klass }
|
|
|
|
end
|
|
|
|
|
2012-02-18 15:12:05 -05:00
|
|
|
def add(klass, *args)
|
2012-02-10 23:20:01 -05:00
|
|
|
entries << Entry.new(klass, *args) unless exists?(klass)
|
|
|
|
end
|
|
|
|
|
|
|
|
def exists?(klass)
|
|
|
|
entries.any? { |entry| entry.klass == klass }
|
2012-02-08 20:04:19 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def retrieve
|
|
|
|
entries.map(&:make_new)
|
|
|
|
end
|
|
|
|
|
|
|
|
def invoke(*args, &final_action)
|
|
|
|
chain = retrieve.dup
|
|
|
|
traverse_chain = lambda do
|
|
|
|
if chain.empty?
|
|
|
|
final_action.call
|
|
|
|
else
|
|
|
|
chain.shift.call(*args, &traverse_chain)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
traverse_chain.call
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class Entry
|
|
|
|
attr_reader :klass
|
|
|
|
def initialize(klass, *args)
|
|
|
|
@klass = klass
|
|
|
|
@args = args
|
|
|
|
end
|
|
|
|
|
|
|
|
def make_new
|
|
|
|
@klass.new(*@args)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|