dalli 5.2.9 → 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'
@@ -37,6 +35,8 @@ module Dalli
37
35
  BYTE_F = 'f'.ord
38
36
  BYTE_K = 'k'.ord
39
37
  BYTE_S = 's'.ord
38
+ BYTE_CR = "\r".ord
39
+ BYTE_LF = "\n".ord
40
40
 
41
41
  T_OK = [OK].freeze
42
42
  T_RESET = [RESET].freeze
@@ -176,11 +176,7 @@ module Dalli
176
176
  def stats
177
177
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
178
178
  values = {}
179
- replies = 0
180
179
  while tokens.first != END_TOKEN
181
- replies += 1
182
- raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
183
-
184
180
  values[tokens[1]] = tokens[2]
185
181
  tokens = next_line_to_tokens
186
182
  end
@@ -204,16 +200,10 @@ module Dalli
204
200
  tokens.last
205
201
  end
206
202
 
207
- def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
203
+ def consume_all_responses_until_mn
208
204
  tokens = next_line_to_tokens
209
205
 
210
- replies = 0
211
- while tokens.first != MN
212
- replies += 1
213
- raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
214
-
215
- tokens = next_line_to_tokens
216
- end
206
+ tokens = next_line_to_tokens while tokens.first != MN
217
207
  true
218
208
  end
219
209
 
@@ -224,13 +214,11 @@ module Dalli
224
214
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
225
215
  # callers can derive the number of successful deletes as
226
216
  # (keys_sent - non_deletions).
227
- def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
217
+ def pipelined_delete_non_deletions
228
218
  non_deletions = 0
229
219
  tokens = next_line_to_tokens
230
220
  until tokens.first == MN
231
221
  non_deletions += 1
232
- raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
233
-
234
222
  tokens = next_line_to_tokens
235
223
  end
236
224
  non_deletions
@@ -251,13 +239,6 @@ module Dalli
251
239
  def getk_response_from_buffer(buf, offset = 0, raw: false)
252
240
  # Find the header terminator starting from offset
253
241
  term_idx = buf.byteindex(TERMINATOR, offset)
254
- max_line_bytes = ConnectionManager::MAX_LINE_BYTES
255
- header_too_long = if term_idx
256
- term_idx - offset + TERMINATOR.bytesize > max_line_bytes
257
- else
258
- buf.bytesize - offset >= max_line_bytes
259
- end
260
- raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
261
242
  return [0] unless term_idx
262
243
 
263
244
  if buf.byteslice(offset, VA_PREFIX.bytesize) == VA_PREFIX
@@ -301,16 +282,23 @@ module Dalli
301
282
  # a complete response, don't advance the buffer
302
283
  return [0] unless buf.bytesize >= offset + resp_size
303
284
 
304
- # The full response is in our buffer, so parse it and return
305
- # the values
306
- body = buf.byteslice(offset + header_len, body_len)
307
- value = retrieve(body, raw ? 0 : flag_int(bitflags, 'f'), raw)
285
+ # The CRLF after the value; see strip_value_terminator!
286
+ term = offset + header_len + body_len
287
+ raise_bad_value_terminator unless buf.getbyte(term) == BYTE_CR && buf.getbyte(term + 1) == BYTE_LF
288
+
308
289
  # A hit with no key can't be matched to a request: skip it (false
309
290
  # status) rather than yield it, or take it for the end of the pipeline
310
291
  return [false, resp_size] unless key
311
292
 
312
293
  key = key.delete_prefix!('k')
313
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
314
302
  [tokens.first == VA, flag_int(cas, 'c'), key, value, resp_size]
315
303
  end
316
304
 
@@ -341,14 +329,37 @@ module Dalli
341
329
  resp_size = header_len + size + TERMINATOR.length
342
330
  return [0] unless buf.bytesize >= offset + resp_size
343
331
 
344
- value = retrieve(buf.byteslice(offset + header_len, size), raw ? 0 : bitflags || 0, raw)
332
+ term = offset + header_len + size
333
+ raise_bad_value_terminator unless buf.getbyte(term) == BYTE_CR && buf.getbyte(term + 1) == BYTE_LF
334
+
345
335
  # Skipped like the token path does; see getk_response_from_buffer
346
336
  return [false, resp_size] unless key
347
337
 
348
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
349
344
  [true, cas || 0, key, value, resp_size]
350
345
  end
351
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
+
352
363
  # Values from a raw request are returned as stored
353
364
  def retrieve(value, bitflags, raw)
354
365
  raw ? value : @value_marshaller.retrieve(value, bitflags)
@@ -477,11 +488,20 @@ module Dalli
477
488
  end
478
489
 
479
490
  def check_value_size!(size)
480
- limit = @value_marshaller.max_response_bytes
481
- return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
491
+ return if size.between?(0, MAX_VALUE_BYTES)
492
+
493
+ raise Dalli::DalliError, "Reply value size #{size} is out of range"
494
+ end
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.
499
+ def strip_value_terminator!(data)
500
+ data&.chomp!(TERMINATOR) || raise_bad_value_terminator
501
+ end
482
502
 
483
- effective_limit = [MAX_VALUE_BYTES, limit].min
484
- raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
503
+ def raise_bad_value_terminator
504
+ raise Dalli::DalliError, "Reply value isn't followed by CRLF, so its size doesn't match the value"
485
505
  end
486
506
 
487
507
  def read_line
@@ -497,7 +517,7 @@ module Dalli
497
517
  # Checked before the terminator is added: -1 or -2 would otherwise
498
518
  # read 1 or 0 bytes and leave the connection out of step
499
519
  check_value_size!(data_size)
500
- @io_source.read(data_size + TERMINATOR.bytesize)&.chomp!(TERMINATOR)
520
+ strip_value_terminator!(@io_source.read(data_size + TERMINATOR.bytesize))
501
521
  end
502
522
  end
503
523
  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.9'
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'