lib/httpx/plugins/response_cache/store.rb in httpx-0.23.4 vs lib/httpx/plugins/response_cache/store.rb in httpx-0.24.0

- old
+ new

@@ -1,44 +1,37 @@ # frozen_string_literal: true -require "forwardable" +require "mutex_m" module HTTPX::Plugins module ResponseCache class Store - extend Forwardable - - def_delegator :@store, :clear - def initialize @store = {} + @store.extend(Mutex_m) end + def clear + @store.synchronize { @store.clear } + end + def lookup(request) - responses = @store[request.response_cache_key] + responses = _get(request) return unless responses - response = responses.find(&method(:match_by_vary?).curry(2)[request]) - - return unless response && response.fresh? - - response + responses.find(&method(:match_by_vary?).curry(2)[request]) end def cached?(request) lookup(request) end def cache(request, response) return unless ResponseCache.cacheable_request?(request) && ResponseCache.cacheable_response?(response) - responses = (@store[request.response_cache_key] ||= []) - - responses.reject!(&method(:match_by_vary?).curry(2)[request]) - - responses << response + _set(request, response) end def prepare(request) cached_response = lookup(request) @@ -67,9 +60,35 @@ return request.headers.same_headers?(original_request.headers) if vary == %w[*] vary.all? do |cache_field| cache_field.downcase! !original_request.headers.key?(cache_field) || request.headers[cache_field] == original_request.headers[cache_field] + end + end + + def _get(request) + @store.synchronize do + responses = @store[request.response_cache_key] + + return unless responses + + responses.select! do |res| + !res.body.closed? && res.fresh? + end + + responses + end + end + + def _set(request, response) + @store.synchronize do + responses = (@store[request.response_cache_key] ||= []) + + responses.reject! do |res| + res.body.closed? || !res.fresh? || match_by_vary?(request, res) + end + + responses << response end end end end end