A circuit is assigned to a given absoolute url or origin.
It sets max_attempts, the number of attempts the circuit allows, before it is opened. It sets reset_attempts_in, the time a circuit stays open at most, before it resets. It sets break_in, the time that must elapse before an open circuit can transit to the half-open state. It sets circuit_breaker_half_open_drip_rate, the rate of requests a circuit allows to be performed when in an half-open state.
Public Class methods
new(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 14 def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate) 15 @max_attempts = max_attempts 16 @reset_attempts_in = reset_attempts_in 17 @break_in = break_in 18 @circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate 19 @attempts = 0 20 @opened_at = @attempted_at = @response = nil 21 22 total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate 23 @drip_factor = (@max_attempts / total_real_attempts).round 24 @state = :closed 25 end
Public Instance methods
respond()
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 27 def respond 28 try_close 29 30 case @state 31 when :closed 32 nil 33 when :half_open 34 @attempts += 1 35 36 # do real requests while drip rate valid 37 if (@real_attempts % @drip_factor).zero? 38 @real_attempts += 1 39 return 40 end 41 42 @response 43 when :open 44 45 @response 46 end 47 end
try_close()
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 77 def try_close 78 case @state 79 when :closed 80 nil 81 when :half_open 82 83 # do not close circuit unless attempts exhausted 84 return unless @attempts >= @max_attempts 85 86 # reset! 87 @attempts = 0 88 @opened_at = @attempted_at = @response = nil 89 @state = :closed 90 91 when :open 92 if Utils.elapsed_time(@opened_at) > @break_in 93 @state = :half_open 94 @attempts = 0 95 @real_attempts = 0 96 end 97 end 98 end
try_open(response)
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 49 def try_open(response) 50 case @state 51 when :closed 52 now = Utils.now 53 54 if @attempts.positive? 55 # reset if error happened long ago 56 @attempts = 0 if now - @attempted_at > @reset_attempts_in 57 else 58 @attempted_at = now 59 end 60 61 @attempts += 1 62 63 return unless @attempts >= @max_attempts 64 65 @state = :open 66 @opened_at = now 67 @response = response 68 when :half_open 69 # open immediately 70 71 @state = :open 72 @attempted_at = @opened_at = Utils.now 73 @response = response 74 end 75 end