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.
@@ -26,22 +26,23 @@ module Dalli
26
26
  def get(key, options = nil)
27
27
  # Skip bitflags in raw mode - saves 2 bytes per request and skips parsing
28
28
  skip_flags = raw_mode? || (options && options[:raw])
29
- req = RequestFormatter.meta_get(key: key, skip_flags: skip_flags)
29
+ req = RequestFormatter.meta_get(key: key, skip_flags: skip_flags, **routing_token_kwargs(options))
30
30
  flushed_write(req)
31
- response_processor.meta_get_with_value(cache_nils: cache_nils?(options), raw: raw_request?(options))
31
+ response_processor.meta_get_with_value(cache_nils: cache_nils?(options))
32
32
  end
33
33
 
34
- def quiet_get_request(key)
34
+ def quiet_get_request(key, options = nil)
35
35
  # Skip bitflags in raw mode - saves 2 bytes per request and skips parsing
36
- RequestFormatter.meta_get(key: key, return_cas: true, quiet: true, skip_flags: raw_mode?)
36
+ RequestFormatter.meta_get(key: key, return_cas: true, quiet: true, skip_flags: raw_mode?,
37
+ **routing_token_kwargs(options))
37
38
  end
38
39
 
39
40
  def gat(key, ttl, options = nil)
40
41
  ttl = TtlSanitizer.sanitize(ttl)
41
42
  skip_flags = raw_mode? || (options && options[:raw])
42
- req = RequestFormatter.meta_get(key: key, ttl: ttl, skip_flags: skip_flags)
43
+ req = RequestFormatter.meta_get(key: key, ttl: ttl, skip_flags: skip_flags, **routing_token_kwargs(options))
43
44
  flushed_write(req)
44
- response_processor.meta_get_with_value(cache_nils: cache_nils?(options), raw: raw_request?(options))
45
+ response_processor.meta_get_with_value(cache_nils: cache_nils?(options))
45
46
  end
46
47
 
47
48
  def touch(key, ttl)
@@ -54,9 +55,9 @@ module Dalli
54
55
  # TODO: This is confusing, as there's a cas command in memcached
55
56
  # and this isn't it. Maybe rename? Maybe eliminate?
56
57
  def cas(key, options = nil)
57
- req = RequestFormatter.meta_get(key: key, value: true, return_cas: true, skip_flags: raw_request?(options))
58
+ req = RequestFormatter.meta_get(key: key, value: true, return_cas: true, **routing_token_kwargs(options))
58
59
  flushed_write(req)
59
- response_processor.meta_get_with_value_and_cas(raw: raw_request?(options))
60
+ response_processor.meta_get_with_value_and_cas
60
61
  end
61
62
 
62
63
  # Comprehensive meta get with support for all metadata flags.
@@ -85,15 +86,19 @@ module Dalli
85
86
  # - :last_access - seconds since last access (only if return_last_access: true)
86
87
  def meta_get(key, options = {})
87
88
  req = RequestFormatter.meta_get(
88
- key: key, value: true, return_cas: true, skip_flags: raw_request?(options),
89
+ key: key, value: true, return_cas: true,
89
90
  vivify_ttl: options[:vivify_ttl], recache_ttl: options[:recache_ttl],
90
91
  return_hit_status: options[:return_hit_status],
91
- return_last_access: options[:return_last_access], skip_lru_bump: options[:skip_lru_bump]
92
+ return_last_access: options[:return_last_access],
93
+ return_ttl_remaining: options[:return_ttl_remaining],
94
+ skip_lru_bump: options[:skip_lru_bump],
95
+ **routing_token_kwargs(options)
92
96
  )
93
97
  flushed_write(req)
94
98
  response_processor.meta_get_with_metadata(
95
99
  cache_nils: cache_nils?(options), return_hit_status: options[:return_hit_status],
96
- return_last_access: options[:return_last_access], raw: raw_request?(options)
100
+ return_last_access: options[:return_last_access],
101
+ return_ttl_remaining: options[:return_ttl_remaining]
97
102
  )
98
103
  end
99
104
 
@@ -137,44 +142,41 @@ module Dalli
137
142
  ttl = TtlSanitizer.sanitize(ttl) if ttl
138
143
  req = RequestFormatter.meta_set(key: key, value: value,
139
144
  bitflags: bitflags, cas: cas,
140
- ttl: ttl, mode: mode, quiet: quiet)
141
- write(request_with_value(req, value))
145
+ ttl: ttl, mode: mode, quiet: quiet,
146
+ **routing_token_kwargs(options))
147
+ write("#{req}#{value}#{TERMINATOR}")
142
148
  @connection_manager.flush unless quiet
143
149
  end
144
150
  # rubocop:enable Metrics/ParameterLists
145
151
 
146
- def append(key, value)
147
- write_append_prepend_req(:append, key, value)
152
+ def append(key, value, options = nil)
153
+ write_append_prepend_req(:append, key, value, nil, nil, options)
148
154
  response_processor.meta_set_append_prepend unless quiet?
149
155
  end
150
156
 
151
- def prepend(key, value)
152
- write_append_prepend_req(:prepend, key, value)
157
+ def prepend(key, value, options = nil)
158
+ write_append_prepend_req(:prepend, key, value, nil, nil, options)
153
159
  response_processor.meta_set_append_prepend unless quiet?
154
160
  end
155
161
 
156
- # rubocop:disable-next Metrics/ParameterLists
157
- def write_append_prepend_req(mode, key, value, ttl = nil, cas = nil, _options = {})
162
+ # rubocop:disable Metrics/ParameterLists
163
+ def write_append_prepend_req(mode, key, value, ttl = nil, cas = nil, options = nil)
158
164
  ttl = TtlSanitizer.sanitize(ttl) if ttl
159
165
  req = RequestFormatter.meta_set(key: key, value: value,
160
- cas: cas, ttl: ttl, mode: mode, quiet: quiet?)
161
- write(request_with_value(req, value))
166
+ cas: cas, ttl: ttl, mode: mode, quiet: quiet?,
167
+ **routing_token_kwargs(options))
168
+ write("#{req}#{value}#{TERMINATOR}")
162
169
  @connection_manager.flush unless quiet?
163
170
  end
164
-
165
- # Ruby refuses to join Strings whose encodings clash, such as a raw
166
- # UTF-16 value next to the ASCII request line. memcached stores bytes,
167
- # so join the bytes then. Joining the Strings first keeps the common
168
- # case free of extra checks.
169
- def request_with_value(req, value)
170
- "#{req}#{value}#{TERMINATOR}"
171
- rescue Encoding::CompatibilityError
172
- "#{req.b}#{value.b}#{TERMINATOR}"
173
- end
171
+ # rubocop:enable Metrics/ParameterLists
174
172
 
175
173
  # Delete Commands
176
- def delete(key, cas)
177
- req = RequestFormatter.meta_delete(key: key, cas: cas, quiet: quiet?)
174
+ #
175
+ # `options` supports the meta-delete keys :invalidate, :tombstone_ttl and
176
+ # :drop_value, plus :p_token/:l_token; see Dalli::Client#delete.
177
+ def delete(key, cas, options = nil)
178
+ req = RequestFormatter.meta_delete(key: key, cas: cas, quiet: quiet?,
179
+ **tombstone_kwargs(options), **routing_token_kwargs(options))
178
180
  write(req)
179
181
  @connection_manager.flush unless quiet?
180
182
  response_processor.meta_delete unless quiet?
@@ -182,8 +184,9 @@ module Dalli
182
184
 
183
185
  # Pipelined delete - writes a quiet delete request without reading response.
184
186
  # Used by PipelinedDeleter for bulk operations.
185
- def pipelined_delete(key)
186
- req = RequestFormatter.meta_delete(key: key, quiet: true)
187
+ def pipelined_delete(key, req_options = nil)
188
+ req = RequestFormatter.meta_delete(key: key, quiet: true,
189
+ **tombstone_kwargs(req_options), **routing_token_kwargs(req_options))
187
190
  write(req)
188
191
  end
189
192
 
@@ -193,53 +196,23 @@ module Dalli
193
196
  end
194
197
 
195
198
  # Arithmetic Commands
196
- def decr(key, count, ttl, initial)
197
- decr_incr false, key, count, ttl, initial
199
+ def decr(key, count, ttl, initial, options = nil)
200
+ decr_incr false, key, count, ttl, initial, options
198
201
  end
199
202
 
200
- def incr(key, count, ttl, initial)
201
- decr_incr true, key, count, ttl, initial
203
+ def incr(key, count, ttl, initial, options = nil)
204
+ decr_incr true, key, count, ttl, initial, options
202
205
  end
203
206
 
204
- def decr_incr(incr, key, delta, ttl, initial)
207
+ # rubocop:disable Metrics/ParameterLists
208
+ def decr_incr(incr, key, delta, ttl, initial, options = nil)
205
209
  ttl = initial ? TtlSanitizer.sanitize(ttl) : nil # Only set a TTL if we want to set a value on miss
206
- # memcached stores an item created by ma's auto-create (N/J) for a
207
- # base64-encoded key without its binary-key flag, and later replies
208
- # name it with the raw key bytes. Create such counters with an add.
209
- return decr_incr_with_add(incr, key, delta, ttl, initial) if initial && KeyRegularizer.required?(key)
210
-
211
210
  write(RequestFormatter.meta_arithmetic(key: key, delta: delta, initial: initial, incr: incr, ttl: ttl,
212
- quiet: quiet?))
211
+ quiet: quiet?, **routing_token_kwargs(options)))
213
212
  @connection_manager.flush unless quiet?
214
213
  response_processor.decr_incr unless quiet?
215
214
  end
216
-
217
- # Like decr_incr with an initial value, without memcached's auto-create:
218
- # on a miss the counter is added with the initial value (which is
219
- # returned, as auto-create would), and the add losing a race to another
220
- # client means the counter now exists, so the incr is tried again. In a
221
- # quiet block both requests are sent and whichever applies takes effect.
222
- def decr_incr_with_add(incr, key, delta, ttl, initial)
223
- add_options = { raw: true } # counters are stored raw
224
- return quiet_decr_incr_with_add(incr, key, delta, ttl, initial, add_options) if quiet?
225
-
226
- 2.times do
227
- value = decr_incr(incr, key, delta, nil, nil)
228
- return value unless value.nil?
229
-
230
- write_storage_req(:add, key, initial.to_s, ttl, nil, add_options, quiet: false)
231
- return initial if response_processor.meta_set_with_cas
232
- end
233
- decr_incr(incr, key, delta, nil, nil)
234
- end
235
-
236
- # rubocop:disable-next Metrics/ParameterLists
237
- def quiet_decr_incr_with_add(incr, key, delta, ttl, initial, add_options)
238
- write(RequestFormatter.meta_arithmetic(key: key, delta: delta, initial: nil, incr: incr, ttl: nil,
239
- quiet: true))
240
- # Sent with the rest of the quiet block, by its closing noop
241
- write_storage_req(:add, key, initial.to_s, ttl, nil, add_options, quiet: true)
242
- end
215
+ # rubocop:enable Metrics/ParameterLists
243
216
 
244
217
  # Other Commands
245
218
  def flush(delay = 0)
@@ -252,10 +225,7 @@ module Dalli
252
225
  # We need to read all the responses at once.
253
226
  def noop
254
227
  write_noop
255
- result = response_processor.consume_all_responses_until_mn
256
- # Everything up to and including the MN has been read
257
- @connection_manager.clear_quiet_responses_pending!
258
- result
228
+ response_processor.consume_all_responses_until_mn
259
229
  end
260
230
 
261
231
  def stats(info = nil)
@@ -280,16 +250,53 @@ module Dalli
280
250
  # Single-server fast path for get_multi. Inlines request formatting and
281
251
  # response parsing to minimize per-key overhead. Avoids the PipelinedGetter
282
252
  # machinery (IO.select, response buffering, server grouping).
283
- def read_multi_req(keys)
253
+ def read_multi_req(keys, options = nil)
284
254
  is_raw = raw_mode?
285
- buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw)
255
+ buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw, **routing_token_kwargs(options))
286
256
  flushed_write(buffer)
287
257
  buffer.clear
288
- read_multi_get_responses(is_raw, keys)
258
+ read_multi_get_responses(is_raw)
289
259
  end
290
260
 
291
- def read_multi_get_responses(is_raw, keys)
292
- expect_reply_keys(keys)
261
+ # Stale-aware bulk get. Returns { key => { value:, cas:, stale:, miss: } }
262
+ # for the keys the server returned. Keys that were not found are absent
263
+ # from the hash, matching read_multi_req and the get_multi family; a
264
+ # tombstoned item is present (it answers VA with the X flag) with
265
+ # stale: true, which is the distinction callers need.
266
+ #
267
+ # Shared by both the single-server fast path and PipelinedGetter's
268
+ # per-server-group request, so this one change covers both routes.
269
+ def read_multi_with_metadata_req(keys, options = nil)
270
+ is_raw = raw_mode?
271
+ buffer = RequestFormatter.multi_meta_get(keys, skip_flags: is_raw, return_cas: true,
272
+ **routing_token_kwargs(options))
273
+ flushed_write(buffer)
274
+ buffer.clear
275
+ read_multi_metadata_responses(is_raw)
276
+ end
277
+
278
+ # Unlike read_multi_get_responses this locates tokens by flag rather than
279
+ # by position, because the c flag shifts the key's index.
280
+ def read_multi_metadata_responses(is_raw)
281
+ hash = {}
282
+ while (line = @connection_manager.read_line)
283
+ break if line.start_with?('MN')
284
+ next unless line.start_with?('VA ')
285
+
286
+ tokens = line.chomp!(TERMINATOR).split
287
+ value = @connection_manager.read(tokens[1].to_i + TERMINATOR.bytesize)&.chomp!(TERMINATOR)
288
+ stale = response_processor.stale_from_tokens(tokens)
289
+ cas = response_processor.cas_from_tokens(tokens)
290
+ bitflags = is_raw ? 0 : response_processor.bitflags_from_tokens(tokens)
291
+ key = response_processor.key_from_tokens(tokens)
292
+ next if key.nil?
293
+
294
+ hash[key] = { value: @value_marshaller.retrieve(value, bitflags), cas: cas, stale: stale, miss: false }
295
+ end
296
+ hash
297
+ end
298
+
299
+ def read_multi_get_responses(is_raw)
293
300
  hash = {}
294
301
  key_index = is_raw ? 2 : 3
295
302
  while (line = @connection_manager.read_line)
@@ -297,24 +304,14 @@ module Dalli
297
304
  next unless line.start_with?('VA ')
298
305
 
299
306
  key, value = parse_multi_get_value(line, key_index, is_raw)
300
- raise_unexpected_reply_key(key) if unexpected_reply_key?(key)
301
307
  hash[key] = value if key
302
308
  end
303
309
  hash
304
310
  end
305
311
 
306
- # The replies after a key that wasn't requested can't be trusted (see
307
- # Base#expect_reply_keys). Raising ends the request, which closes the
308
- # connection; the caller treats this server's keys as missing.
309
- def raise_unexpected_reply_key(key)
310
- raise Dalli::UnexpectedReplyKeyError, "#{name} replied with a key that wasn't requested: #{key.inspect}"
311
- end
312
-
313
312
  def parse_multi_get_value(line, key_index, is_raw)
314
313
  tokens = line.chomp!(TERMINATOR).split
315
- size = tokens[1].to_i
316
- response_processor.check_value_size!(size)
317
- value = @connection_manager.read(size + TERMINATOR.bytesize)&.chomp!(TERMINATOR)
314
+ value = @connection_manager.read(tokens[1].to_i + TERMINATOR.bytesize)&.chomp!(TERMINATOR)
318
315
  raw_key = tokens[key_index]
319
316
  return unless raw_key
320
317
 
@@ -326,33 +323,23 @@ module Dalli
326
323
 
327
324
  # Single-server fast path for set_multi. Inlines request formatting to
328
325
  # minimize per-key overhead. Avoids PipelinedSetter server grouping.
329
- #
330
- # A value that can't be marshalled or is over value_max_bytes is skipped;
331
- # the other keys are still stored, then the first such error is raised
332
- # (as PipelinedSetter does on the multi-server path).
333
326
  def write_multi_req(pairs, ttl, req_options)
334
327
  ttl = TtlSanitizer.sanitize(ttl) if ttl
335
- value_error = nil
336
- entries = pairs.filter_map do |key, raw_value|
328
+ entries = pairs.map do |key, raw_value|
337
329
  [key, @value_marshaller.store(key, raw_value, req_options)]
338
- rescue Dalli::MarshalError, Dalli::ValueOverMaxSize => e
339
- value_error ||= e
340
- nil
341
330
  end
342
331
 
343
- unless entries.empty?
344
- buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl)
345
- flushed_write(buffer)
346
- buffer.clear
347
- response_processor.consume_all_responses_until_mn
348
- end
349
- raise value_error if value_error
332
+ buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl, **routing_token_kwargs(req_options))
333
+ flushed_write(buffer)
334
+ buffer.clear
335
+ response_processor.consume_all_responses_until_mn
350
336
  end
351
337
 
352
338
  # Single-server fast path for delete_multi. Writes all quiet delete requests
353
339
  # terminated by a noop, then consumes all responses.
354
- def delete_multi_req(keys)
355
- buffer = RequestFormatter.multi_meta_delete(keys)
340
+ def delete_multi_req(keys, req_options = nil)
341
+ buffer = RequestFormatter.multi_meta_delete(keys, **tombstone_kwargs(req_options),
342
+ **routing_token_kwargs(req_options))
356
343
  flushed_write(buffer)
357
344
  buffer.clear
358
345
  keys.size - response_processor.pipelined_delete_non_deletions
@@ -36,28 +36,40 @@ module Dalli
36
36
  # - l<N>: Seconds since last access
37
37
  def meta_get(key:, value: true, return_cas: false, ttl: nil, quiet: false,
38
38
  vivify_ttl: nil, recache_ttl: nil,
39
- return_hit_status: false, return_last_access: false, skip_lru_bump: false,
40
- skip_flags: false)
39
+ return_hit_status: false, return_last_access: false, return_ttl_remaining: false,
40
+ skip_lru_bump: false, skip_flags: false, p_token: nil, l_token: nil)
41
41
  cmd = "mg #{encoded_key(key)}"
42
42
  # In raw mode (skip_flags: true), we don't request bitflags since they're not used.
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}" if ttl
47
+ cmd << routing_tokens(p_token: p_token, l_token: l_token)
47
48
  cmd << ' k q s' if quiet # Return the key in the response if quiet
48
- cmd << " N#{integer_flag(:vivify_ttl, vivify_ttl)}" if vivify_ttl # Thundering herd: vivify on miss
49
- # Thundering herd: win recache if TTL below threshold
50
- cmd << " R#{integer_flag(:recache_ttl, recache_ttl)}" if recache_ttl
49
+ cmd << " N#{vivify_ttl}" if vivify_ttl # Thundering herd: vivify on miss
50
+ cmd << " R#{recache_ttl}" if recache_ttl # Thundering herd: win recache if TTL below threshold
51
51
  cmd << ' h' if return_hit_status # Return hit status (0 or 1)
52
52
  cmd << ' l' if return_last_access # Return seconds since last access
53
+ cmd << ' t' if return_ttl_remaining # Return seconds of TTL remaining (-1 = no TTL)
53
54
  cmd << ' u' if skip_lru_bump # Don't bump LRU or update access stats
54
55
  cmd << TERMINATOR
55
56
  end
56
57
 
57
- def multi_meta_get(keys, skip_flags: false)
58
+ def multi_meta_get(keys, skip_flags: false, return_cas: false, p_token: nil, l_token: nil)
58
59
  # In raw mode: "mg <key> v k q s\r\n" (no f flag, key at index 2)
59
60
  # Normal mode: "mg <key> v f k q s\r\n" (key at index 3)
60
- post_get = skip_flags ? " v k q s\r\n" : " v f k q s\r\n"
61
+ # With return_cas a "c" flag follows, which shifts those indexes --
62
+ # callers of that variant locate tokens by flag rather than position.
63
+ # Routing tokens apply to every key in the batch, so the suffix is
64
+ # built once rather than per key.
65
+ post_get = if return_cas
66
+ skip_flags ? ' v c' : ' v f c'
67
+ else
68
+ skip_flags ? ' v' : ' v f'
69
+ end
70
+ post_get += routing_tokens(p_token: p_token, l_token: l_token)
71
+ post_get += " k q s#{TERMINATOR}"
72
+
61
73
  buffer = ''.b
62
74
  keys.each do |key|
63
75
  buffer << 'mg ' << encoded_key(key) << post_get
@@ -65,7 +77,8 @@ module Dalli
65
77
  buffer << 'mn' << TERMINATOR
66
78
  end
67
79
 
68
- def meta_set(key:, value:, bitflags: nil, cas: nil, ttl: nil, mode: :set, quiet: false)
80
+ def meta_set(key:, value:, bitflags: nil, cas: nil, ttl: nil, mode: :set, quiet: false,
81
+ p_token: nil, l_token: nil)
69
82
  base64 = KeyRegularizer.required?(key)
70
83
  key = KeyRegularizer.encode(key) if base64
71
84
  cmd = "ms #{key} #{value.bytesize}"
@@ -75,14 +88,18 @@ module Dalli
75
88
  cmd << ' b' if base64
76
89
  cmd << " F#{bitflags}" if bitflags
77
90
  cmd << cas_string(cas)
78
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
91
+ cmd << " T#{ttl}" if ttl
79
92
  cmd << " M#{mode_to_token(mode)}"
80
93
  cmd << ' q' if quiet
94
+ cmd << routing_tokens(p_token: p_token, l_token: l_token)
81
95
  cmd << TERMINATOR
82
96
  end
83
97
 
84
- def multi_meta_set(entries, ttl: nil)
85
- ttl = integer_flag(:ttl, ttl) if ttl
98
+ def multi_meta_set(entries, ttl: nil, p_token: nil, l_token: nil)
99
+ # Routing tokens apply to every entry in the batch, so the suffix is
100
+ # built once rather than per entry.
101
+ token_suffix = routing_tokens(p_token: p_token, l_token: l_token)
102
+
86
103
  buffer = ''.b
87
104
  entries.each do |key, pair|
88
105
  value, bitflags = pair
@@ -90,65 +107,109 @@ module Dalli
90
107
  base64 = KeyRegularizer.required?(key)
91
108
  key = KeyRegularizer.encode(key) if base64
92
109
 
93
- # Inline format: "ms <key> <size> c [b] F<flags> T<ttl> MS q\r\n"
110
+ # Inline format: "ms <key> <size> c [b] F<flags> T<ttl> MS q [P/L]\r\n"
94
111
  buffer << "ms #{key} #{value.bytesize} c"
95
112
  buffer << ' b' if base64
96
113
  buffer << " F#{bitflags}" if bitflags
97
114
  buffer << " T#{ttl}" if ttl
98
- buffer << ' MS q' << TERMINATOR
99
- append_bytes(buffer, value)
100
- buffer << TERMINATOR
115
+ buffer << ' MS q' << token_suffix << TERMINATOR << value << TERMINATOR
101
116
  end
102
117
  buffer << META_NOOP
103
118
  end
104
119
 
105
- # Values are appended as bytes. One batch can hold UTF-8 and binary
106
- # values, which String#<< refuses to combine, and a raw value can be in
107
- # an encoding that isn't ASCII-compatible, such as UTF-16.
108
- # Don't chain on the result: TruffleRuby's append_as_bytes returns its
109
- # arguments rather than the buffer.
110
- if String.method_defined?(:append_as_bytes)
111
- def append_bytes(buffer, value)
112
- buffer.append_as_bytes(value)
113
- end
114
- else
115
- def append_bytes(buffer, value)
116
- buffer << (value.encoding == Encoding::BINARY ? value : value.b)
117
- end
118
- end
119
- private :append_bytes
120
-
121
120
  # Thundering herd protection flag:
122
121
  # - stale (I flag): Instead of deleting the item, mark it as stale. Other clients
123
122
  # using N/R flags will see the X flag and know the item is being regenerated.
124
- def meta_delete(key:, cas: nil, ttl: nil, quiet: false, stale: false)
123
+ # Tombstone flags:
124
+ # - stale (I flag): mark the item stale instead of removing it. Readers
125
+ # using N/R flags, or get_with_metadata, see the X flag and know the
126
+ # item is being regenerated.
127
+ # - ttl (T flag): how long the stale marker lives. memcached only honors
128
+ # T on a delete when it is paired with I, so this raises rather than
129
+ # emitting a request the server would apply differently than intended.
130
+ # - drop_value (x flag): remove the item's value but leave the item, so a
131
+ # tombstone can be left without retaining the old payload.
132
+ def meta_delete(key:, cas: nil, ttl: nil, quiet: false, stale: false, drop_value: false,
133
+ p_token: nil, l_token: nil)
134
+ # Message uses this method's own parameter names (ttl/stale), not the
135
+ # client-facing tombstone_ttl/invalidate names Dalli::Client validates
136
+ # against -- this guard is also reachable by internal callers (tests,
137
+ # direct RequestFormatter use) that never go through the client.
138
+ raise ArgumentError, 'ttl requires stale: true' if ttl && !stale
139
+
125
140
  cmd = "md #{encoded_key(key)}"
126
141
  cmd << cas_string(cas)
127
- cmd << " T#{integer_flag(:ttl, ttl)}" if ttl
128
142
  cmd << ' I' if stale # Mark stale instead of deleting
143
+ cmd << " T#{Integer(ttl)}" if ttl
144
+ cmd << ' x' if drop_value # Drop the value but keep the item
129
145
  cmd << ' q' if quiet
146
+ cmd << routing_tokens(p_token: p_token, l_token: l_token)
130
147
  cmd << TERMINATOR
131
148
  end
132
149
 
133
- def multi_meta_delete(keys)
150
+ # Tombstone and routing-token flags apply to every key in the batch;
151
+ # see meta_delete.
152
+ def multi_meta_delete(keys, stale: false, ttl: nil, drop_value: false, p_token: nil, l_token: nil)
153
+ raise ArgumentError, 'tombstone_ttl requires invalidate: true' if ttl && !stale
154
+
155
+ suffix = +''
156
+ suffix << ' I' if stale
157
+ suffix << " T#{Integer(ttl)}" if ttl
158
+ suffix << ' x' if drop_value
159
+ suffix << ' q'
160
+ suffix << routing_tokens(p_token: p_token, l_token: l_token)
161
+ suffix << TERMINATOR
162
+
134
163
  buffer = ''.b
135
164
  keys.each do |key|
136
- buffer << 'md ' << encoded_key(key) << ' q' << TERMINATOR
165
+ buffer << 'md ' << encoded_key(key) << suffix
137
166
  end
138
167
  buffer << META_NOOP
139
168
  end
140
169
 
141
- def meta_arithmetic(key:, delta:, initial:, incr: true, cas: nil, ttl: nil, quiet: false)
170
+ def meta_arithmetic(key:, delta:, initial:, incr: true, cas: nil, ttl: nil, quiet: false,
171
+ p_token: nil, l_token: nil)
142
172
  cmd = "ma #{encoded_key(key)} v"
143
- cmd << " D#{integer_flag(:delta, delta)}" if delta
144
- cmd << " J#{integer_flag(:initial, initial)}" if initial
173
+ cmd << " D#{delta}" if delta
174
+ cmd << " J#{initial}" if initial
145
175
  # Always set a TTL if an initial value is specified
146
- cmd << " N#{ttl ? integer_flag(:ttl, ttl) : 0}" if ttl || initial
176
+ cmd << " N#{ttl || 0}" if ttl || initial
147
177
  cmd << cas_string(cas)
148
178
  cmd << ' q' if quiet
149
179
  cmd << " M#{incr ? 'I' : 'D'}"
180
+ cmd << routing_tokens(p_token: p_token, l_token: l_token)
150
181
  cmd << TERMINATOR
151
182
  end
183
+
184
+ # Builds the wire-format suffix for opaque routing tokens (P and L).
185
+ # memcached itself ignores these; they exist as hints for a proxy or
186
+ # router sitting between the client and memcached. See protocol.txt:
187
+ # "All commands accept tokens 'P' and 'L' which are completely ignored.
188
+ # The arguments to 'P' and 'L' can be used as hints or path
189
+ # specifications to a proxy or router inbetween a client and a
190
+ # memcached daemon."
191
+ #
192
+ # Empty / nil tokens are treated as no-ops. CRLF and null bytes are
193
+ # rejected with ArgumentError to prevent the token from being used as a
194
+ # wire-protocol injection vector (e.g. "foo\r\nflush_all\r\n" would
195
+ # otherwise be parsed as a second command by memcached or any
196
+ # intermediate proxy/LB).
197
+ def routing_tokens(p_token: nil, l_token: nil)
198
+ # Only an empty *String* is a no-op. Checking respond_to?(:empty?)
199
+ # instead would also swallow p_token: [] / {} before the type check
200
+ # below ever runs, silently dropping caller mistakes that should
201
+ # raise "must be a String".
202
+ p_token = nil if p_token.is_a?(String) && p_token.empty?
203
+ l_token = nil if l_token.is_a?(String) && l_token.empty?
204
+ validate_routing_token!('p_token', p_token)
205
+ validate_routing_token!('l_token', l_token)
206
+ return '' unless p_token || l_token
207
+
208
+ s = +''
209
+ s << " P#{p_token}" if p_token
210
+ s << " L#{l_token}" if l_token
211
+ s
212
+ end
152
213
  # rubocop:enable Metrics/CyclomaticComplexity
153
214
  # rubocop:enable Metrics/ParameterLists
154
215
  # rubocop:enable Metrics/PerceivedComplexity
@@ -189,16 +250,15 @@ module Dalli
189
250
 
190
251
  private
191
252
 
192
- # Numeric flag values are written straight into the command line, so a
193
- # value that isn't an integer -- e.g. a String carrying CRLF -- would let
194
- # the caller inject further memcached commands (GHSA-6wmv-xq9m-fmp7).
195
- # Converting to Integer means only digits ever reach the wire. Strings
196
- # are parsed as base 10 so "010" means 10, as memcached would read it,
197
- # rather than octal 8.
198
- def integer_flag(name, value)
199
- value.is_a?(String) ? Integer(value, 10) : Integer(value)
200
- rescue ArgumentError, TypeError, FloatDomainError
201
- raise ArgumentError, "#{name} must be an Integer, got #{value.inspect}"
253
+ # Disallowed bytes: CR, LF, NUL. Any of these embedded in a routing
254
+ # token would let the caller inject a second wire-protocol command.
255
+ ROUTING_TOKEN_FORBIDDEN = /[\r\n\0]/
256
+ private_constant :ROUTING_TOKEN_FORBIDDEN
257
+
258
+ def validate_routing_token!(name, value)
259
+ return if value.nil?
260
+ raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
261
+ raise ArgumentError, "#{name} must not contain CRLF or null bytes" if value.match?(ROUTING_TOKEN_FORBIDDEN)
202
262
  end
203
263
 
204
264
  def mode_to_token(mode)