Sha256: b6a5414c7dda8710bc85e320e8811f7baf107f53a6a24d20c443ea5615ff9975

Contents?: true

Size: 1.08 KB

Versions: 17

Compression:

Stored size: 1.08 KB

Contents

module Attune
  class CallDropping < Faraday::Middleware
    def initialize app, storage=default_storage
      @app = app
      @storage = storage
    end

    def call env
      raise_timeout if should_skip?
      begin
        result = @app.call(env)
        increment_skips(-SKIP_STEP)
        result
      rescue Faraday::Error::TimeoutError => e
        increment_skips(SKIP_STEP)
        raise e
      end
    end

    private
    # requests to skip before retry
    SKIP_STEP = 0.25

    # The most requests to skip before retrying
    SKIP_MAX = 10.0

    def raise_timeout
      raise Faraday::Error::TimeoutError, "dropped request"
    end

    def should_skip?
      rand > (1.0 / (1.0 + skip_rate))
    end

    def increment_skips amount
      self.skip_rate = skip_rate + amount

      if skip_rate <= 0.0
        self.skip_rate = 0.0
      elsif skip_rate >= SKIP_MAX
        self.skip_rate = SKIP_MAX
      end
    end

    def skip_rate; @storage[:skip_rate] || 0.0; end
    def skip_rate= v; @storage[:skip_rate]= v; end

    def default_storage
      Thread.current
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
attune-1.0.21 lib/attune/call_dropping.rb
attune-1.0.20 lib/attune/call_dropping.rb
attune-1.0.19 lib/attune/call_dropping.rb
attune-1.0.18 lib/attune/call_dropping.rb
attune-1.0.17 lib/attune/call_dropping.rb
attune-1.0.16 lib/attune/call_dropping.rb
attune-1.0.15 lib/attune/call_dropping.rb
attune-1.0.14 lib/attune/call_dropping.rb
attune-1.0.13 lib/attune/call_dropping.rb
attune-1.0.12 lib/attune/call_dropping.rb
attune-1.0.11 lib/attune/call_dropping.rb
attune-1.0.10 lib/attune/call_dropping.rb
attune-1.0.9 lib/attune/call_dropping.rb
attune-1.0.8 lib/attune/call_dropping.rb
attune-1.0.7 lib/attune/call_dropping.rb
attune-1.0.6 lib/attune/call_dropping.rb
attune-1.0.5 lib/attune/call_dropping.rb