Class: FaradayDynamicTimeout::Middleware

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/faraday_dynamic_timeout/middleware.rb

Instance Method Summary collapse

Constructor Details

#initializeMiddleware

Returns a new instance of Middleware.



5
6
7
8
9
10
11
12
13
14
# File 'lib/faraday_dynamic_timeout/middleware.rb', line 5

def initialize(*)
  super

  @redis_client = option(:redis)
  if @redis_client.nil? && !(options.include?(:redis) || options.include?("redis"))
    @redis_client = Redis.new
  end

  @memoized_buckets = []
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/faraday_dynamic_timeout/middleware.rb', line 16

def call(env)
  # A Redis outage must never take down HTTP traffic, so if building the bucket
  # configuration touches Redis (e.g. a capacity based strategy) and it is
  # unavailable, fail open and let the request through with no dynamic timeout.
  buckets = safe_redis { sorted_buckets }
  redis = redis_client
  return app.call(env) if !enabled?(env) || buckets.nil? || buckets.empty? || redis.nil?

  error = nil
  bucket_timeout = nil
  callback = option(:callback)
  start_time = monotonic_time if callback

  count_request(env.url, redis, buckets, callback) do |request_count|
    execute_with_timeout(env.url, buckets, request_count, redis) do |timeout|
      bucket_timeout = timeout
      set_timeout(env, timeout) if timeout

      # Resetting the start time to more accurately reflect the time spent in the request.
      start_time = monotonic_time if callback
      app.call(env)
    end
  rescue => e
    error = e
    raise
  ensure
    if callback
      duration = monotonic_time - start_time
      request_info = RequestInfo.new(env: env, duration: duration, timeout: bucket_timeout, request_count: request_count, error: error)
      callback.call(request_info)
    end
  end
end