Skip to content

Commit

Permalink
Optimize traversing middleware chain
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima authored and mperham committed Feb 8, 2023
1 parent 9ef1d41 commit 8e31758
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions lib/sidekiq/middleware/chain.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,23 +166,26 @@ def clear

# Used by Sidekiq to execute the middleware at runtime
# @api private
def invoke(*args)
def invoke(*args, &block)
return yield if empty?

chain = retrieve
traverse_chain = proc do
if chain.empty?
yield
else
chain.shift.call(*args, &traverse_chain)
traverse(chain, 0, args, &block)
end

private

def traverse(chain, index, args, &block)
if index >= chain.size
yield
else
chain[index].call(*args) do
traverse(chain, index + 1, args, &block)
end
end
traverse_chain.call
end
end

private

# Represents each link in the middleware chain
# @api private
class Entry
Expand Down

0 comments on commit 8e31758

Please sign in to comment.