dalli 4.3.12 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -172
  3. data/Gemfile +1 -1
  4. data/README.md +4 -63
  5. data/lib/dalli/client.rb +39 -99
  6. data/lib/dalli/compressor.rb +5 -53
  7. data/lib/dalli/instrumentation.rb +1 -1
  8. data/lib/dalli/key_manager.rb +2 -28
  9. data/lib/dalli/options.rb +2 -2
  10. data/lib/dalli/pipelined_deleter.rb +3 -3
  11. data/lib/dalli/pipelined_getter.rb +31 -52
  12. data/lib/dalli/pipelined_setter.rb +11 -20
  13. data/lib/dalli/protocol/base.rb +32 -176
  14. data/lib/dalli/protocol/connection_manager.rb +20 -143
  15. data/lib/dalli/protocol/meta.rb +16 -55
  16. data/lib/dalli/protocol/{meta/request_formatter.rb → request_formatter.rb} +8 -21
  17. data/lib/dalli/protocol/response_buffer.rb +12 -27
  18. data/lib/dalli/protocol/{meta/response_processor.rb → response_processor.rb} +35 -100
  19. data/lib/dalli/protocol/server_config_parser.rb +1 -1
  20. data/lib/dalli/protocol/string_marshaller.rb +1 -3
  21. data/lib/dalli/protocol/value_compressor.rb +7 -36
  22. data/lib/dalli/protocol/value_marshaller.rb +0 -4
  23. data/lib/dalli/protocol/value_serializer.rb +1 -1
  24. data/lib/dalli/protocol.rb +9 -7
  25. data/lib/dalli/ring.rb +2 -2
  26. data/lib/dalli/servers_arg_normalizer.rb +1 -1
  27. data/lib/dalli/socket.rb +5 -54
  28. data/lib/dalli/version.rb +2 -2
  29. data/lib/dalli.rb +0 -3
  30. data/lib/rack/session/dalli.rb +2 -1
  31. metadata +8 -18
  32. data/lib/dalli/json_serializer.rb +0 -28
  33. data/lib/dalli/protocol/binary/request_formatter.rb +0 -116
  34. data/lib/dalli/protocol/binary/response_header.rb +0 -36
  35. data/lib/dalli/protocol/binary/response_processor.rb +0 -259
  36. data/lib/dalli/protocol/binary/sasl_authentication.rb +0 -60
  37. data/lib/dalli/protocol/binary.rb +0 -202
  38. data/lib/dalli/protocol_deprecations.rb +0 -45
  39. /data/lib/dalli/protocol/{meta/key_regularizer.rb → key_regularizer.rb} +0 -0
@@ -1,259 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Dalli
4
- module Protocol
5
- class Binary
6
- ##
7
- # Class that encapsulates logic for processing binary protocol responses
8
- # from memcached. Includes logic for pulling data from an IO source
9
- # and parsing into local values. Handles errors on unexpected values.
10
- ##
11
- class ResponseProcessor
12
- MAX_STATS_ENTRIES = 10_000
13
- MAX_QUIET_RESPONSES = 100_000
14
- # Response codes taken from:
15
- # https://github.com/memcached/memcached/wiki/BinaryProtocolRevamped#response-status
16
- RESPONSE_CODES = {
17
- 0 => 'No error',
18
- 1 => 'Key not found',
19
- 2 => 'Key exists',
20
- 3 => 'Value too large',
21
- 4 => 'Invalid arguments',
22
- 5 => 'Item not stored',
23
- 6 => 'Incr/decr on a non-numeric value',
24
- 7 => 'The vbucket belongs to another server',
25
- 8 => 'Authentication error',
26
- 9 => 'Authentication continue',
27
- 0x20 => 'Authentication required',
28
- 0x81 => 'Unknown command',
29
- 0x82 => 'Out of memory',
30
- 0x83 => 'Not supported',
31
- 0x84 => 'Internal error',
32
- 0x85 => 'Busy',
33
- 0x86 => 'Temporary failure'
34
- }.freeze
35
-
36
- def initialize(io_source, value_marshaller)
37
- @io_source = io_source
38
- @value_marshaller = value_marshaller
39
- end
40
-
41
- def read(num_bytes)
42
- @io_source.read(num_bytes)
43
- end
44
-
45
- def read_response
46
- resp_header = ResponseHeader.new(read_header)
47
- check_body_size!(resp_header)
48
- body = read(resp_header.body_len) if resp_header.body_len.positive?
49
- [resp_header, body]
50
- end
51
-
52
- def unpack_response_body(resp_header, body, parse_as_stored_value)
53
- extra_len = resp_header.extra_len
54
- key_len = resp_header.key_len
55
- bitflags = extra_len.positive? ? body.unpack1('N') : 0x0
56
- key = body.byteslice(extra_len, key_len).force_encoding(Encoding::UTF_8) if key_len.positive?
57
- value = body.byteslice((extra_len + key_len)..-1)
58
- value = @value_marshaller.retrieve(value, bitflags) if parse_as_stored_value
59
- [key, value]
60
- end
61
-
62
- def read_header
63
- read(ResponseHeader::SIZE) || raise(Dalli::NetworkError, 'No response')
64
- end
65
-
66
- def raise_on_not_ok!(resp_header)
67
- return if resp_header.ok?
68
-
69
- raise Dalli::DalliError, "Response error #{resp_header.status}: #{RESPONSE_CODES[resp_header.status]}"
70
- end
71
-
72
- # raw: true returns the value as stored, without deserializing or
73
- # decompressing it, whatever flags it was stored with
74
- def get(cache_nils: false, raw: false)
75
- resp_header, body = read_response
76
-
77
- return false if resp_header.not_stored? # Not stored, normal status for add operation
78
- return cache_nils ? ::Dalli::NOT_FOUND : nil if resp_header.not_found?
79
-
80
- raise_on_not_ok!(resp_header)
81
- return true unless body
82
-
83
- unpack_response_body(resp_header, body, !raw).last
84
- end
85
-
86
- ##
87
- # Response for a storage operation. Returns the cas on success. False
88
- # if the value wasn't stored. And raises an error on all other error
89
- # codes from memcached.
90
- ##
91
- def storage_response
92
- resp_header, = read_response
93
- return nil if resp_header.not_found?
94
- return false if resp_header.not_stored? # Not stored, normal status for add operation
95
-
96
- raise_on_not_ok!(resp_header)
97
- resp_header.cas
98
- end
99
-
100
- def delete
101
- resp_header, = read_response
102
- return false if resp_header.not_found? || resp_header.not_stored?
103
-
104
- raise_on_not_ok!(resp_header)
105
- true
106
- end
107
-
108
- # raw: true returns the value as stored; see #get
109
- def data_cas_response(raw: false)
110
- resp_header, body = read_response
111
- return [nil, resp_header.cas] if resp_header.not_found?
112
- return [nil, false] if resp_header.not_stored?
113
-
114
- raise_on_not_ok!(resp_header)
115
- return [nil, resp_header.cas] unless body
116
-
117
- [unpack_response_body(resp_header, body, !raw).last, resp_header.cas]
118
- end
119
-
120
- # Returns the new value for the key, if found and updated
121
- def decr_incr
122
- body = generic_response
123
- body ? body.unpack1('Q>') : body
124
- end
125
-
126
- def stats
127
- hash = {}
128
- replies = 0
129
- loop do
130
- resp_header, body = read_response
131
- # This is the response to the terminating noop / end of stat
132
- return hash if resp_header.ok? && resp_header.key_len.zero?
133
-
134
- replies += 1
135
- raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
136
-
137
- # Ignore any responses with non-zero status codes,
138
- # such as errors from set operations. That allows
139
- # this code to be used at the end of a multi
140
- # block to clear any error responses from inside the multi.
141
- next unless resp_header.ok?
142
-
143
- key, value = unpack_response_body(resp_header, body, true)
144
- hash[key] = value
145
- end
146
- end
147
-
148
- def flush
149
- no_body_response
150
- end
151
-
152
- def reset
153
- generic_response
154
- end
155
-
156
- def version
157
- generic_response
158
- end
159
-
160
- def consume_all_responses_until_noop(max_responses = MAX_QUIET_RESPONSES)
161
- replies = 0
162
- loop do
163
- resp_header, = read_response
164
- # This is the response to the terminating noop / end of stat
165
- return true if resp_header.ok? && resp_header.key_len.zero?
166
-
167
- replies += 1
168
- raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
169
- end
170
- end
171
-
172
- def generic_response
173
- resp_header, body = read_response
174
-
175
- return false if resp_header.not_stored? # Not stored, normal status for add operation
176
- return nil if resp_header.not_found?
177
-
178
- raise_on_not_ok!(resp_header)
179
- return true unless body
180
-
181
- unpack_response_body(resp_header, body, false).last
182
- end
183
-
184
- def no_body_response
185
- resp_header, = read_response
186
- return false if resp_header.not_stored? # Not stored, possible status for append/prepend/delete
187
-
188
- raise_on_not_ok!(resp_header)
189
- true
190
- end
191
-
192
- def validate_auth_format(extra_len, count)
193
- return if extra_len.zero?
194
-
195
- raise Dalli::NetworkError, "Unexpected message format: #{extra_len} #{count}"
196
- end
197
-
198
- def auth_response(buf = read_header)
199
- resp_header = ResponseHeader.new(buf)
200
- body_len = resp_header.body_len
201
- validate_auth_format(resp_header.extra_len, body_len)
202
- check_body_size!(resp_header)
203
- content = read(body_len) if body_len.positive?
204
- [resp_header.status, content]
205
- end
206
-
207
- ##
208
- # This method returns an array of values used in a pipelined
209
- # getk process. The first value is the number of bytes by
210
- # which to advance the pointer in the buffer. If the
211
- # complete response is found in the buffer, this will
212
- # be the response size. Otherwise it is zero.
213
- #
214
- # The remaining three values in the array are the ResponseHeader,
215
- # key, and value.
216
- ##
217
- # memcached can't store an item larger than 1 GiB (its -I maximum). A
218
- # pipelined reply claiming an impossible size would otherwise have the
219
- # buffer wait for (and accumulate) that many bytes.
220
- MAX_BODY_BYTES = 1024 * 1024 * 1024
221
-
222
- def check_body_size!(header)
223
- size = header.body_len
224
- value_size = size - header.extra_len - header.key_len
225
- limit = [MAX_BODY_BYTES, @value_marshaller.max_response_bytes].min
226
- return if size <= MAX_BODY_BYTES && value_size.between?(0, limit)
227
-
228
- raise Dalli::DalliError, "Reply body size #{size} is out of range"
229
- end
230
-
231
- def getk_response_from_buffer(buf, offset = 0)
232
- # There's no header in the buffer, so don't advance
233
- return [0, nil, nil, nil, nil] unless buf && buf.bytesize >= offset + ResponseHeader::SIZE
234
-
235
- resp_header = ResponseHeader.new(buf.byteslice(offset, ResponseHeader::SIZE))
236
- body_len = resp_header.body_len
237
- check_body_size!(resp_header)
238
-
239
- # We have a complete response that has no body.
240
- # This is either the response to the terminating
241
- # noop or, if the status is not zero, an intermediate
242
- # error response that needs to be discarded.
243
- return [ResponseHeader::SIZE, resp_header.ok?, resp_header.cas, nil, nil] if body_len.zero?
244
-
245
- resp_size = ResponseHeader::SIZE + body_len
246
- # The header is in the buffer, but the body is not. As we don't have
247
- # a complete response, don't advance the buffer
248
- return [0, nil, nil, nil, nil] unless buf.bytesize >= offset + resp_size
249
-
250
- # The full response is in our buffer, so parse it and return
251
- # the values
252
- body = buf.byteslice(offset + ResponseHeader::SIZE, body_len)
253
- key, value = unpack_response_body(resp_header, body, true)
254
- [resp_size, resp_header.ok?, resp_header.cas, key, value]
255
- end
256
- end
257
- end
258
- end
259
- end
@@ -1,60 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Dalli
4
- module Protocol
5
- class Binary
6
- ##
7
- # Code to support SASL authentication
8
- ##
9
- module SaslAuthentication
10
- def perform_auth_negotiation
11
- write(RequestFormatter.standard_request(opkey: :auth_negotiation))
12
-
13
- status, content = response_processor.auth_response
14
- return [status, []] if content.nil?
15
-
16
- # Substitute spaces for the \x00 returned by
17
- # memcached as a separator for easier
18
- content&.tr!("\u0000", ' ')
19
- mechanisms = content&.split
20
- [status, mechanisms]
21
- end
22
-
23
- PLAIN_AUTH = 'PLAIN'
24
-
25
- def supported_mechanisms!(mechanisms)
26
- unless mechanisms.include?(PLAIN_AUTH)
27
- raise NotImplementedError,
28
- 'Dalli only supports the PLAIN authentication mechanism'
29
- end
30
- [PLAIN_AUTH]
31
- end
32
-
33
- def authenticate_with_plain
34
- write(RequestFormatter.standard_request(opkey: :auth_request,
35
- key: PLAIN_AUTH,
36
- value: "\x0#{username}\x0#{password}"))
37
- @response_processor.auth_response
38
- end
39
-
40
- def authenticate_connection
41
- Dalli.logger.info { "Dalli/SASL authenticating as #{username}" }
42
-
43
- status, mechanisms = perform_auth_negotiation
44
- return Dalli.logger.debug('Authentication not required/supported by server') if status == 0x81
45
-
46
- supported_mechanisms!(mechanisms)
47
- status, content = authenticate_with_plain
48
-
49
- return Dalli.logger.info("Dalli/SASL: #{content}") if status.zero?
50
-
51
- raise Dalli::DalliError, "Error authenticating: 0x#{status.to_s(16)}" unless status == 0x21
52
-
53
- raise NotImplementedError, 'No two-step authentication mechanisms supported'
54
- # (step, msg) = sasl.receive('challenge', content)
55
- # raise Dalli::NetworkError, "Authentication failed" if sasl.failed? || step != 'response'
56
- end
57
- end
58
- end
59
- end
60
- end
@@ -1,202 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'forwardable'
4
- require 'socket'
5
- require 'timeout'
6
-
7
- module Dalli
8
- module Protocol
9
- ##
10
- # Access point for a single Memcached server, accessed via Memcached's binary
11
- # protocol. Contains logic for managing connection state to the server (retries, etc),
12
- # formatting requests to the server, and unpacking responses.
13
- ##
14
- class Binary < Base
15
- def response_processor
16
- @response_processor ||= ResponseProcessor.new(@connection_manager, @value_marshaller)
17
- end
18
-
19
- private
20
-
21
- # Retrieval Commands
22
- def get(key, options = nil)
23
- req = RequestFormatter.standard_request(opkey: :get, key: key)
24
- write(req)
25
- @connection_manager.flush
26
- response_processor.get(cache_nils: cache_nils?(options), raw: raw_request?(options))
27
- end
28
-
29
- def quiet_get_request(key)
30
- RequestFormatter.standard_request(opkey: :getkq, key: key)
31
- end
32
-
33
- def gat(key, ttl, options = nil)
34
- ttl = TtlSanitizer.sanitize(ttl)
35
- req = RequestFormatter.standard_request(opkey: :gat, key: key, ttl: ttl)
36
- write(req)
37
- @connection_manager.flush
38
- response_processor.get(cache_nils: cache_nils?(options), raw: raw_request?(options))
39
- end
40
-
41
- def touch(key, ttl)
42
- ttl = TtlSanitizer.sanitize(ttl)
43
- write(RequestFormatter.standard_request(opkey: :touch, key: key, ttl: ttl))
44
- @connection_manager.flush
45
- response_processor.generic_response
46
- end
47
-
48
- # TODO: This is confusing, as there's a cas command in memcached
49
- # and this isn't it. Maybe rename? Maybe eliminate?
50
- def cas(key, options = nil)
51
- req = RequestFormatter.standard_request(opkey: :get, key: key)
52
- write(req)
53
- @connection_manager.flush
54
- response_processor.data_cas_response(raw: raw_request?(options))
55
- end
56
-
57
- # Storage Commands
58
- def set(key, value, ttl, cas, options)
59
- opkey = quiet? ? :setq : :set
60
- storage_req(opkey, key, value, ttl, cas, options)
61
- end
62
-
63
- # Pipelined set - writes a quiet set request without reading response.
64
- # Used by PipelinedSetter for bulk operations.
65
- def pipelined_set(key, value, ttl, options)
66
- storage_req(:setq, key, value, ttl, 0, options, quiet: true)
67
- end
68
-
69
- def add(key, value, ttl, options)
70
- opkey = quiet? ? :addq : :add
71
- storage_req(opkey, key, value, ttl, 0, options)
72
- end
73
-
74
- def replace(key, value, ttl, cas, options)
75
- opkey = quiet? ? :replaceq : :replace
76
- storage_req(opkey, key, value, ttl, cas, options)
77
- end
78
-
79
- # rubocop:disable-next Metrics/ParameterLists
80
- def storage_req(opkey, key, value, ttl, cas, options, quiet: quiet?)
81
- (value, bitflags) = @value_marshaller.store(key, value, options)
82
- ttl = TtlSanitizer.sanitize(ttl)
83
-
84
- req = RequestFormatter.standard_request(opkey: opkey, key: key,
85
- value: value, bitflags: bitflags,
86
- ttl: ttl, cas: cas)
87
- write(req)
88
- @connection_manager.flush unless quiet
89
- response_processor.storage_response unless quiet
90
- end
91
-
92
- def append(key, value)
93
- opkey = quiet? ? :appendq : :append
94
- write_append_prepend opkey, key, value
95
- end
96
-
97
- def prepend(key, value)
98
- opkey = quiet? ? :prependq : :prepend
99
- write_append_prepend opkey, key, value
100
- end
101
-
102
- def write_append_prepend(opkey, key, value)
103
- write(RequestFormatter.standard_request(opkey: opkey, key: key, value: value))
104
- @connection_manager.flush unless quiet?
105
- response_processor.no_body_response unless quiet?
106
- end
107
-
108
- # Delete Commands
109
- def delete(key, cas)
110
- opkey = quiet? ? :deleteq : :delete
111
- req = RequestFormatter.standard_request(opkey: opkey, key: key, cas: cas)
112
- write(req)
113
- @connection_manager.flush unless quiet?
114
- response_processor.delete unless quiet?
115
- end
116
-
117
- # Pipelined delete - writes a quiet delete request without reading response.
118
- # Used by PipelinedDeleter for bulk operations.
119
- def pipelined_delete(key)
120
- req = RequestFormatter.standard_request(opkey: :deleteq, key: key, cas: 0)
121
- write(req)
122
- end
123
-
124
- # Arithmetic Commands
125
- def decr(key, count, ttl, initial)
126
- opkey = quiet? ? :decrq : :decr
127
- decr_incr opkey, key, count, ttl, initial
128
- end
129
-
130
- def incr(key, count, ttl, initial)
131
- opkey = quiet? ? :incrq : :incr
132
- decr_incr opkey, key, count, ttl, initial
133
- end
134
-
135
- # This allows us to special case a nil initial value, and
136
- # handle it differently than a zero. This special value
137
- # for expiry causes memcached to return a not found
138
- # if the key doesn't already exist, rather than
139
- # setting the initial value
140
- NOT_FOUND_EXPIRY = 0xFFFFFFFF
141
- private_constant :NOT_FOUND_EXPIRY
142
-
143
- def decr_incr(opkey, key, count, ttl, initial)
144
- expiry = initial ? TtlSanitizer.sanitize(ttl) : NOT_FOUND_EXPIRY
145
- initial ||= 0
146
- write(RequestFormatter.decr_incr_request(opkey: opkey, key: key,
147
- count: count, initial: initial, expiry: expiry))
148
- @connection_manager.flush unless quiet?
149
- response_processor.decr_incr unless quiet?
150
- end
151
-
152
- # Other Commands
153
- def flush(ttl = 0)
154
- opkey = quiet? ? :flushq : :flush
155
- write(RequestFormatter.standard_request(opkey: opkey, ttl: ttl))
156
- @connection_manager.flush unless quiet?
157
- response_processor.no_body_response unless quiet?
158
- end
159
-
160
- # Noop is a keepalive operation but also used to demarcate the end of a set of pipelined commands.
161
- # We need to read all the responses at once.
162
- def noop(max_responses = ResponseProcessor::MAX_QUIET_RESPONSES)
163
- write_noop
164
- result = response_processor.consume_all_responses_until_noop(max_responses)
165
- # Everything up to and including the noop reply has been read
166
- @connection_manager.clear_quiet_responses_pending!
167
- result
168
- end
169
-
170
- def stats(info = '')
171
- req = RequestFormatter.standard_request(opkey: :stat, key: info)
172
- write(req)
173
- @connection_manager.flush
174
- response_processor.stats
175
- end
176
-
177
- def reset_stats
178
- write(RequestFormatter.standard_request(opkey: :stat, key: 'reset'))
179
- @connection_manager.flush
180
- response_processor.reset
181
- end
182
-
183
- def version
184
- write(RequestFormatter.standard_request(opkey: :version))
185
- @connection_manager.flush
186
- response_processor.version
187
- end
188
-
189
- def write_noop
190
- req = RequestFormatter.standard_request(opkey: :noop)
191
- write(req)
192
- @connection_manager.flush
193
- end
194
-
195
- require_relative 'binary/request_formatter'
196
- require_relative 'binary/response_header'
197
- require_relative 'binary/response_processor'
198
- require_relative 'binary/sasl_authentication'
199
- include SaslAuthentication
200
- end
201
- end
202
- end
@@ -1,45 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Dalli
4
- ##
5
- # Handles deprecation warnings for protocol and authentication features
6
- # that will be removed in Dalli 5.0.
7
- ##
8
- module ProtocolDeprecations
9
- BINARY_PROTOCOL_DEPRECATION_MESSAGE = <<~MSG.chomp
10
- [DEPRECATION] The binary protocol is deprecated and will be removed in Dalli 5.0. \
11
- Please use `protocol: :meta` instead. The meta protocol requires memcached 1.6+. \
12
- See https://github.com/petergoldstein/dalli for migration details.
13
- MSG
14
-
15
- SASL_AUTH_DEPRECATION_MESSAGE = <<~MSG.chomp
16
- [DEPRECATION] SASL authentication is deprecated and will be removed in Dalli 5.0. \
17
- SASL is only supported by the binary protocol, which is being removed. \
18
- Consider using network-level security (firewall rules, VPN) or memcached's TLS support instead.
19
- MSG
20
-
21
- private
22
-
23
- def emit_deprecation_warnings
24
- emit_binary_protocol_deprecation_warning
25
- emit_sasl_auth_deprecation_warning
26
- end
27
-
28
- def emit_binary_protocol_deprecation_warning
29
- protocol = @options[:protocol]
30
- # Binary is used when protocol is nil, :binary, or 'binary'
31
- return if protocol.to_s == 'meta'
32
-
33
- warn BINARY_PROTOCOL_DEPRECATION_MESSAGE
34
- Dalli.logger.warn(BINARY_PROTOCOL_DEPRECATION_MESSAGE)
35
- end
36
-
37
- def emit_sasl_auth_deprecation_warning
38
- username = @options[:username] || ENV.fetch('MEMCACHE_USERNAME', nil)
39
- return unless username
40
-
41
- warn SASL_AUTH_DEPRECATION_MESSAGE
42
- Dalli.logger.warn(SASL_AUTH_DEPRECATION_MESSAGE)
43
- end
44
- end
45
- end