Last active
August 2, 2018 04:05
-
-
Save meetme2meat/9f0e9bf5f54d02ad29820abcd8b15e7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## following is a simple cicruit breaker implementation with thread support. | |
## https://github.com/soundcloud/simple_circuit_breaker/blob/master/lib/simple_circuit_breaker.rb | |
class CircuitBreaker | |
class Error < StandardError | |
end | |
def initialize(retry_timeout=10, threshold=30) | |
@mutex = Mutex.new | |
@retry_timeout = retry_timeout | |
@threshold = threshold | |
reset! | |
end | |
def handle | |
if tripped? | |
raise CircuitBreaker::Error.new('circuit opened') | |
else | |
execute | |
end | |
end | |
def execute | |
result = yield | |
reset! | |
result | |
rescue Exception => exception | |
fail! | |
raise exception | |
end | |
def tripped? | |
opened? && !timeout_exceeded? | |
end | |
def fail! | |
@mutex.synchronize do | |
@failures += 1 | |
if @failures >= @threshold | |
@open_time = Time.now | |
@circuit = :opened | |
end | |
end | |
end | |
def opened? | |
@circuit == :opened | |
end | |
def timeout_exceeded? | |
@open_time + @retry_timeout < Time.now | |
end | |
def reset! | |
@mutex.synchronize do | |
@circuit = :closed | |
@failures = 0 | |
end | |
end | |
end | |
http_circuit_breaker = CircuitBreaker.new | |
http_circuit_breaker.handle { make_http_request } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment