yammer / circuitbox

Circuit breaker built with large Ruby apps in mind.
Other
704 stars 59 forks source link

Use explicit block for Ruby 3 compatibility #189

Closed hank-spokeo closed 1 year ago

hank-spokeo commented 1 year ago

Explicitly passing the block in the run and run! methods fixed tried to create Proc object without a block (ArgumentError) on Ruby 3

Fixes https://github.com/yammer/circuitbox/issues/185

This PR is 1 commit ahead of tag v1.1.1, but I had to open the PR against main since there isn't a 1.x branch

Here's the fix as a Rails monkey patch File: config/initializers/circuitbox.rb

# Circuitbox monkey patch created from
# https://github.com/yammer/circuitbox/tree/v1.1.1
#
# Explicitly passing the block in the `run` and `run!` methods fixed
# `ArgumentError: tried to create Proc object without a block` on Ruby 3
module FixCircuitboxRuby3
  def run!(run_options = {}, &block)
    @partition = run_options.delete(:partition) # sorry for this hack.

    if open?
      logger.debug "[CIRCUIT] open: skipping #{service}"
      open! unless open_flag?
      skipped!
      raise Circuitbox::OpenCircuitError.new(service)
    else
      close! if was_open?
      logger.debug "[CIRCUIT] closed: querying #{service}"

      begin
        response = if exceptions.include? Timeout::Error
          timeout_seconds = run_options.fetch(:timeout_seconds) { option_value(:timeout_seconds) }
          timeout (timeout_seconds) { block.call }
        else
          block.call
        end

        logger.debug "[CIRCUIT] closed: #{service} querie success"
        success!
      rescue *exceptions => exception
        logger.debug "[CIRCUIT] closed: detected #{service} failure"
        failure!
        open! if half_open?
        raise Circuitbox::ServiceFailureError.new(service, exception)
      end
    end

    return response
  end

  def run(run_options = {}, &block)
    begin
      run!(run_options, &block)
    rescue Circuitbox::Error
      nil
    end
  end
end
Circuitbox::CircuitBreaker.prepend(FixCircuitboxRuby3)
matthewshafer commented 1 year ago

Closing, fixed in 2.0.0