Skip to content

Instantly share code, notes, and snippets.

@meetme2meat
Last active August 2, 2018 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meetme2meat/9f0e9bf5f54d02ad29820abcd8b15e7d to your computer and use it in GitHub Desktop.
Save meetme2meat/9f0e9bf5f54d02ad29820abcd8b15e7d to your computer and use it in GitHub Desktop.
## 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