Class: ZendeskAPI::Middleware::Request::EtagCache

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/zendesk_api/middleware/request/etag_cache.rb

Overview

Request middleware that caches responses based on etags can be removed once this is merged: https://github.com/pengwynn/faraday_middleware/pull/42

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ EtagCache

Returns a new instance of EtagCache.



10
11
12
13
14
15
16
# File 'lib/zendesk_api/middleware/request/etag_cache.rb', line 10

def initialize(app, options = {})
  @app = app
  @instrumentation = options[:instrumentation] if options[:instrumentation].respond_to?(:instrument)
  @cache = options[:cache] ||
    raise("need :cache option e.g. ActiveSupport::Cache::MemoryStore.new")
  @cache_key_prefix = options.fetch(:cache_key_prefix, :faraday_etags)
end

Instance Method Details

#cache_key(env) ⇒ Object



18
19
20
# File 'lib/zendesk_api/middleware/request/etag_cache.rb', line 18

def cache_key(env)
  [@cache_key_prefix, env[:url].to_s]
end

#call(environment) ⇒ Object



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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/zendesk_api/middleware/request/etag_cache.rb', line 22

def call(environment)
  return @app.call(environment) unless [:get, :head].include?(environment[:method])

  # send known etag
  cached = @cache.read(cache_key(environment))

  if cached
    environment[:request_headers]["If-None-Match"] ||= cached[:response_headers]["Etag"]
  end

  @app.call(environment).on_complete do |env|
    if cached && env[:status] == 304 # not modified
      # Handle differences in serialized env keys in Faraday < 1.0 and 1.0
      # See https://github.com/lostisland/faraday/pull/847
      env[:body] = cached[:body]
      env[:response_body] = cached[:response_body]

      env[:response_headers].merge!(
        etag: cached[:response_headers][:etag],
        content_type: cached[:response_headers][:content_type],
        content_length: cached[:response_headers][:content_length],
        content_encoding: cached[:response_headers][:content_encoding]
      )
      if @instrumentation
        begin
          @instrumentation.instrument("zendesk.cache_hit",
            {
              endpoint: env[:url]&.path,
              status: env[:status]
            })
        rescue
          # Swallow instrumentation errors to maintain cache behavior
        end
      end
    elsif env[:status] == 200 && env[:response_headers]["Etag"] # modified and cacheable
      @cache.write(cache_key(env), env.to_hash)
      if @instrumentation
        begin
          @instrumentation.instrument("zendesk.cache_miss",
            {
              endpoint: env[:url]&.path,
              status: env[:status]
            })
        rescue
          # Swallow instrumentation errors to maintain cache behavior
        end
      end
    end
  end
end