dalli 3.2.17 → 4.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.
@@ -9,8 +9,6 @@ module Dalli
9
9
  # and parsing into local values. Handles errors on unexpected values.
10
10
  ##
11
11
  class ResponseProcessor
12
- MAX_STATS_ENTRIES = 10_000
13
- MAX_QUIET_RESPONSES = 100_000
14
12
  # Response codes taken from:
15
13
  # https://github.com/memcached/memcached/wiki/BinaryProtocolRevamped#response-status
16
14
  RESPONSE_CODES = {
@@ -44,7 +42,6 @@ module Dalli
44
42
 
45
43
  def read_response
46
44
  resp_header = ResponseHeader.new(read_header)
47
- check_body_size!(resp_header)
48
45
  body = read(resp_header.body_len) if resp_header.body_len.positive?
49
46
  [resp_header, body]
50
47
  end
@@ -69,9 +66,7 @@ module Dalli
69
66
  raise Dalli::DalliError, "Response error #{resp_header.status}: #{RESPONSE_CODES[resp_header.status]}"
70
67
  end
71
68
 
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)
69
+ def get(cache_nils: false)
75
70
  resp_header, body = read_response
76
71
 
77
72
  return false if resp_header.not_stored? # Not stored, normal status for add operation
@@ -80,7 +75,7 @@ module Dalli
80
75
  raise_on_not_ok!(resp_header)
81
76
  return true unless body
82
77
 
83
- unpack_response_body(resp_header, body, !raw).last
78
+ unpack_response_body(resp_header, body, true).last
84
79
  end
85
80
 
86
81
  ##
@@ -105,8 +100,7 @@ module Dalli
105
100
  true
106
101
  end
107
102
 
108
- # raw: true returns the value as stored; see #get
109
- def data_cas_response(raw: false)
103
+ def data_cas_response
110
104
  resp_header, body = read_response
111
105
  return [nil, resp_header.cas] if resp_header.not_found?
112
106
  return [nil, false] if resp_header.not_stored?
@@ -114,7 +108,7 @@ module Dalli
114
108
  raise_on_not_ok!(resp_header)
115
109
  return [nil, resp_header.cas] unless body
116
110
 
117
- [unpack_response_body(resp_header, body, !raw).last, resp_header.cas]
111
+ [unpack_response_body(resp_header, body, true).last, resp_header.cas]
118
112
  end
119
113
 
120
114
  # Returns the new value for the key, if found and updated
@@ -123,17 +117,13 @@ module Dalli
123
117
  body ? body.unpack1('Q>') : body
124
118
  end
125
119
 
126
- def stats # rubocop:disable Metrics/MethodLength
120
+ def stats
127
121
  hash = {}
128
- replies = 0
129
122
  loop do
130
123
  resp_header, body = read_response
131
124
  # This is the response to the terminating noop / end of stat
132
125
  return hash if resp_header.ok? && resp_header.key_len.zero?
133
126
 
134
- replies += 1
135
- raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
136
-
137
127
  # Ignore any responses with non-zero status codes,
138
128
  # such as errors from set operations. That allows
139
129
  # this code to be used at the end of a multi
@@ -157,15 +147,11 @@ module Dalli
157
147
  generic_response
158
148
  end
159
149
 
160
- def consume_all_responses_until_noop(max_responses = MAX_QUIET_RESPONSES)
161
- replies = 0
150
+ def consume_all_responses_until_noop
162
151
  loop do
163
152
  resp_header, = read_response
164
153
  # This is the response to the terminating noop / end of stat
165
154
  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
155
  end
170
156
  end
171
157
 
@@ -199,7 +185,6 @@ module Dalli
199
185
  resp_header = ResponseHeader.new(buf)
200
186
  body_len = resp_header.body_len
201
187
  validate_auth_format(resp_header.extra_len, body_len)
202
- check_body_size!(resp_header)
203
188
  content = read(body_len) if body_len.positive?
204
189
  [resp_header.status, content]
205
190
  end
@@ -224,27 +209,12 @@ module Dalli
224
209
  # The remaining three values in the array are the ResponseHeader,
225
210
  # key, and value.
226
211
  ##
227
- # memcached can't store an item larger than 1 GiB (its -I maximum). A
228
- # pipelined reply claiming an impossible size would otherwise have the
229
- # buffer wait for (and accumulate) that many bytes.
230
- MAX_BODY_BYTES = 1024 * 1024 * 1024
231
-
232
- def check_body_size!(header)
233
- size = header.body_len
234
- value_size = size - header.extra_len - header.key_len
235
- limit = [MAX_BODY_BYTES, @value_marshaller.max_response_bytes].min
236
- return if size <= MAX_BODY_BYTES && value_size.between?(0, limit)
237
-
238
- raise Dalli::DalliError, "Reply body size #{size} is out of range"
239
- end
240
-
241
212
  def getk_response_from_buffer(buf)
242
213
  # There's no header in the buffer, so don't advance
243
214
  return [0, nil, nil, nil, nil] unless contains_header?(buf)
244
215
 
245
216
  resp_header = response_header_from_buffer(buf)
246
217
  body_len = resp_header.body_len
247
- check_body_size!(resp_header)
248
218
 
249
219
  # We have a complete response that has no body.
250
220
  # This is either the response to the terminating
@@ -22,7 +22,7 @@ module Dalli
22
22
  def get(key, options = nil)
23
23
  req = RequestFormatter.standard_request(opkey: :get, key: key)
24
24
  write(req)
25
- response_processor.get(cache_nils: cache_nils?(options), raw: raw_request?(options))
25
+ response_processor.get(cache_nils: cache_nils?(options))
26
26
  end
27
27
 
28
28
  def quiet_get_request(key)
@@ -33,7 +33,7 @@ module Dalli
33
33
  ttl = TtlSanitizer.sanitize(ttl)
34
34
  req = RequestFormatter.standard_request(opkey: :gat, key: key, ttl: ttl)
35
35
  write(req)
36
- response_processor.get(cache_nils: cache_nils?(options), raw: raw_request?(options))
36
+ response_processor.get(cache_nils: cache_nils?(options))
37
37
  end
38
38
 
39
39
  def touch(key, ttl)
@@ -44,10 +44,10 @@ module Dalli
44
44
 
45
45
  # TODO: This is confusing, as there's a cas command in memcached
46
46
  # and this isn't it. Maybe rename? Maybe eliminate?
47
- def cas(key, options = nil)
47
+ def cas(key)
48
48
  req = RequestFormatter.standard_request(opkey: :get, key: key)
49
49
  write(req)
50
- response_processor.data_cas_response(raw: raw_request?(options))
50
+ response_processor.data_cas_response
51
51
  end
52
52
 
53
53
  # Storage Commands
@@ -119,6 +119,7 @@ module Dalli
119
119
  # if the key doesn't already exist, rather than
120
120
  # setting the initial value
121
121
  NOT_FOUND_EXPIRY = 0xFFFFFFFF
122
+ private_constant :NOT_FOUND_EXPIRY
122
123
 
123
124
  def decr_incr(opkey, key, count, ttl, initial)
124
125
  expiry = initial ? TtlSanitizer.sanitize(ttl) : NOT_FOUND_EXPIRY
@@ -139,10 +140,7 @@ module Dalli
139
140
  # We need to read all the responses at once.
140
141
  def noop
141
142
  write_noop
142
- result = response_processor.consume_all_responses_until_noop
143
- # Everything up to and including the noop reply has been read
144
- @connection_manager.quiet_responses_pending = false
145
- result
143
+ response_processor.consume_all_responses_until_noop
146
144
  end
147
145
 
148
146
  def stats(info = '')
@@ -12,7 +12,7 @@ module Dalli
12
12
  # Manages the socket connection to the server, including ensuring liveness
13
13
  # and retries.
14
14
  ##
15
- class ConnectionManager # rubocop:disable Metrics/ClassLength
15
+ class ConnectionManager
16
16
  DEFAULTS = {
17
17
  # seconds between trying to contact a remote server
18
18
  down_retry_delay: 30,
@@ -28,7 +28,6 @@ module Dalli
28
28
 
29
29
  attr_accessor :hostname, :port, :socket_type, :options
30
30
  attr_reader :sock
31
- attr_writer :quiet_responses_pending
32
31
 
33
32
  def initialize(hostname, port, socket_type, client_options)
34
33
  @hostname = hostname
@@ -36,11 +35,9 @@ module Dalli
36
35
  @socket_type = socket_type
37
36
  @options = DEFAULTS.merge(client_options)
38
37
  @request_in_progress = false
39
- @quiet_responses_pending = false
40
38
  @sock = nil
41
39
  @pid = nil
42
40
 
43
- @fail_count = 0
44
41
  reset_down_info
45
42
  end
46
43
 
@@ -56,11 +53,10 @@ module Dalli
56
53
  Dalli.logger.debug { "Dalli::Server#connect #{name}" }
57
54
 
58
55
  @sock = memcached_socket
59
- @pid = Process.pid
56
+ @pid = PIDCache.pid
60
57
  @request_in_progress = false
61
- @quiet_responses_pending = false
62
- rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError, SocketError => e
63
- # SocketError = DNS resolution failure; SSL_ERRORS = failed TLS handshake
58
+ rescue SystemCallError, *TIMEOUT_ERRORS, EOFError, SocketError => e
59
+ # SocketError = DNS resolution failure
64
60
  error_on_request!(e)
65
61
  end
66
62
 
@@ -88,8 +84,6 @@ module Dalli
88
84
  def down!
89
85
  close
90
86
  log_down_detected
91
- # Once down_retry_delay passes, the server gets a full set of attempts
92
- @fail_count = 0
93
87
 
94
88
  @error = $ERROR_INFO&.class&.name
95
89
  @msg ||= $ERROR_INFO&.message
@@ -106,47 +100,32 @@ module Dalli
106
100
 
107
101
  def confirm_ready!
108
102
  close if request_in_progress?
109
- close_on_fork if fork_detected?
103
+ reconnect_on_fork if fork_detected?
110
104
  end
111
105
 
112
106
  def confirm_in_progress!
113
107
  raise '[Dalli] No request in progress. This may be a bug in Dalli.' unless request_in_progress?
114
108
 
115
- close_on_fork if fork_detected?
109
+ reconnect_on_fork if fork_detected?
116
110
  end
117
111
 
118
112
  def close
119
113
  return unless @sock
120
114
 
121
115
  begin
122
- close_socket
116
+ @sock.close
123
117
  rescue StandardError
124
118
  nil
125
119
  end
126
120
  @sock = nil
127
121
  @pid = nil
128
- @quiet_responses_pending = false
129
122
  abort_request!
130
123
  end
131
124
 
132
- # A forked child shares the parent's connection, so it closes only its
133
- # own file descriptor. Closing the TLS socket itself would send
134
- # close_notify and end the parent's TLS session.
135
- def close_socket
136
- fork_detected? ? @sock.to_io.close : @sock.close
137
- end
138
-
139
125
  def connected?
140
126
  !@sock.nil?
141
127
  end
142
128
 
143
- # True when a quiet request was written on this connection and its
144
- # replies (memcached only suppresses some of them) haven't been
145
- # consumed by a noop yet.
146
- def quiet_responses_pending?
147
- @quiet_responses_pending
148
- end
149
-
150
129
  def request_in_progress?
151
130
  @request_in_progress
152
131
  end
@@ -161,57 +140,28 @@ module Dalli
161
140
  raise '[Dalli] No request in progress. This may be a bug in Dalli.' unless @request_in_progress
162
141
 
163
142
  @request_in_progress = false
164
- # A completed request is what proves the server healthy again, so the
165
- # failure count resets here rather than on reconnect: a server that
166
- # accepts connections but never answers would otherwise reset it on
167
- # every retry and never reach socket_max_failures.
168
- @fail_count = 0
169
143
  end
170
144
 
171
145
  def abort_request!
172
146
  @request_in_progress = false
173
147
  end
174
148
 
175
- # The longest reply line Dalli reads, in bytes, CRLF included. A meta
176
- # reply header is at most about 500 bytes: "VA <size>" plus its flags,
177
- # the largest being a 250-byte key base64-encoded to 336 bytes, a
178
- # 20-digit CAS, a 32-byte opaque and a few numeric fields. The longest
179
- # stats line (stats settings) carries a file path such as ext_path, up
180
- # to PATH_MAX (4096). 8 KiB leaves room for both, while a server that
181
- # never sends CRLF can't grow the read buffer without bound.
182
- MAX_LINE_BYTES = 8 * 1024
183
-
184
149
  def read_line
185
- data = with_tls_timeout { @sock.gets("\r\n", MAX_LINE_BYTES) }
150
+ data = @sock.gets("\r\n")
186
151
  error_on_request!('EOF in read_line') if data.nil?
187
- # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
188
- # short by EOF; either way the connection is out of step
189
- error_on_request!("Reply line without CRLF in the first #{MAX_LINE_BYTES} bytes") unless data.end_with?("\r\n")
190
152
  data
191
153
  rescue SystemCallError, *TIMEOUT_ERRORS, EOFError => e
192
154
  error_on_request!(e)
193
155
  end
194
156
 
195
- # memcached can't store an item larger than 1 GiB (its -I maximum), so a
196
- # reply claiming more (or a negative size) is malformed or hostile.
197
- # Reading allocates the full count up front, so check before reading.
198
- MAX_READ_BYTES = (1024 * 1024 * 1024) + 2 # plus the value's trailing "\r\n"
199
-
200
- def check_read_size!(count)
201
- return if count.between?(0, MAX_READ_BYTES)
202
-
203
- raise Dalli::DalliError, "Reply size #{count} from #{name} is out of range"
204
- end
205
-
206
157
  def read(count)
207
- check_read_size!(count)
208
- with_tls_timeout { @sock.readfull(count) }
158
+ @sock.readfull(count)
209
159
  rescue SystemCallError, *TIMEOUT_ERRORS, EOFError => e
210
160
  error_on_request!(e)
211
161
  end
212
162
 
213
163
  def write(bytes)
214
- with_tls_timeout { @sock.write(bytes) }
164
+ @sock.write(bytes)
215
165
  rescue SystemCallError, *TIMEOUT_ERRORS => e
216
166
  error_on_request!(e)
217
167
  end
@@ -222,12 +172,6 @@ module Dalli
222
172
  @sock.read_available
223
173
  end
224
174
 
225
- def with_tls_timeout
226
- return yield unless @sock.is_a?(Dalli::Socket::SSLSocket)
227
-
228
- Timeout.timeout(socket_timeout) { yield } # rubocop:disable Style/ExplicitBlockArgument
229
- end
230
-
231
175
  def max_allowed_failures
232
176
  @max_allowed_failures ||= @options[:socket_max_failures] || 2
233
177
  end
@@ -251,9 +195,8 @@ module Dalli
251
195
  raise Dalli::NetworkError, message
252
196
  end
253
197
 
254
- # Called on connect. Deliberately leaves @fail_count alone; see
255
- # finish_request!.
256
198
  def reset_down_info
199
+ @fail_count = 0
257
200
  @down_at = nil
258
201
  @last_down_at = nil
259
202
  @msg = nil
@@ -269,28 +212,22 @@ module Dalli
269
212
  end
270
213
 
271
214
  def log_warn_message(err_or_string)
272
- detail = err_or_string.is_a?(String) ? err_or_string : "#{err_or_string.class}: #{err_or_string.message}"
273
215
  Dalli.logger.warn do
274
216
  detail = err_or_string.is_a?(String) ? err_or_string : "#{err_or_string.class}: #{err_or_string.message}"
275
217
  "#{name} failed (count: #{@fail_count}) #{detail}"
276
218
  end
277
219
  end
278
220
 
279
- def close_on_fork
221
+ def reconnect_on_fork
280
222
  message = 'Fork detected, re-connecting child process...'
281
223
  Dalli.logger.info { message }
282
- # Closes the inherited socket without touching the parent's
283
- # connection, setting us up for reconnect on next request.
224
+ # Close socket on a fork and reconnect immediately
284
225
  close
285
- raise Dalli::NetworkError, message
226
+ establish_connection
286
227
  end
287
228
 
288
229
  def fork_detected?
289
- # Process.pid rather than PIDCache: PIDCache is refreshed by a
290
- # Process._fork hook, and another library's fork hook (such as
291
- # connection_pool closing its connections) can run in the child before
292
- # it, which would close the parent's TLS session as if it were ours.
293
- @pid && @pid != Process.pid
230
+ @pid && @pid != PIDCache.pid
294
231
  end
295
232
 
296
233
  def log_down_detected
@@ -10,7 +10,7 @@ module Dalli
10
10
  # memcached supports the use of base64 hashes for keys containing
11
11
  # whitespace or non-ASCII characters, provided the 'b' flag is included in the request.
12
12
  class KeyRegularizer
13
- WHITESPACE = /\s/.freeze
13
+ WHITESPACE = /\s/
14
14
 
15
15
  def self.encode(key)
16
16
  return [key, false] if key.ascii_only? && !WHITESPACE.match(key)
@@ -13,7 +13,6 @@ module Dalli
13
13
  # and introducing an intermediate object seems like overkill.
14
14
  #
15
15
  # rubocop:disable Metrics/CyclomaticComplexity
16
- # rubocop:disable Metrics/MethodLength
17
16
  # rubocop:disable Metrics/ParameterLists
18
17
  # rubocop:disable Metrics/PerceivedComplexity
19
18
  def self.meta_get(key:, value: true, return_cas: false, ttl: nil, base64: false, quiet: false)
@@ -21,7 +20,7 @@ module Dalli
21
20
  cmd << ' v f' if value
22
21
  cmd << ' c' if return_cas
23
22
  cmd << ' b' if base64
24
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
23
+ cmd << " T#{ttl}" if ttl
25
24
  cmd << ' k q s' if quiet # Return the key in the response if quiet
26
25
  cmd + TERMINATOR
27
26
  end
@@ -32,19 +31,17 @@ module Dalli
32
31
  cmd << ' b' if base64
33
32
  cmd << " F#{bitflags}" if bitflags
34
33
  cmd << cas_string(cas)
35
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
34
+ cmd << " T#{ttl}" if ttl
36
35
  cmd << " M#{mode_to_token(mode)}"
37
36
  cmd << ' q' if quiet
38
37
  cmd << TERMINATOR
39
- cmd << value
40
- cmd + TERMINATOR
41
38
  end
42
39
 
43
40
  def self.meta_delete(key:, cas: nil, ttl: nil, base64: false, quiet: false)
44
41
  cmd = "md #{key}"
45
42
  cmd << ' b' if base64
46
43
  cmd << cas_string(cas)
47
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
44
+ cmd << " T#{ttl}" if ttl
48
45
  cmd << ' q' if quiet
49
46
  cmd + TERMINATOR
50
47
  end
@@ -52,17 +49,16 @@ module Dalli
52
49
  def self.meta_arithmetic(key:, delta:, initial:, incr: true, cas: nil, ttl: nil, base64: false, quiet: false)
53
50
  cmd = "ma #{key} v"
54
51
  cmd << ' b' if base64
55
- cmd << " D#{integer_flag(:delta, delta)}" if delta
56
- cmd << " J#{integer_flag(:initial, initial)}" if initial
52
+ cmd << " D#{delta}" if delta
53
+ cmd << " J#{initial}" if initial
57
54
  # Always set a TTL if an initial value is specified
58
- cmd << " N#{ttl ? integer_flag(:ttl, ttl) : 0}" if ttl || initial
55
+ cmd << " N#{ttl || 0}" if ttl || initial
59
56
  cmd << cas_string(cas)
60
57
  cmd << ' q' if quiet
61
58
  cmd << " M#{incr ? 'I' : 'D'}"
62
59
  cmd + TERMINATOR
63
60
  end
64
61
  # rubocop:enable Metrics/CyclomaticComplexity
65
- # rubocop:enable Metrics/MethodLength
66
62
  # rubocop:enable Metrics/ParameterLists
67
63
  # rubocop:enable Metrics/PerceivedComplexity
68
64
 
@@ -81,13 +77,16 @@ module Dalli
81
77
  cmd + TERMINATOR
82
78
  end
83
79
 
80
+ ALLOWED_STATS_ARGS = [nil, '', 'items', 'slabs', 'settings', 'reset'].freeze
81
+
84
82
  def self.stats(arg = nil)
83
+ raise ArgumentError, "Invalid stats argument: #{arg.inspect}" unless ALLOWED_STATS_ARGS.include?(arg)
84
+
85
85
  cmd = +'stats'
86
- cmd << " #{arg}" if arg
86
+ cmd << " #{arg}" if arg && !arg.empty?
87
87
  cmd + TERMINATOR
88
88
  end
89
89
 
90
- # rubocop:disable Metrics/MethodLength
91
90
  def self.mode_to_token(mode)
92
91
  case mode
93
92
  when :add
@@ -102,19 +101,6 @@ module Dalli
102
101
  'S'
103
102
  end
104
103
  end
105
- # rubocop:enable Metrics/MethodLength
106
-
107
- # Numeric flag values are written straight into the command line, so a
108
- # value that isn't an integer -- e.g. a String carrying CRLF -- would let
109
- # the caller inject further memcached commands (GHSA-6wmv-xq9m-fmp7).
110
- # Converting to Integer means only digits ever reach the wire. Strings
111
- # are parsed as base 10 so "010" means 10, as memcached would read it,
112
- # rather than octal 8.
113
- def self.integer_flag(name, value)
114
- value.is_a?(String) ? Integer(value, 10) : Integer(value)
115
- rescue ArgumentError, TypeError, FloatDomainError
116
- raise ArgumentError, "#{name} must be an Integer, got #{value.inspect}"
117
- end
118
104
 
119
105
  def self.cas_string(cas)
120
106
  cas = parse_to_64_bit_int(cas, nil)