Skip to content

Commit

Permalink
Make request_allowed? thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
byroot committed Aug 10, 2016
1 parent 27d0175 commit 3f96882
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
14 changes: 8 additions & 6 deletions lib/semian/circuit_breaker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module Semian
class CircuitBreaker #:nodoc:
extend Forwardable

def_delegators :@state, :closed?, :open?, :half_open?

def initialize(name, exceptions:, success_threshold:, error_threshold:, error_timeout:, implementation:)
@name = name.to_sym
@success_count_threshold = success_threshold
Expand All @@ -15,6 +17,8 @@ def initialize(name, exceptions:, success_threshold:, error_threshold:, error_ti
end

def acquire
half_open if open? && error_timeout_expired?

raise OpenCircuitError unless request_allowed?

result = nil
Expand All @@ -30,9 +34,10 @@ def acquire
end

def request_allowed?
return true if closed?
half_open if error_timeout_expired?
!open?
closed? ||
half_open? ||
# The circuit breaker is officially open, but it will transition to half-open on the next attempt.
(open? && error_timeout_expired?)
end

def mark_failed(_error)
Expand Down Expand Up @@ -64,9 +69,6 @@ def destroy

private

def_delegators :@state, :closed?, :open?, :half_open?
private :closed?, :open?, :half_open?

def close
log_state_transition(:closed)
@state.close
Expand Down
3 changes: 2 additions & 1 deletion lib/semian/protected_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ class ProtectedResource
extend Forwardable

def_delegators :@resource, :destroy, :count, :semid, :tickets, :name
def_delegators :@circuit_breaker, :reset, :mark_failed, :mark_success, :request_allowed?
def_delegators :@circuit_breaker, :reset, :mark_failed, :mark_success, :request_allowed?,
:open?, :closed?, :half_open?

def initialize(resource, circuit_breaker)
@resource = resource
Expand Down
12 changes: 12 additions & 0 deletions test/circuit_breaker_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,18 @@ def test_sparse_errors_dont_open_circuit
Semian.destroy(:three)
end

def test_request_allowed_query_doesnt_trigger_transitions
Timecop.travel(Time.now - 6) do
open_circuit!

refute_predicate @resource, :request_allowed?
assert_predicate @resource, :open?
end

assert_predicate @resource, :request_allowed?
assert_predicate @resource, :open?
end

private

def open_circuit!(resource = @resource)
Expand Down

0 comments on commit 3f96882

Please sign in to comment.