Class: Faraday::HttpCache

Inherits:
Middleware
  • Object
show all
Defined in:
lib/faraday/http_cache.rb,
lib/faraday/http_cache/request.rb,
lib/faraday/http_cache/storage.rb,
lib/faraday/http_cache/version.rb,
lib/faraday/http_cache/response.rb,
lib/faraday/http_cache/memory_store.rb,
lib/faraday/http_cache/cache_control.rb,
lib/faraday/http_cache/strategies/by_url.rb,
lib/faraday/http_cache/strategies/by_vary.rb,
lib/faraday/http_cache/strategies/base_strategy.rb

Overview

Public: The middleware responsible for caching and serving responses. The middleware use the provided configuration options to establish on of ‘Faraday::HttpCache::Strategies’ to cache responses retrieved by the stack adapter. If a stored response can be served again for a subsequent request, the middleware will return the response instead of issuing a new request to it’s server. This middleware should be the last attached handler to your stack, so it will be closest to the inner app, avoiding issues with other middlewares on your stack.

Examples:

# Using the middleware with a simple client:
client = Faraday.new do |builder|
  builder.use :http_cache, store: my_store_backend
  builder.adapter Faraday.default_adapter
end

# Attach a Logger to the middleware.
client = Faraday.new do |builder|
  builder.use :http_cache, logger: my_logger_instance, store: my_store_backend
  builder.adapter Faraday.default_adapter
end

# Provide an existing CacheStore (for instance, from a Rails app)
client = Faraday.new do |builder|
  builder.use :http_cache, store: Rails.cache
end

# Use Marshal for serialization
client = Faraday.new do |builder|
  builder.use :http_cache, store: Rails.cache, serializer: Marshal
end

# Instrument events using ActiveSupport::Notifications
client = Faraday.new do |builder|
  builder.use :http_cache, store: Rails.cache, instrumenter: ActiveSupport::Notifications
end

Defined Under Namespace

Modules: Strategies Classes: CacheControl, MemoryStore, Request, Response, Storage

Constant Summary collapse

UNSAFE_METHODS =
%i[post put delete patch].freeze
ERROR_STATUSES =
(400..499)
EVENT_NAME =

The name of the instrumentation event.

'http_cache.faraday'
CACHE_STATUSES =
[
  # The request was not cacheable.
  :unacceptable,

  # The response was cached and can still be used.
  :fresh,

  # The response was stale but served while revalidating asynchronously.
  :stale,

  # The response was cached and the server has validated it with a 304 response.
  :valid,

  # The response was cached but was not revalidated by the server.
  :invalid,

  # No response was found in the cache.
  :miss,

  # The response can't be cached.
  :uncacheable,

  # The request was cached but need to be revalidated by the server.
  :must_revalidate
].freeze
VERSION =
'2.7.0'

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}, &block) ⇒ HttpCache

Public: Initializes a new HttpCache middleware.

app - the next endpoint on the ‘Faraday’ stack. :store - A cache store that should respond to ‘read’, ‘write’, and ‘delete’. :serializer - A serializer that should respond to ‘dump’ and ‘load’. :shared_cache - A flag to mark the middleware as a shared cache or not. :instrumenter - An instrumentation object that should respond to ‘instrument’. :instrument_name - The String name of the instrument being reported on (optional). :on_stale - A Proc/lambda called with request:, env:, cached_response: when

a stale response is served within stale-while-revalidate window.

:logger - A logger object. :max_entries - The maximum number of entries to store per cache key. This option is only

used when using the +ByUrl+ cache strategy.

Examples:

# Initialize the middleware with a logger.
Faraday::HttpCache.new(app, logger: my_logger)

# Initialize the middleware with a logger and Marshal as a serializer
Faraday::HttpCache.new(app, logger: my_logger, serializer: Marshal)

# Initialize the middleware with a FileStore at the 'tmp' dir.
store = ActiveSupport::Cache.lookup_store(:file_store, ['tmp'])
Faraday::HttpCache.new(app, store: store)

# Initialize the middleware with a MemoryStore and logger
store = ActiveSupport::Cache.lookup_store
Faraday::HttpCache.new(app, store: store, logger: my_logger)


112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/faraday/http_cache.rb', line 112

def initialize(app, options = {}, &block)
  super(app)

  options = options.dup
  @logger = options[:logger]
  @shared_cache = options.delete(:shared_cache) { true }
  @instrumenter = options.delete(:instrumenter)
  @instrument_name = options.delete(:instrument_name) { EVENT_NAME }
  @on_stale = options.delete(:on_stale) || block

  strategy = options.delete(:strategy) { Strategies::ByUrl }

  @strategy = strategy.new(**options)
end

Instance Method Details

#call(env) ⇒ Object

Public: Process the request into a duplicate of this instance to ensure that the internal state is preserved.



129
130
131
# File 'lib/faraday/http_cache.rb', line 129

def call(env)
  dup.call!(env)
end

#call!(env) ⇒ Object

Internal: Process the stack request to try to serve a cache response. On a cacheable request, the middleware will attempt to locate a valid stored response to serve. On a cache miss, the middleware will forward the request and try to store the response for future requests. If the request can’t be cached, the request will be delegated directly to the underlying app and does nothing to the response. The processed steps will be recorded to be logged once the whole process is finished.

Returns a ‘Faraday::Response’ instance.



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/faraday/http_cache.rb', line 143

def call!(env)
  @trace = []
  @request = create_request(env)

  response = nil

  if @request.cacheable?
    response = process(env)
  else
    trace :unacceptable
    response = @app.call(env)
  end

  response.on_complete do
    delete(@request, response) if should_delete?(response.status, @request.method)
    log_request
    response.env[:http_cache_trace] = @trace
    instrument(response.env)
  end
end