dalli 5.2.10 → 5.3.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.
@@ -43,10 +43,10 @@ module Dalli
43
43
  # This saves 2 bytes per request and skips parsing on response.
44
44
  cmd << (skip_flags ? ' v' : ' v f') if value
45
45
  cmd << ' c' if return_cas
46
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
46
+ cmd << " T#{ttl_flag(:ttl, ttl)}" if ttl
47
47
  cmd << routing_tokens(p_token: p_token, l_token: l_token)
48
48
  cmd << ' k q s' if quiet # Return the key in the response if quiet
49
- cmd << " N#{integer_flag(:vivify_ttl, vivify_ttl)}" if vivify_ttl # Thundering herd: vivify on miss
49
+ cmd << " N#{ttl_flag(:vivify_ttl, vivify_ttl)}" if vivify_ttl # Thundering herd: vivify on miss
50
50
  # Thundering herd: win recache if TTL below threshold
51
51
  cmd << " R#{integer_flag(:recache_ttl, recache_ttl)}" if recache_ttl
52
52
  cmd << ' h' if return_hit_status # Return hit status (0 or 1)
@@ -68,7 +68,7 @@ module Dalli
68
68
  # without the keyword-argument handling and incremental string building.
69
69
  def plain_meta_set(key, value_bytesize, bitflags, ttl)
70
70
  flags = bitflags ? " F#{bitflags}" : ''
71
- flags += " T#{integer_flag(:ttl, ttl)}" if ttl
71
+ flags += " T#{ttl_flag(:ttl, ttl)}" if ttl
72
72
  if KeyRegularizer.required?(key)
73
73
  "ms #{KeyRegularizer.encode(key)} #{value_bytesize} c b#{flags} MS#{TERMINATOR}"
74
74
  else
@@ -111,7 +111,7 @@ module Dalli
111
111
  cmd << ' b' if base64
112
112
  cmd << " F#{bitflags}" if bitflags
113
113
  cmd << cas_string(cas)
114
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
114
+ cmd << " T#{ttl_flag(:ttl, ttl)}" if ttl
115
115
  cmd << " M#{mode_to_token(mode)}"
116
116
  cmd << ' q' if quiet
117
117
  cmd << routing_tokens(p_token: p_token, l_token: l_token)
@@ -123,7 +123,7 @@ module Dalli
123
123
  # built once rather than per entry. It's binary, like the buffer, so
124
124
  # a token with non-ASCII characters doesn't turn the buffer UTF-8.
125
125
  token_suffix = routing_tokens(p_token: p_token, l_token: l_token).b
126
- ttl = integer_flag(:ttl, ttl) if ttl
126
+ ttl = ttl_flag(:ttl, ttl) if ttl
127
127
 
128
128
  buffer = ''.b
129
129
  entries.each do |key, pair|
@@ -144,22 +144,6 @@ module Dalli
144
144
  buffer << META_NOOP
145
145
  end
146
146
 
147
- # Values are appended as bytes. One batch can hold UTF-8 and binary
148
- # values, which String#<< refuses to combine, and a raw value can be in
149
- # an encoding that isn't ASCII-compatible, such as UTF-16.
150
- # Don't chain on the result: TruffleRuby's append_as_bytes returns its
151
- # arguments rather than the buffer.
152
- if String.method_defined?(:append_as_bytes)
153
- def append_bytes(buffer, value)
154
- buffer.append_as_bytes(value)
155
- end
156
- else
157
- def append_bytes(buffer, value)
158
- buffer << (value.encoding == Encoding::BINARY ? value : value.b)
159
- end
160
- end
161
- private :append_bytes
162
-
163
147
  # Thundering herd protection flag:
164
148
  # - stale (I flag): Instead of deleting the item, mark it as stale. Other clients
165
149
  # using N/R flags will see the X flag and know the item is being regenerated.
@@ -183,7 +167,7 @@ module Dalli
183
167
  cmd = "md #{encoded_key(key)}"
184
168
  cmd << cas_string(cas)
185
169
  cmd << ' I' if stale # Mark stale instead of deleting
186
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
170
+ cmd << " T#{ttl_flag(:ttl, ttl)}" if ttl
187
171
  cmd << ' x' if drop_value # Drop the value but keep the item
188
172
  cmd << ' q' if quiet
189
173
  cmd << routing_tokens(p_token: p_token, l_token: l_token)
@@ -202,7 +186,7 @@ module Dalli
202
186
 
203
187
  suffix = +''
204
188
  suffix << ' I' if stale
205
- suffix << " T#{integer_flag(:ttl, ttl)}" if ttl
189
+ suffix << " T#{ttl_flag(:ttl, ttl)}" if ttl
206
190
  suffix << ' x' if drop_value
207
191
  suffix << ' q'
208
192
  suffix << routing_tokens(p_token: p_token, l_token: l_token)
@@ -218,10 +202,10 @@ module Dalli
218
202
  def meta_arithmetic(key:, delta:, initial:, incr: true, cas: nil, ttl: nil, quiet: false,
219
203
  p_token: nil, l_token: nil)
220
204
  cmd = "ma #{encoded_key(key)} v"
221
- cmd << " D#{integer_flag(:delta, delta)}" if delta
222
- cmd << " J#{integer_flag(:initial, initial)}" if initial
205
+ cmd << " D#{parse_to_64_bit_int(:delta, delta)}" if delta
206
+ cmd << " J#{parse_to_64_bit_int(:initial, initial)}" if initial
223
207
  # Always set a TTL if an initial value is specified
224
- cmd << " N#{ttl ? integer_flag(:ttl, ttl) : 0}" if ttl || initial
208
+ cmd << " N#{ttl ? ttl_flag(:ttl, ttl) : 0}" if ttl || initial
225
209
  cmd << cas_string(cas)
226
210
  cmd << ' q' if quiet
227
211
  cmd << " M#{incr ? 'I' : 'D'}"
@@ -273,7 +257,7 @@ module Dalli
273
257
 
274
258
  def flush(delay: nil, quiet: false)
275
259
  cmd = +'flush_all'
276
- cmd << " #{parse_to_64_bit_int(delay, 0)}" if delay
260
+ cmd << " #{parse_to_64_bit_int(:delay, delay)}" if delay
277
261
  cmd << ' noreply' if quiet
278
262
  cmd << TERMINATOR
279
263
  end
@@ -298,6 +282,21 @@ module Dalli
298
282
 
299
283
  private
300
284
 
285
+ # Values are appended as bytes. One batch can hold UTF-8 and binary
286
+ # values, which String#<< refuses to combine, and a raw value can be in
287
+ # an encoding that isn't ASCII-compatible, such as UTF-16.
288
+ # Don't chain on the result: TruffleRuby's append_as_bytes returns its
289
+ # arguments rather than the buffer.
290
+ if String.method_defined?(:append_as_bytes)
291
+ def append_bytes(buffer, value)
292
+ buffer.append_as_bytes(value)
293
+ end
294
+ else
295
+ def append_bytes(buffer, value)
296
+ buffer << (value.encoding == Encoding::BINARY ? value : value.b)
297
+ end
298
+ end
299
+
301
300
  # Disallowed bytes: whitespace and control characters. CR, LF or NUL
302
301
  # would let a token inject a second command; a space would let it add
303
302
  # meta flags (T, N, I, q, ...) to the request it rides on.
@@ -323,6 +322,20 @@ module Dalli
323
322
  raise ArgumentError, "#{name} must be an Integer, got #{value.inspect}"
324
323
  end
325
324
 
325
+ # A TTL becomes memcached's expiration time, which must fit in a signed
326
+ # 32-bit value; anything else gets a CLIENT_ERROR reply, which a quiet
327
+ # request never reports. Callers pass TTLs through TtlSanitizer first.
328
+ def ttl_flag(name, value)
329
+ min = TtlSanitizer::MIN_EXPIRATION_TIME
330
+ max = TtlSanitizer::MAX_EXPIRATION_TIME
331
+ return value if value.is_a?(Integer) && value >= min && value <= max
332
+
333
+ ttl = integer_flag(name, value)
334
+ return ttl if ttl.between?(min, max)
335
+
336
+ raise ArgumentError, "#{name} must be between #{min} and #{max}, got #{value.inspect}"
337
+ end
338
+
326
339
  def mode_to_token(mode)
327
340
  case mode
328
341
  when :add
@@ -339,15 +352,31 @@ module Dalli
339
352
  end
340
353
 
341
354
  def cas_string(cas)
342
- cas = parse_to_64_bit_int(cas, nil)
355
+ # No CAS, the usual case
356
+ return '' if cas.nil? || cas.eql?(0)
357
+
358
+ cas = parse_to_64_bit_int(:cas, cas)
343
359
  cas.nil? || cas.zero? ? '' : " C#{cas}"
344
360
  end
345
361
 
346
- def parse_to_64_bit_int(val, default)
347
- val.nil? ? nil : Integer(val)
348
- rescue ArgumentError
349
- # Sanitize to default if it isn't parsable as an integer
350
- default
362
+ MAX_UINT64 = (2**64) - 1
363
+ private_constant :MAX_UINT64
364
+
365
+ # Parses a value memcached reads as an unsigned 64-bit integer (a CAS,
366
+ # an incr/decr delta or initial value, a flush delay): an Integer, or a
367
+ # String of decimal digits. Anything else raises. A bad CAS used to be
368
+ # dropped, which turned a CAS write into an unconditional one; a Float
369
+ # delta was truncated, so incr by 0.9 did nothing.
370
+ def parse_to_64_bit_int(name, val)
371
+ return nil if val.nil?
372
+
373
+ int = case val
374
+ when Integer then val
375
+ when String then Integer(val, 10, exception: false)
376
+ end
377
+ return int if int && int >= 0 && int <= MAX_UINT64
378
+
379
+ raise ArgumentError, "#{name} must be an Integer between 0 and #{MAX_UINT64}, got #{val.inspect}"
351
380
  end
352
381
  end
353
382
  end
@@ -26,8 +26,6 @@ module Dalli
26
26
  VA_PREFIX = 'VA '
27
27
  # memcached can't store an item larger than 1 GiB (its -I maximum)
28
28
  MAX_VALUE_BYTES = 1024 * 1024 * 1024
29
- MAX_STATS_ENTRIES = 10_000
30
- MAX_QUIET_RESPONSES = 100_000
31
29
  HD_PREFIX = 'HD '
32
30
  FLAGS_TOKEN_PREFIX = ' f'
33
31
  CAS_TOKEN_PREFIX = ' c'
@@ -178,11 +176,7 @@ module Dalli
178
176
  def stats
179
177
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
180
178
  values = {}
181
- replies = 0
182
179
  while tokens.first != END_TOKEN
183
- replies += 1
184
- raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
185
-
186
180
  values[tokens[1]] = tokens[2]
187
181
  tokens = next_line_to_tokens
188
182
  end
@@ -206,16 +200,10 @@ module Dalli
206
200
  tokens.last
207
201
  end
208
202
 
209
- def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
203
+ def consume_all_responses_until_mn
210
204
  tokens = next_line_to_tokens
211
205
 
212
- replies = 0
213
- while tokens.first != MN
214
- replies += 1
215
- raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
216
-
217
- tokens = next_line_to_tokens
218
- end
206
+ tokens = next_line_to_tokens while tokens.first != MN
219
207
  true
220
208
  end
221
209
 
@@ -226,13 +214,11 @@ module Dalli
226
214
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
227
215
  # callers can derive the number of successful deletes as
228
216
  # (keys_sent - non_deletions).
229
- def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
217
+ def pipelined_delete_non_deletions
230
218
  non_deletions = 0
231
219
  tokens = next_line_to_tokens
232
220
  until tokens.first == MN
233
221
  non_deletions += 1
234
- raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
235
-
236
222
  tokens = next_line_to_tokens
237
223
  end
238
224
  non_deletions
@@ -253,13 +239,6 @@ module Dalli
253
239
  def getk_response_from_buffer(buf, offset = 0, raw: false)
254
240
  # Find the header terminator starting from offset
255
241
  term_idx = buf.byteindex(TERMINATOR, offset)
256
- max_line_bytes = ConnectionManager::MAX_LINE_BYTES
257
- header_too_long = if term_idx
258
- term_idx - offset + TERMINATOR.bytesize > max_line_bytes
259
- else
260
- buf.bytesize - offset >= max_line_bytes
261
- end
262
- raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
263
242
  return [0] unless term_idx
264
243
 
265
244
  if buf.byteslice(offset, VA_PREFIX.bytesize) == VA_PREFIX
@@ -303,19 +282,23 @@ module Dalli
303
282
  # a complete response, don't advance the buffer
304
283
  return [0] unless buf.bytesize >= offset + resp_size
305
284
 
285
+ # The CRLF after the value; see strip_value_terminator!
306
286
  term = offset + header_len + body_len
307
287
  raise_bad_value_terminator unless buf.getbyte(term) == BYTE_CR && buf.getbyte(term + 1) == BYTE_LF
308
288
 
309
- # The full response is in our buffer, so parse it and return
310
- # the values
311
- body = buf.byteslice(offset + header_len, body_len)
312
- value = retrieve(body, raw ? 0 : flag_int(bitflags, 'f'), raw)
313
289
  # A hit with no key can't be matched to a request: skip it (false
314
290
  # status) rather than yield it, or take it for the end of the pipeline
315
291
  return [false, resp_size] unless key
316
292
 
317
293
  key = key.delete_prefix!('k')
318
294
  key = KeyRegularizer.decode(key) if base64
295
+ # The full response is in our buffer, so parse it and return
296
+ # the values
297
+ begin
298
+ value = retrieve(buf.byteslice(offset + header_len, body_len), raw ? 0 : flag_int(bitflags, 'f'), raw)
299
+ rescue Dalli::UnmarshalError => e
300
+ return unmarshal_failed(e, key, resp_size)
301
+ end
319
302
  [tokens.first == VA, flag_int(cas, 'c'), key, value, resp_size]
320
303
  end
321
304
 
@@ -349,14 +332,34 @@ module Dalli
349
332
  term = offset + header_len + size
350
333
  raise_bad_value_terminator unless buf.getbyte(term) == BYTE_CR && buf.getbyte(term + 1) == BYTE_LF
351
334
 
352
- value = retrieve(buf.byteslice(offset + header_len, size), raw ? 0 : bitflags || 0, raw)
353
335
  # Skipped like the token path does; see getk_response_from_buffer
354
336
  return [false, resp_size] unless key
355
337
 
356
338
  key = KeyRegularizer.decode(key) if base64
339
+ begin
340
+ value = retrieve(buf.byteslice(offset + header_len, size), raw ? 0 : bitflags || 0, raw)
341
+ rescue Dalli::UnmarshalError => e
342
+ return unmarshal_failed(e, key, resp_size)
343
+ end
357
344
  [true, cas || 0, key, value, resp_size]
358
345
  end
359
346
 
347
+ # A pipelined reply whose value can't be deserialized is consumed and
348
+ # skipped (false status), so the replies after it stay in step. Its
349
+ # key is still returned for the reply key check. The first such error
350
+ # is held until the pipeline finishes; see take_unmarshal_error.
351
+ def unmarshal_failed(error, key, resp_size)
352
+ @unmarshal_error ||= error
353
+ [false, 0, key, nil, resp_size]
354
+ end
355
+
356
+ # Returns the error held by unmarshal_failed, if any, and forgets it
357
+ def take_unmarshal_error
358
+ error = @unmarshal_error
359
+ @unmarshal_error = nil
360
+ error
361
+ end
362
+
360
363
  # Values from a raw request are returned as stored
361
364
  def retrieve(value, bitflags, raw)
362
365
  raw ? value : @value_marshaller.retrieve(value, bitflags)
@@ -485,13 +488,14 @@ module Dalli
485
488
  end
486
489
 
487
490
  def check_value_size!(size)
488
- limit = @value_marshaller.max_response_bytes
489
- return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
491
+ return if size.between?(0, MAX_VALUE_BYTES)
490
492
 
491
- effective_limit = [MAX_VALUE_BYTES, limit].min
492
- raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
493
+ raise Dalli::DalliError, "Reply value size #{size} is out of range"
493
494
  end
494
495
 
496
+ # A value is read by its declared size, so check the CRLF that should
497
+ # follow it. If the size doesn't match the value, the rest of the
498
+ # reply would otherwise be read as the next one. Returns the value.
495
499
  def strip_value_terminator!(data)
496
500
  data&.chomp!(TERMINATOR) || raise_bad_value_terminator
497
501
  end
@@ -15,14 +15,12 @@ module Dalli
15
15
  value_max_bytes: 1024 * 1024
16
16
  }.freeze
17
17
 
18
- attr_reader :value_max_bytes, :max_response_bytes
18
+ attr_reader :value_max_bytes
19
19
 
20
20
  def initialize(client_options)
21
21
  @value_max_bytes = client_options.fetch(:value_max_bytes) do
22
22
  DEFAULTS.fetch(:value_max_bytes)
23
23
  end.to_i
24
- @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, @value_max_bytes))
25
- raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
26
24
  end
27
25
 
28
26
  def store(key, value, _options = nil)
@@ -14,9 +14,17 @@ module Dalli
14
14
  # treated as a unix timestamp of an exact date.
15
15
  MAX_ACCEPTABLE_EXPIRATION_INTERVAL = 30 * 24 * 60 * 60 # 30 days
16
16
 
17
+ # memcached holds an expiration time in a signed 32-bit integer, so a
18
+ # sanitized TTL outside this range is rejected with CLIENT_ERROR. A
19
+ # negative TTL is accepted and stores the item as already expired.
20
+ MIN_EXPIRATION_TIME = -(2**31)
21
+ MAX_EXPIRATION_TIME = (2**31) - 1
22
+
17
23
  # Ensures the TTL passed to Memcached is a valid TTL in the expected format.
24
+ # A String must be a whole number in decimal; it used to go through
25
+ # String#to_i, so 'abc' became 0, which means no expiry.
18
26
  def self.sanitize(ttl)
19
- ttl_as_i = ttl.to_i
27
+ ttl_as_i = ttl.is_a?(String) ? Integer(ttl, 10) : ttl.to_i
20
28
  return ttl_as_i if less_than_max_expiration_interval?(ttl_as_i)
21
29
 
22
30
  as_timestamp(ttl_as_i)
@@ -30,9 +38,10 @@ module Dalli
30
38
  now = current_timestamp
31
39
  return ttl_as_i if ttl_as_i > now # Already a timestamp
32
40
 
33
- Dalli.logger.debug "Expiration interval (#{ttl_as_i}) too long for Memcached " \
34
- 'and too short to be a future timestamp, ' \
35
- 'converting to an expiration timestamp'
41
+ Dalli.logger.debug do
42
+ "Expiration interval (#{ttl_as_i}) too long for Memcached " \
43
+ 'and too short to be a future timestamp, converting to an expiration timestamp'
44
+ end
36
45
  now + ttl_as_i
37
46
  end
38
47
 
@@ -47,8 +47,6 @@ module Dalli
47
47
  @marshal_options =
48
48
  DEFAULTS.merge(client_options.slice(*OPTIONS))
49
49
  @marshal_options[:value_max_bytes] = @marshal_options[:value_max_bytes].to_i
50
- @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, value_max_bytes))
51
- raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
52
50
  end
53
51
 
54
52
  def store(key, value, options = nil)
@@ -69,8 +67,6 @@ module Dalli
69
67
  @marshal_options[:value_max_bytes]
70
68
  end
71
69
 
72
- attr_reader :max_response_bytes
73
-
74
70
  def error_if_over_max_value_bytes(key, value)
75
71
  self.class.error_if_over_max_value_bytes(key, value, value_max_bytes)
76
72
  end
data/lib/dalli/ring.rb CHANGED
@@ -34,6 +34,10 @@ module Dalli
34
34
  @failover = options[:failover] != false
35
35
  end
36
36
 
37
+ def failover?
38
+ @failover
39
+ end
40
+
37
41
  def continuum=(entries)
38
42
  @continuum = entries
39
43
  # Plain integers, so the lookup in server_for_hash_key needn't call
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'uri'
4
+
3
5
  module Dalli
4
6
  ##
5
7
  # This module contains methods for validating and normalizing the servers
@@ -26,6 +28,8 @@ module Dalli
26
28
  module ServersArgNormalizer
27
29
  ENV_VAR_NAME = 'MEMCACHE_SERVERS'
28
30
  DEFAULT_SERVERS = ['127.0.0.1:11211'].freeze
31
+ URI_CREDENTIAL_WARNING = 'Dalli 5.0 removed SASL authentication. ' \
32
+ 'Credentials in memcached:// URIs are ignored.'
29
33
 
30
34
  ##
31
35
  # Normalizes the argument into an array of servers.
@@ -34,7 +38,21 @@ module Dalli
34
38
  def self.normalize_servers(arg)
35
39
  arg = apply_defaults(arg)
36
40
  validate_type(arg)
37
- Array(arg).flat_map { |s| s.split(',') }.reject(&:empty?)
41
+ Array(arg).flat_map { |s| s.split(',') }.reject(&:empty?).map { |s| without_credentials(s) }
42
+ end
43
+
44
+ # Dalli 5 doesn't use credentials in a memcached:// URI, so they are
45
+ # dropped here, with a warning, rather than kept in the client's server
46
+ # list where #inspect would show them.
47
+ def self.without_credentials(server)
48
+ return server unless server.start_with?('memcached://') && server.include?('@')
49
+
50
+ uri = URI.parse(server)
51
+ return server unless uri.userinfo
52
+
53
+ Dalli.logger.warn(URI_CREDENTIAL_WARNING)
54
+ uri.user = nil # clears the password too
55
+ uri.to_s
38
56
  end
39
57
 
40
58
  def self.apply_defaults(arg)
data/lib/dalli/socket.rb CHANGED
@@ -19,10 +19,6 @@ module Dalli
19
19
  ##
20
20
  module InstanceMethods
21
21
  READ_CHUNK_SIZE = 8196
22
- # Give the response parser control between bounded socket reads. In
23
- # particular, a peer continuously sending a header without CRLF must
24
- # not keep this method appending forever.
25
- MAX_AVAILABLE_BYTES = READ_CHUNK_SIZE * 8
26
22
 
27
23
  # Reads whatever is available without blocking. A read that returns less
28
24
  # than a full chunk means the socket was drained, so we stop there rather
@@ -30,7 +26,7 @@ module Dalli
30
26
  # Callers keep waiting on IO.select for anything that arrives later.
31
27
  def read_available(reusable_buffer = nil)
32
28
  if reusable_buffer
33
- value = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES].min, reusable_buffer, exception: false)
29
+ value = read_nonblock(READ_CHUNK_SIZE, reusable_buffer, exception: false)
34
30
  case value
35
31
  when :wait_writable, :wait_readable
36
32
  return reusable_buffer.clear
@@ -38,15 +34,13 @@ module Dalli
38
34
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
39
35
  end
40
36
  return value if drained_after?(value)
41
- return value if value.bytesize >= MAX_AVAILABLE_BYTES
42
37
  else
43
38
  value = ''.b
44
39
  end
45
40
 
46
41
  buffer = ''.b
47
42
  loop do
48
- result = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES - value.bytesize].min,
49
- buffer, exception: false)
43
+ result = read_nonblock(READ_CHUNK_SIZE, buffer, exception: false)
50
44
  case result
51
45
  when :wait_writable, :wait_readable
52
46
  buffer.clear
@@ -56,7 +50,6 @@ module Dalli
56
50
  else
57
51
  value << result
58
52
  return value if drained_after?(result)
59
- return value if value.bytesize >= MAX_AVAILABLE_BYTES
60
53
  end
61
54
  end
62
55
  end
@@ -121,17 +114,13 @@ module Dalli
121
114
  # jruby-openssl can take the next record off the socket during a short
122
115
  # read and hold it where neither pending nor IO.select sees it, so on
123
116
  # JRuby a read continues until the socket would block.
124
- def pending_data?
125
- pending.positive? || (@rbuffer && !@rbuffer.empty?)
126
- end
127
-
128
117
  if RUBY_ENGINE == 'jruby'
129
118
  def buffered_data?
130
119
  true
131
120
  end
132
121
  else
133
122
  def buffered_data?
134
- pending_data?
123
+ pending.positive?
135
124
  end
136
125
  end
137
126
 
@@ -168,12 +157,7 @@ module Dalli
168
157
  sock.options = { host: host, port: port }.merge(options)
169
158
  init_socket_options(sock, options)
170
159
 
171
- if options[:ssl_context]
172
- wrapping_ssl_socket(sock, host, options[:ssl_context],
173
- options[:socket_timeout])
174
- else
175
- sock
176
- end
160
+ options[:ssl_context] ? wrapping_ssl_socket(sock, host, options[:ssl_context]) : sock
177
161
  end
178
162
  end
179
163
 
@@ -208,6 +192,9 @@ module Dalli
208
192
  end
209
193
 
210
194
  def self.init_socket_options(sock, options)
195
+ # CRuby sets this on every socket; TruffleRuby doesn't, so a process
196
+ # the app spawns would inherit the connection and hold it open
197
+ sock.close_on_exec = true
211
198
  configure_tcp_options(sock, options)
212
199
  configure_socket_buffers(sock, options)
213
200
  configure_timeout(sock, options)
@@ -264,15 +251,13 @@ module Dalli
264
251
 
265
252
  # Closes the TCP socket if the handshake fails or times out, so a failed
266
253
  # attempt doesn't hold a file descriptor until GC.
267
- def self.wrapping_ssl_socket(tcp_socket, host, ssl_context, timeout = nil)
254
+ def self.wrapping_ssl_socket(tcp_socket, host, ssl_context)
268
255
  warn_if_unverified(ssl_context)
269
256
  connected = false
270
257
  ssl_socket = Dalli::Socket::SSLSocket.new(tcp_socket, ssl_context)
271
258
  ssl_socket.hostname = host
272
259
  ssl_socket.sync_close = true
273
- # The underlying TCP socket's IO#timeout= does not reliably bound
274
- # OpenSSL's blocking handshake on Ruby 3.3.
275
- Timeout.timeout(timeout) { ssl_socket.connect }
260
+ ssl_socket.connect
276
261
  connected = true
277
262
  ssl_socket
278
263
  ensure
@@ -335,6 +320,8 @@ module Dalli
335
320
  end
336
321
 
337
322
  def self.init_socket_options(sock, options)
323
+ # Not inherited by spawned processes; see TCP.init_socket_options
324
+ sock.close_on_exec = true
338
325
  # https://man7.org/linux/man-pages/man7/unix.7.html
339
326
  sock.setsockopt(::Socket::SOL_SOCKET, ::Socket::SO_SNDBUF, options[:sndbuf]) if options[:sndbuf]
340
327
  sock.timeout = options[:socket_timeout] if options[:socket_timeout] && sock.respond_to?(:timeout=)
data/lib/dalli/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Dalli
4
- VERSION = '5.2.10'
4
+ VERSION = '5.3.0'
5
5
 
6
6
  MIN_SUPPORTED_MEMCACHED_VERSION = '1.6.27'
7
7
  end
data/lib/dalli.rb CHANGED
@@ -29,7 +29,19 @@ module Dalli
29
29
  class ServerError < DalliError; end
30
30
 
31
31
  # socket/server communication error that can be retried
32
- class RetryableNetworkError < NetworkError; end
32
+ class RetryableNetworkError < NetworkError
33
+ def initialize(message = nil, request_sent: false)
34
+ super(message)
35
+ @request_sent = request_sent
36
+ end
37
+
38
+ # True when some of the failed request was handed to the socket, so
39
+ # memcached may have applied it even though its reply was lost. Only a
40
+ # request that is safe to send twice is retried then.
41
+ def request_sent?
42
+ @request_sent
43
+ end
44
+ end
33
45
 
34
46
  # a multi-get reply named a key that wasn't requested, so the rest of that
35
47
  # server's replies can't be trusted
@@ -71,6 +83,7 @@ require_relative 'dalli/compressor'
71
83
  require_relative 'dalli/cache_result'
72
84
  require_relative 'dalli/client'
73
85
  require_relative 'dalli/key_manager'
86
+ require_relative 'dalli/key_grouping'
74
87
  require_relative 'dalli/pipelined_getter'
75
88
  require_relative 'dalli/pipelined_setter'
76
89
  require_relative 'dalli/pipelined_deleter'
@@ -46,7 +46,10 @@ module Rack
46
46
  #
47
47
  # It is not recommended to set `:expires_in`. Instead, use `:expire_after`,
48
48
  # which will control both the expiration of the client cookie as well
49
- # as the expiration of the corresponding entry in memcached.
49
+ # as the expiration of the corresponding entry in memcached. Without
50
+ # `:expire_after`, sessions are stored with no expiry: one stays in
51
+ # memcached until it's deleted (for example by a logout) or memcached
52
+ # evicts it, and a stolen session cookie keeps working until then.
50
53
  #
51
54
  # Rack::Session::Dalli also accepts a host of options that control how
52
55
  # the sessions and session cookies are managed, including the
@@ -144,6 +147,11 @@ module Rack
144
147
  sid.private_id if sid.respond_to?(:private_id)
145
148
  end
146
149
 
150
+ # A session that can't be decoded, for example after a change of
151
+ # serializer or a deploy that removed a class stored in it, is treated
152
+ # as missing, so the request gets a new session. Otherwise the session
153
+ # id couldn't be used or replaced, and the user couldn't log in until
154
+ # the cookie was cleared.
147
155
  def existing_session_for_sid(client, sid)
148
156
  return nil unless sid && !sid.empty?
149
157
 
@@ -151,6 +159,9 @@ module Rack
151
159
  return nil if key.nil?
152
160
 
153
161
  client.get(key)
162
+ rescue ::Dalli::UnmarshalError => e
163
+ ::Dalli.logger.warn("#{self.class} couldn't decode a stored session, so it started a new one: #{e.message}")
164
+ nil
154
165
  end
155
166
 
156
167
  def create_sid_with_empty_session(client)
@@ -184,12 +195,9 @@ module Rack
184
195
  end
185
196
  end
186
197
 
187
- # Rails stores an ActionDispatch::Request::Session::Options in the env, not a
188
- # Hash. It implements [] (and to_hash) but not Hash#slice, so slicing it
189
- # raised NoMethodError instead of returning this 401.
190
198
  def missing_session_response(env)
191
199
  options = env[Rack::RACK_SESSION_OPTIONS] || @default_options
192
- cookie = Rack::Utils.delete_set_cookie_header(key, { path: options[:path], domain: options[:domain] })
200
+ cookie = Rack::Utils.delete_set_cookie_header(key, options.slice(:path, :domain))
193
201
  [401, { 'content-type' => 'text/plain', 'set-cookie' => cookie }, ['Wrong session ID']]
194
202
  end
195
203
 
@@ -234,8 +242,6 @@ module Rack
234
242
  def with_dalli_client(result_on_error = nil, &)
235
243
  @data.with(&)
236
244
  rescue ::Dalli::DalliError, Errno::ECONNREFUSED
237
- raise if $ERROR_INFO.message.include?('undefined class')
238
-
239
245
  if $VERBOSE
240
246
  warn "#{self} is unable to find memcached server."
241
247
  warn $ERROR_INFO.inspect