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 21 total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate 22 @drip_factor = (@max_attempts / total_real_attempts).round 23 @state = :closed 24 end
Public Instance methods
respond()
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 26 def respond 27 try_close 28 29 case @state 30 when :closed 31 nil 32 when :half_open 33 @attempts += 1 34 35 # do real requests while drip rate valid 36 if (@real_attempts % @drip_factor).zero? 37 @real_attempts += 1 38 return 39 end 40 41 @response 42 when :open 43 44 @response 45 end 46 end
try_close()
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 76 def try_close 77 case @state 78 when :closed 79 nil 80 when :half_open 81 82 # do not close circuit unless attempts exhausted 83 return unless @attempts >= @max_attempts 84 85 # reset! 86 @attempts = 0 87 @opened_at = @attempted_at = @response = nil 88 @state = :closed 89 90 when :open 91 if Utils.elapsed_time(@opened_at) > @break_in 92 @state = :half_open 93 @attempts = 0 94 @real_attempts = 0 95 end 96 end 97 end
try_open(response)
[show source]
# File lib/httpx/plugins/circuit_breaker/circuit.rb 48 def try_open(response) 49 case @state 50 when :closed 51 now = Utils.now 52 53 if @attempts.positive? 54 # reset if error happened long ago 55 @attempts = 0 if now - @attempted_at > @reset_attempts_in 56 else 57 @attempted_at = now 58 end 59 60 @attempts += 1 61 62 return unless @attempts >= @max_attempts 63 64 @state = :open 65 @opened_at = now 66 @response = response 67 when :half_open 68 # open immediately 69 70 @state = :open 71 @attempted_at = @opened_at = Utils.now 72 @response = response 73 end 74 end