Class: Circuitbox::FaradayMiddleware
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Circuitbox::FaradayMiddleware
- Defined in:
- lib/circuitbox/faraday_middleware.rb
Defined Under Namespace
Classes: NullResponse, RequestFailed
Constant Summary collapse
- DEFAULT_OPTIONS =
{ open_circuit: lambda do |response| # response.status: # nil -> connection could not be established, or failed very hard # 5xx -> non recoverable server error, opposed to 4xx which are client errors response.status.nil? || (response.status >= 500 && response.status <= 599) end, default_value: ->(service_response, exception) { NullResponse.new(service_response, exception) }, # It's possible for the URL object to not have a host at the time the middleware # is run. To not break circuitbox by creating a circuit with a nil service name # we can get the string representation of the URL object and use that as the service name. identifier: ->(env) { env[:url].host || env[:url].to_s }, # default circuit breaker options are merged in during initialization circuit_breaker_options: {} }.freeze
- DEFAULT_EXCEPTIONS =
[ Faraday::TimeoutError, RequestFailed ].freeze
- DEFAULT_CIRCUIT_BREAKER_OPTIONS =
{ exceptions: DEFAULT_EXCEPTIONS }.freeze
Instance Method Summary collapse
- #call(request_env) ⇒ Object
-
#initialize(app, opts = {}) ⇒ FaradayMiddleware
constructor
A new instance of FaradayMiddleware.
Constructor Details
#initialize(app, opts = {}) ⇒ FaradayMiddleware
Returns a new instance of FaradayMiddleware.
45 46 47 48 49 50 51 |
# File 'lib/circuitbox/faraday_middleware.rb', line 45 def initialize(app, opts = {}) @app = app @opts = DEFAULT_OPTIONS.merge(opts) @opts[:circuit_breaker_options] = DEFAULT_CIRCUIT_BREAKER_OPTIONS.merge(@opts[:circuit_breaker_options]) super(app) end |
Instance Method Details
#call(request_env) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/circuitbox/faraday_middleware.rb', line 53 def call(request_env) service_response = nil circuit(request_env).run do @app.call(request_env).on_complete do |env| service_response = Faraday::Response.new(env) raise RequestFailed if open_circuit?(service_response) end end rescue Circuitbox::Error => e circuit_open_value(request_env, service_response, e) end |