File: dalli_proxy.rb

package info (click to toggle)
ruby-rack-attack 6.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 380 kB
  • sloc: ruby: 2,626; makefile: 4
file content (78 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# frozen_string_literal: true

require 'rack/attack/base_proxy'

module Rack
  class Attack
    module StoreProxy
      class DalliProxy < BaseProxy
        def self.handle?(store)
          return false unless defined?(::Dalli)

          # Consider extracting to a separate Connection Pool proxy to reduce
          # code here and handle clients other than Dalli.
          if defined?(::ConnectionPool) && store.is_a?(::ConnectionPool)
            store.with { |conn| conn.is_a?(::Dalli::Client) }
          else
            store.is_a?(::Dalli::Client)
          end
        end

        def initialize(client)
          super(client)
          stub_with_if_missing
        end

        def read(key)
          rescuing do
            with do |client|
              client.get(key)
            end
          end
        end

        def write(key, value, options = {})
          rescuing do
            with do |client|
              client.set(key, value, options.fetch(:expires_in, 0), raw: true)
            end
          end
        end

        def increment(key, amount, options = {})
          rescuing do
            with do |client|
              client.incr(key, amount, options.fetch(:expires_in, 0), amount)
            end
          end
        end

        def delete(key)
          rescuing do
            with do |client|
              client.delete(key)
            end
          end
        end

        private

        def stub_with_if_missing
          unless __getobj__.respond_to?(:with)
            class << self
              def with
                yield __getobj__
              end
            end
          end
        end

        def rescuing
          yield
        rescue Dalli::DalliError
          nil
        end
      end
    end
  end
end