dalli 5.0.14 → 5.1.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.
@@ -25,7 +25,6 @@ module Dalli
25
25
  warn_uri_credentials(user_creds)
26
26
  @options = client_options.merge(user_creds)
27
27
  @raw_mode = client_options[:raw]
28
- @verify_reply_keys = client_options[:verify_reply_keys] ? true : false
29
28
  @value_marshaller = @raw_mode ? StringMarshaller.new(@options) : ValueMarshaller.new(@options)
30
29
  @connection_manager = ConnectionManager.new(hostname, port, socket_type, @options)
31
30
  end
@@ -36,14 +35,6 @@ module Dalli
36
35
  @raw_mode
37
36
  end
38
37
 
39
- # True when values should come back as stored: the client is in raw mode,
40
- # or this request passed raw: true. Retrieval paths use it to skip
41
- # requesting flags, so a stored value is never deserialized or
42
- # decompressed for a caller who asked for raw bytes.
43
- def raw_request?(options)
44
- raw_mode? || (options.is_a?(Hash) && options[:raw]) ? true : false
45
- end
46
-
47
38
  # Chokepoint method for error handling and ensuring liveness
48
39
  def request(opkey, *args)
49
40
  verify_state(opkey)
@@ -51,25 +42,15 @@ module Dalli
51
42
  begin
52
43
  request_completed = false
53
44
  @connection_manager.start_request!
54
- drain_pending_quiet_responses(opkey)
55
45
  response = send(opkey, *args)
56
- # Quiet requests can leave replies on the socket; remember that so a
57
- # later non-quiet request knows to read them first
58
- @connection_manager.mark_quiet_responses_pending! if quiet? && opkey != :noop
59
46
 
60
47
  # pipelined_get/pipelined_get_interleaved emit query but don't read the response(s)
61
48
  @connection_manager.finish_request! unless %i[pipelined_get pipelined_get_interleaved].include?(opkey)
62
49
 
63
50
  request_completed = true
64
51
  response
65
- rescue Dalli::MarshalError, Dalli::ValueOverMaxSize => e
66
- log_marshal_err(args.first, e) if e.is_a?(Dalli::MarshalError)
67
- # Raised only while the connection is clean: a value is marshalled
68
- # before any of its request is written, and write_multi_req raises
69
- # only after reading every reply. Closing the connection would
70
- # discard earlier quiet writes still waiting in the write buffer.
71
- @connection_manager.abort_request!
72
- request_completed = true
52
+ rescue Dalli::MarshalError => e
53
+ log_marshal_err(args.first, e)
73
54
  raise
74
55
  rescue Dalli::DalliError
75
56
  raise
@@ -97,6 +78,19 @@ module Dalli
97
78
  # particular memcached instance is available for use.
98
79
  def alive?
99
80
  ensure_connected!
81
+ rescue Dalli::RetryableNetworkError => e
82
+ # A single connection attempt failure is retryable -- the same
83
+ # contract #request enforces on the send/receive path. Retrying here
84
+ # lets error_on_request!'s own fail-count threshold decide when to
85
+ # give up: it keeps raising RetryableNetworkError until
86
+ # socket_max_failures is reached, then raises a terminal
87
+ # NetworkError via down!, which the next rescue converts to false.
88
+ # Without this, a single transient hiccup during the liveness check
89
+ # itself -- as opposed to an actual request -- would report this
90
+ # server as not alive even though it would have reconnected fine.
91
+ Dalli.logger.debug { e.inspect }
92
+ Dalli.logger.debug { "retrying connection attempt to #{name} because of network error" }
93
+ retry
100
94
  rescue Dalli::NetworkError
101
95
  # ensure_connected! raises a NetworkError if connection fails. We
102
96
  # want to capture that error and convert it to a boolean value here.
@@ -116,7 +110,7 @@ module Dalli
116
110
  verify_pipelined_state(:getkq)
117
111
  write_noop
118
112
  # Use ensure_ready instead of reset to preserve any data already buffered
119
- # while this get_multi's interleaved requests were sent
113
+ # during interleaved pipelined get draining
120
114
  response_buffer.ensure_ready
121
115
  end
122
116
 
@@ -129,20 +123,10 @@ module Dalli
129
123
  # avoiding intermediate Hash allocation. Returns nil.
130
124
  # Without a block, returns a Hash of { key => [value, cas] }.
131
125
  def pipeline_next_responses(&block)
132
- return abandon_pipeline if @pipeline_out_of_step
133
-
134
126
  reconnect_on_pipeline_complete!
135
127
  values = nil
136
128
 
137
- # Only the read is socket I/O. The caller's block runs below, outside
138
- # this rescue, so an Errno or Timeout::Error it raises reaches the
139
- # caller instead of being mistaken for a network failure (which closed
140
- # the connection and retried the whole get_multi, yielding keys twice).
141
- begin
142
- response_buffer.read
143
- rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
144
- @connection_manager.error_on_request!(e)
145
- end
129
+ response_buffer.read
146
130
 
147
131
  status, cas, key, value = response_buffer.process_single_getk_response
148
132
  # status is not nil only if we have a full response to parse
@@ -152,13 +136,6 @@ module Dalli
152
136
  # to the noop at the end of the pipeline
153
137
  finish_pipeline && break if status && key.nil?
154
138
 
155
- # A key that wasn't requested means the replies are out of step
156
- # (see expect_reply_keys): keep what was read so far, drop the rest
157
- if unexpected_reply_key?(key)
158
- abandon_pipeline
159
- break
160
- end
161
-
162
139
  # If the status is ok and the key is not nil, then this is a
163
140
  # getkq response with a value that we want to set in the response hash
164
141
  unless key.nil?
@@ -170,38 +147,30 @@ module Dalli
170
147
  end
171
148
  end
172
149
 
173
- # A request to this server from inside the block closes the
174
- # connection, and with it the rest of this get_multi's replies
175
- raise_pipeline_closed unless response_buffer.in_progress?
176
-
177
150
  # Get the next response from the buffer
178
151
  status, cas, key, value = response_buffer.process_single_getk_response
179
152
  end
180
153
 
181
154
  values || {}
155
+ rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
156
+ @connection_manager.error_on_request!(e)
182
157
  end
183
158
  # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
184
159
 
185
160
  # Abort current pipelined get. Generally used to signal an external
186
- # timeout during pipelined get, or that the get_multi stopped before
187
- # reading all its replies (timed_out: false). The underlying socket is
161
+ # timeout during pipelined get. The underlying socket is
188
162
  # disconnected, and the exception is swallowed.
189
163
  #
190
164
  # Returns nothing.
191
- def pipeline_abort(timed_out: true)
165
+ def pipeline_abort
192
166
  response_buffer.clear
193
- @pipeline_out_of_step = false
194
- @expected_reply_keys = nil
195
167
  @connection_manager.abort_request!
196
168
  return true unless connected?
197
169
 
198
- # Closes the connection, which ensures that our connection is in a
199
- # clean state for future requests. The get_multi ran out of time
200
- # overall, or stopped early, rather than hitting a socket error, so it
201
- # doesn't count toward socket_max_failures: two slow get_multis in a
202
- # row would otherwise mark a healthy server down.
203
- log_pipeline_abort(timed_out)
204
- @connection_manager.close
170
+ # Closes the connection, which ensures that our connection
171
+ # is in a clean state for future requests
172
+ @connection_manager.error_on_request!('External timeout')
173
+ rescue NetworkError
205
174
  true
206
175
  end
207
176
 
@@ -232,18 +201,6 @@ module Dalli
232
201
  ALLOWED_QUIET_OPS = %i[add replace set delete incr decr append prepend flush noop].freeze
233
202
  private_constant :ALLOWED_QUIET_OPS
234
203
 
235
- # Reads the replies still pending from quiet requests before any
236
- # non-quiet request, which reads a reply of its own. A quiet block reads
237
- # them at its end, but the connection is shared: another thread or fiber
238
- # (quiet? is fiber-local) can make a request while the block is still
239
- # open, and would otherwise read the block's replies as its own. The
240
- # noop also sends any quiet requests still buffered.
241
- def drain_pending_quiet_responses(opkey)
242
- return unless @connection_manager.quiet_responses_pending? && opkey != :noop && !quiet?
243
-
244
- noop
245
- end
246
-
247
204
  def verify_allowed_quiet!(opkey)
248
205
  return if ALLOWED_QUIET_OPS.include?(opkey)
249
206
 
@@ -293,22 +250,52 @@ module Dalli
293
250
  opts[:cache_nils] ? true : false
294
251
  end
295
252
 
253
+ # Extracts opaque routing-token kwargs (:p_token, :l_token) from a
254
+ # request-options Hash so they can be splatted into a RequestFormatter
255
+ # call. Returns {} when neither is set, so the splat is a no-op on the
256
+ # common path. Validation (type, forbidden bytes) happens at the
257
+ # wire-formatter level, where it can raise uniformly regardless of how
258
+ # the token reached the formatter.
259
+ def routing_token_kwargs(opts)
260
+ return {} unless opts.is_a?(Hash)
261
+ return {} unless opts[:p_token] || opts[:l_token]
262
+
263
+ { p_token: opts[:p_token], l_token: opts[:l_token] }
264
+ end
265
+
266
+ # Maps the client-facing meta-delete options onto RequestFormatter's flag
267
+ # names, so they can be splatted into a meta_delete call. Returns {} when
268
+ # none are set, keeping the splat a no-op on the common path.
269
+ #
270
+ # :tombstone_ttl becomes the T flag, which is the same TTL the formatter
271
+ # already accepted -- deliberately not a second TTL parameter, since two
272
+ # would allow emitting two T tokens in one request. It is sanitized like
273
+ # every other TTL Dalli sends.
274
+ def tombstone_kwargs(opts)
275
+ return {} unless opts.is_a?(Hash)
276
+
277
+ kwargs = {}
278
+ kwargs[:stale] = true if opts[:invalidate]
279
+ kwargs[:ttl] = TtlSanitizer.sanitize(Integer(opts[:tombstone_ttl])) if opts[:tombstone_ttl]
280
+ kwargs[:drop_value] = true if opts[:drop_value]
281
+ kwargs
282
+ end
283
+
296
284
  def connect
297
285
  @connection_manager.establish_connection
298
286
  @version = version
299
287
  up!
300
288
  end
301
289
 
302
- def pipelined_get(keys)
290
+ def pipelined_get(keys, options = nil)
303
291
  # Clear buffer to remove any stale data from interrupted operations.
304
292
  # Use clear (not reset) to keep pipeline_complete? = true, which is
305
293
  # the expected state before pipeline_response_setup is called.
306
294
  response_buffer.clear
307
- expect_reply_keys(keys)
308
295
 
309
296
  req = +''
310
297
  keys.each do |key|
311
- req << quiet_get_request(key)
298
+ req << quiet_get_request(key, options)
312
299
  end
313
300
  # Could send noop here instead of in pipeline_response_setup
314
301
  write(req)
@@ -317,17 +304,15 @@ module Dalli
317
304
  # For large batches, interleave writing requests with draining responses.
318
305
  # This prevents socket buffer deadlock when sending many keys.
319
306
  # Populates the provided results hash with any responses drained during send.
320
- def pipelined_get_interleaved(keys, chunk_size, results)
321
- # Start with an empty buffer for draining during the send phase. Bytes
322
- # left by an earlier get_multi that stopped early belong to its replies.
323
- response_buffer.reset
324
- expect_reply_keys(keys)
307
+ def pipelined_get_interleaved(keys, chunk_size, results, options = nil)
308
+ # Initialize the response buffer for draining during send phase
309
+ response_buffer.ensure_ready
325
310
 
326
311
  keys.each_slice(chunk_size) do |chunk|
327
312
  # Build and write this chunk of requests
328
313
  req = +''
329
314
  chunk.each do |key|
330
- req << quiet_get_request(key)
315
+ req << quiet_get_request(key, options)
331
316
  end
332
317
  write(req)
333
318
  @connection_manager.flush
@@ -354,12 +339,6 @@ module Dalli
354
339
  status, cas, key, value = response_buffer.process_single_getk_response
355
340
  break if status.nil? # No complete response available
356
341
 
357
- # Handled by the next pipeline_next_responses, once sending is done
358
- if unexpected_reply_key?(key)
359
- @pipeline_out_of_step = true
360
- break
361
- end
362
-
363
342
  results[key] = [value, cas] unless key.nil?
364
343
  end
365
344
  rescue SystemCallError, Dalli::NetworkError
@@ -367,48 +346,8 @@ module Dalli
367
346
  nil
368
347
  end
369
348
 
370
- # Registered with the connection manager, which clears it whenever the
371
- # connection closes, so a new connection never parses an old one's bytes
372
349
  def response_buffer
373
- @response_buffer ||= ResponseBuffer.new(@connection_manager, response_processor).tap do |buffer|
374
- @connection_manager.response_buffer = buffer
375
- end
376
- end
377
-
378
- # A multi-get only accepts replies for the keys it asked for. memcached
379
- # names an item created by auto-create (ma or mg with N) for a
380
- # base64-encoded key by its raw bytes, without the b flag; such a key
381
- # can contain spaces or CR/LF, which split the reply header and make the
382
- # replies after it parse as different ones. A key that wasn't requested
383
- # is how that shows up.
384
- # Only with the verify_reply_keys option, since building the set costs a
385
- # multi-get about 15%. Dalli itself no longer creates such items (see
386
- # Meta#decr_incr); the check guards against ones that older versions or
387
- # other clients created, on memcached versions with the behavior.
388
- def expect_reply_keys(keys)
389
- @pipeline_out_of_step = false
390
- @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
391
- end
392
-
393
- def unexpected_reply_key?(key)
394
- !key.nil? && @expected_reply_keys && !@expected_reply_keys.include?(reply_key_form(key))
395
- end
396
-
397
- # Keys compared as bytes; ASCII keys compare equal in any encoding as is
398
- def reply_key_form(key)
399
- key.ascii_only? ? key : key.b
400
- end
401
-
402
- # Keeps what was read, drops the rest of this server's replies, and
403
- # closes the connection so nothing unread is left on it. Not a socket
404
- # failure, so it doesn't count toward socket_max_failures; the keys not
405
- # read are simply missing from the result.
406
- def abandon_pipeline
407
- Dalli.logger.warn { "#{name} replied to a get_multi with a key that wasn't requested; closing the connection" }
408
- @pipeline_out_of_step = false
409
- response_buffer.clear
410
- @connection_manager.close
411
- {}
350
+ @response_buffer ||= ResponseBuffer.new(@connection_manager, response_processor)
412
351
  end
413
352
 
414
353
  # Called after the noop response is received at the end of a set
@@ -424,23 +363,7 @@ module Dalli
424
363
  @connection_manager.reconnect! 'pipelined get has completed' if pipeline_complete?
425
364
  end
426
365
 
427
- def raise_pipeline_closed
428
- raise Dalli::DalliError, "The connection to #{name} closed while a get_multi was reading its replies " \
429
- '(a request made from inside the get_multi block?)'
430
- end
431
-
432
- def log_pipeline_abort(timed_out)
433
- if timed_out
434
- Dalli.logger.warn { "#{name} didn't finish a get_multi within socket_timeout; closing the connection" }
435
- else
436
- Dalli.logger.debug { "#{name} get_multi stopped before reading all replies; closing the connection" }
437
- end
438
- end
439
-
440
- # The single-server set_multi path passes its whole pairs hash as the
441
- # first argument; log only its keys, never the values
442
366
  def log_marshal_err(key, err)
443
- key = key.keys.join("', '") if key.is_a?(Hash)
444
367
  Dalli.logger.error "Marshalling error for key '#{key}': #{err.message}"
445
368
  Dalli.logger.error 'You are trying to cache a Ruby object which cannot be serialized to memcached.'
446
369
  end
@@ -26,9 +26,6 @@ module Dalli
26
26
 
27
27
  attr_accessor :hostname, :port, :socket_type, :options
28
28
  attr_reader :sock
29
- # The buffer replies are read into (see Base#response_buffer). It's
30
- # cleared with the write buffer whenever the connection closes.
31
- attr_writer :response_buffer
32
29
 
33
30
  def initialize(hostname, port, socket_type, client_options)
34
31
  @hostname = hostname
@@ -36,14 +33,9 @@ module Dalli
36
33
  @socket_type = socket_type
37
34
  @options = DEFAULTS.merge(client_options)
38
35
  @request_in_progress = false
39
- @quiet_responses_pending = false
40
36
  @sock = nil
41
37
  @pid = nil
42
- @write_buffer = []
43
- @write_buffer_bytes = 0
44
- @response_buffer = nil
45
38
 
46
- @fail_count = 0
47
39
  reset_down_info
48
40
  end
49
41
 
@@ -59,13 +51,11 @@ module Dalli
59
51
  Dalli.logger.debug { "Dalli::Server#connect #{name}" }
60
52
 
61
53
  @sock = memcached_socket
62
- # Writes are buffered in @write_buffer instead; see WRITE_BUFFER_FLUSH_BYTES
63
- @sock.sync = true
54
+ @sock.sync = false # Enable buffered I/O for better performance
64
55
  @pid = Process.pid
65
56
  @request_in_progress = false
66
- @quiet_responses_pending = false
67
- rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError, SocketError => e
68
- # SocketError = DNS resolution failure; SSL_ERRORS = failed TLS handshake
57
+ rescue SystemCallError, *TIMEOUT_ERRORS, EOFError, SocketError => e
58
+ # SocketError = DNS resolution failure
69
59
  error_on_request!(e)
70
60
  end
71
61
 
@@ -93,8 +83,6 @@ module Dalli
93
83
  def down!
94
84
  close
95
85
  log_down_detected
96
- # Once down_retry_delay passes, the server gets a full set of attempts
97
- @fail_count = 0
98
86
 
99
87
  @error = $ERROR_INFO&.class&.name
100
88
  @msg ||= $ERROR_INFO&.message
@@ -124,7 +112,7 @@ module Dalli
124
112
  return unless @sock
125
113
 
126
114
  begin
127
- close_socket
115
+ @sock.close
128
116
  rescue StandardError
129
117
  nil
130
118
  ensure
@@ -135,39 +123,14 @@ module Dalli
135
123
  # @request_in_progress == true.
136
124
  @sock = nil
137
125
  @pid = nil
138
- @quiet_responses_pending = false
139
- discard_write_buffer
140
- @response_buffer&.clear
141
126
  abort_request!
142
127
  end
143
128
  end
144
129
 
145
- # A forked child shares the parent's connection, so it closes only its
146
- # own file descriptor. Closing the TLS socket itself would send
147
- # close_notify and end the parent's TLS session.
148
- def close_socket
149
- fork_detected? ? @sock.to_io.close : @sock.close
150
- end
151
-
152
130
  def connected?
153
131
  !@sock.nil?
154
132
  end
155
133
 
156
- # True when a quiet request was written on this connection and its
157
- # replies (memcached only suppresses some of them) haven't been
158
- # consumed by a noop yet.
159
- def quiet_responses_pending?
160
- @quiet_responses_pending
161
- end
162
-
163
- def mark_quiet_responses_pending!
164
- @quiet_responses_pending = true
165
- end
166
-
167
- def clear_quiet_responses_pending!
168
- @quiet_responses_pending = false
169
- end
170
-
171
134
  def request_in_progress?
172
135
  @request_in_progress
173
136
  end
@@ -182,33 +145,15 @@ module Dalli
182
145
  raise '[Dalli] No request in progress. This may be a bug in Dalli.' unless @request_in_progress
183
146
 
184
147
  @request_in_progress = false
185
- # A completed request is what proves the server healthy again, so the
186
- # failure count resets here rather than on reconnect: a server that
187
- # accepts connections but never answers would otherwise reset it on
188
- # every retry and never reach socket_max_failures.
189
- @fail_count = 0
190
148
  end
191
149
 
192
150
  def abort_request!
193
151
  @request_in_progress = false
194
152
  end
195
153
 
196
- # The longest reply line Dalli reads, in bytes, CRLF included. A meta
197
- # reply header is at most about 500 bytes: "VA <size>" plus its flags,
198
- # the largest being a 250-byte key base64-encoded to 336 bytes, a
199
- # 20-digit CAS, a 32-byte opaque and a few numeric fields. The longest
200
- # stats line (stats settings) carries a file path such as ext_path, up
201
- # to PATH_MAX (4096). 8 KiB leaves room for both, while a server that
202
- # never sends CRLF can't grow the read buffer without bound.
203
- MAX_LINE_BYTES = 8 * 1024
204
-
205
154
  def read_line
206
- flush_write_buffer
207
- data = @sock.gets("\r\n", MAX_LINE_BYTES)
155
+ data = @sock.gets("\r\n")
208
156
  error_on_request!('EOF in read_line') if data.nil?
209
- # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
210
- # short by EOF; either way the connection is out of step
211
- error_on_request!("Reply line without CRLF in the first #{MAX_LINE_BYTES} bytes") unless data.end_with?("\r\n")
212
157
  data
213
158
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
214
159
  error_on_request!(e)
@@ -216,29 +161,14 @@ module Dalli
216
161
 
217
162
  # JRuby doesn't support IO#timeout=, so use custom readfull implementation
218
163
  # CRuby 3.3+ has IO#timeout= which makes IO#read work with timeouts
219
- # memcached can't store an item larger than 1 GiB (its -I maximum), so a
220
- # reply claiming more (or a negative size) is malformed or hostile.
221
- # IO#read allocates the full count up front, so check before reading.
222
- MAX_READ_BYTES = (1024 * 1024 * 1024) + 2 # plus the value's trailing "\r\n"
223
-
224
- def check_read_size!(count)
225
- return if count.between?(0, MAX_READ_BYTES)
226
-
227
- raise Dalli::DalliError, "Reply size #{count} from #{name} is out of range"
228
- end
229
-
230
164
  if RUBY_ENGINE == 'jruby'
231
165
  def read(count)
232
- check_read_size!(count)
233
- flush_write_buffer
234
166
  @sock.readfull(count)
235
167
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
236
168
  error_on_request!(e)
237
169
  end
238
170
  else
239
171
  def read(count)
240
- check_read_size!(count)
241
- flush_write_buffer
242
172
  read_bytes(count)
243
173
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, EOFError => e
244
174
  error_on_request!(e)
@@ -249,34 +179,22 @@ module Dalli
249
179
  # at the call site.
250
180
  alias read_exact read
251
181
 
252
- # Requests are buffered here rather than in the socket's own IO buffer
253
- # (the socket is sync). Ruby flushes an IO's write buffer when any process
254
- # holding it closes or finalizes the IO, so after a fork a child could
255
- # send bytes the parent had buffered but not sent yet: a quiet write would
256
- # run twice, or the parent's replies would shift onto the wrong requests.
257
- # A forked child discards this buffer instead. Like IO's own buffer, it
258
- # is sent once it grows past this size, or when a reply is read.
259
- WRITE_BUFFER_FLUSH_BYTES = 64 * 1024
260
-
261
182
  def write(bytes)
262
- @write_buffer << bytes
263
- @write_buffer_bytes += bytes.bytesize
264
- flush_write_buffer if @write_buffer_bytes >= WRITE_BUFFER_FLUSH_BYTES
265
- bytes.bytesize
183
+ @sock.write(bytes)
266
184
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
267
185
  error_on_request!(e)
268
186
  end
269
187
 
270
188
  def flush
271
- flush_write_buffer
189
+ @sock.flush
272
190
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
273
191
  error_on_request!(e)
274
192
  end
275
193
 
276
194
  def flushed_write(bytes)
277
- @write_buffer << bytes
278
- flush_write_buffer
279
- bytes.bytesize
195
+ written = @sock.write(bytes)
196
+ @sock.flush
197
+ written
280
198
  rescue SystemCallError, *TIMEOUT_ERRORS, *SSL_ERRORS, IOError => e
281
199
  error_on_request!(e)
282
200
  end
@@ -284,7 +202,6 @@ module Dalli
284
202
  # Non-blocking read. Here to support the operation
285
203
  # of the get_multi operation
286
204
  def read_available(...)
287
- flush_write_buffer
288
205
  @sock.read_available(...)
289
206
  end
290
207
 
@@ -311,9 +228,8 @@ module Dalli
311
228
  raise Dalli::RetryableNetworkError, message
312
229
  end
313
230
 
314
- # Called on connect. Deliberately leaves @fail_count alone; see
315
- # finish_request!.
316
231
  def reset_down_info
232
+ @fail_count = 0
317
233
  @down_at = nil
318
234
  @last_down_at = nil
319
235
  @msg = nil
@@ -338,8 +254,7 @@ module Dalli
338
254
  def reconnect_on_fork
339
255
  message = 'Fork detected, re-connecting child process...'
340
256
  Dalli.logger.info { message }
341
- # Drops anything the parent had buffered, closes the inherited socket
342
- # without touching the parent's connection, and reconnects immediately
257
+ # Close socket on a fork and reconnect immediately
343
258
  close
344
259
  establish_connection
345
260
  end
@@ -369,37 +284,6 @@ module Dalli
369
284
 
370
285
  private
371
286
 
372
- # One write per flush. A TLS socket sends each argument of
373
- # write(*parts) as its own record and system call, so the parts are
374
- # joined first.
375
- def flush_write_buffer
376
- return if @write_buffer.empty?
377
-
378
- @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer)
379
- discard_write_buffer
380
- end
381
-
382
- # Joined as bytes: requests can mix UTF-8 and binary strings, which
383
- # String#<< refuses to combine when both hold non-ASCII bytes
384
- if String.method_defined?(:append_as_bytes)
385
- def joined_write_buffer
386
- out = String.new(capacity: @write_buffer_bytes, encoding: Encoding::BINARY)
387
- @write_buffer.each { |part| out.append_as_bytes(part) }
388
- out
389
- end
390
- else
391
- def joined_write_buffer
392
- out = String.new(capacity: @write_buffer_bytes, encoding: Encoding::BINARY)
393
- @write_buffer.each { |part| out << part.b }
394
- out
395
- end
396
- end
397
-
398
- def discard_write_buffer
399
- @write_buffer.clear
400
- @write_buffer_bytes = 0
401
- end
402
-
403
287
  # Reads exactly `count` bytes. IO#read(count) on a blocking socket blocks
404
288
  # until it has `count` bytes, accumulating across TCP chunks internally,
405
289
  # and only hands back a shorter (or nil) buffer when the stream hits EOF.
@@ -12,8 +12,25 @@ module Dalli
12
12
  module KeyRegularizer
13
13
  module_function
14
14
 
15
+ # protocol.txt requires that a key "must not include control
16
+ # characters or whitespace" -- \p{Cntrl} is C0 (0x00-0x1F) plus DEL
17
+ # (0x7F). \s alone misses NUL and the rest of that range: a key
18
+ # containing one of those bytes but no whitespace is ASCII-only, so
19
+ # it would otherwise be written to the wire unencoded. Not a
20
+ # protocol-injection risk (the text protocol splits on CRLF, not
21
+ # other control bytes), but a downstream consumer that treats the key
22
+ # specially at one of those bytes (a C string terminating at NUL, a
23
+ # terminal or log line interpreting an escape byte) could silently
24
+ # act on a different key than Dalli believes it sent.
25
+ #
26
+ # Written as \p{Cntrl} rather than the POSIX [:cntrl:] bracket class:
27
+ # \s and [:cntrl:] overlap (tab, newline, CR are in both), and Ruby
28
+ # warns "character class has duplicated range" when they're combined
29
+ # in one -- fatal here, since this suite's -w run treats warnings as
30
+ # errors (see test_strict_warnings.rb). \p{Cntrl} matches the same
31
+ # bytes without the overlap warning.
15
32
  def required?(key)
16
- !key.ascii_only? || /\s/.match?(key)
33
+ !key.ascii_only? || /[\p{Cntrl}\s]/.match?(key)
17
34
  end
18
35
 
19
36
  def encode(key)