dalli 5.0.16 → 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.
@@ -13,54 +13,8 @@ module Dalli
13
13
  Zlib::Deflate.deflate(data)
14
14
  end
15
15
 
16
- # DEFLATE can't expand data by more than about 1032:1
17
- MAX_EXPANSION = 1032
18
- # Compressed input is fed to zlib this many bytes at a time. MRI's zlib
19
- # yields the output in small chunks; one that returns it instead still
20
- # produces at most MAX_EXPANSION times this per step.
21
- INFLATE_SLICE_BYTES = 64 * 1024
22
-
23
- # max_bytes caps the decompressed size; inflating stops and raises as soon
24
- # as the output passes it, so a small compressed value can't expand into
25
- # gigabytes of memory.
26
- def self.decompress(data, max_bytes: nil)
27
- return Zlib::Inflate.inflate(data) unless may_exceed?(data, max_bytes)
28
-
29
- inflate_within_limit(Zlib::Inflate.new, data, max_bytes)
30
- end
31
-
32
- # False when even the largest possible expansion stays within max_bytes,
33
- # so the value can be inflated in one step
34
- def self.may_exceed?(data, max_bytes)
35
- max_bytes ? data.bytesize * MAX_EXPANSION > max_bytes : false
36
- end
37
-
38
- def self.inflate_within_limit(inflater, data, max_bytes)
39
- out = String.new(encoding: Encoding::BINARY)
40
- 0.step(data.bytesize - 1, INFLATE_SLICE_BYTES) do |pos|
41
- inflate_slice(inflater, data.byteslice(pos, INFLATE_SLICE_BYTES), out, max_bytes)
42
- # Anything after the end of the stream isn't part of the value, as
43
- # with Zlib::Inflate.inflate; finish would return it as output
44
- break if inflater.finished?
45
- end
46
- return out if inflater.finished?
47
-
48
- append_within_limit(out, inflater.finish, max_bytes)
49
- ensure
50
- inflater.close
51
- end
52
-
53
- # Both yielded and returned output count toward the limit
54
- def self.inflate_slice(inflater, slice, out, max_bytes)
55
- rest = inflater.inflate(slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
56
- append_within_limit(out, rest, max_bytes)
57
- end
58
-
59
- def self.append_within_limit(out, chunk, max_bytes)
60
- out << chunk if chunk
61
- return out if out.bytesize <= max_bytes
62
-
63
- raise Dalli::UnmarshalError, "Decompressed value exceeds #{max_bytes} bytes (decompressed_max_bytes)"
16
+ def self.decompress(data)
17
+ Zlib::Inflate.inflate(data)
64
18
  end
65
19
  end
66
20
 
@@ -78,11 +32,9 @@ module Dalli
78
32
  io.string
79
33
  end
80
34
 
81
- def self.decompress(data, max_bytes: nil)
82
- return Zlib::GzipReader.new(StringIO.new(data, 'rb')).read unless Compressor.may_exceed?(data, max_bytes)
83
-
84
- # MAX_WBITS + 16 makes zlib read the gzip format (and check its CRC)
85
- Compressor.inflate_within_limit(Zlib::Inflate.new(Zlib::MAX_WBITS + 16), data, max_bytes)
35
+ def self.decompress(data)
36
+ io = StringIO.new(data, 'rb')
37
+ Zlib::GzipReader.new(io).read
86
38
  end
87
39
  end
88
40
  end
@@ -58,7 +58,7 @@ module Dalli
58
58
  raise ArgumentError, 'key cannot be blank' unless key&.length&.positive?
59
59
 
60
60
  key = key_with_namespace(key)
61
- wire_length(key) > MAX_KEY_LENGTH ? truncated_key(key) : key
61
+ key.length > MAX_KEY_LENGTH ? truncated_key(key) : key
62
62
  end
63
63
 
64
64
  ##
@@ -122,28 +122,7 @@ module Dalli
122
122
  ##
123
123
  def truncated_key(key)
124
124
  digest = digest_class.hexdigest(key)
125
- prefix = key[0, [prefix_length(digest), 0].max]
126
- truncated = "#{prefix}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
127
- # A prefix with whitespace or non-ASCII characters sends the whole key
128
- # base64-encoded, which can still be too long on the wire; shorten it.
129
- while wire_length(truncated) > MAX_KEY_LENGTH && !prefix.empty?
130
- prefix = prefix[0...-1]
131
- truncated = "#{prefix}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
132
- end
133
- return truncated if wire_length(truncated) <= MAX_KEY_LENGTH
134
-
135
- # Only possible with a digest_class whose digests aren't short hex strings
136
- raise ArgumentError, "#{digest_class} digests are too long to fit in a truncated key"
137
- end
138
-
139
- # memcached's key limit applies to the key as sent: in bytes, and after
140
- # base64 encoding when the key needs it. A key can be within the limit in
141
- # characters and still be rejected, and memcached's CLIENT_ERROR for it
142
- # must never reach a pipelined get.
143
- def wire_length(key)
144
- return key.bytesize unless Dalli::Protocol::Meta::KeyRegularizer.required?(key)
145
-
146
- ((key.bytesize + 2) / 3) * 4
125
+ "#{key[0, prefix_length(digest)]}#{TRUNCATED_KEY_SEPARATOR}#{digest}"
147
126
  end
148
127
 
149
128
  def prefix_length(digest)
data/lib/dalli/options.rb CHANGED
@@ -43,7 +43,7 @@ module Dalli
43
43
  end
44
44
  end
45
45
 
46
- def pipeline_abort(...)
46
+ def pipeline_abort
47
47
  @lock.synchronize do
48
48
  super
49
49
  end
@@ -15,17 +15,24 @@ module Dalli
15
15
  ##
16
16
  # Deletes multiple keys from memcached.
17
17
  #
18
+ # `req_options` is applied to every delete in the batch (see
19
+ # Dalli::Client#delete for the supported meta-delete keys).
20
+ #
18
21
  # @param keys [Array<String>] keys to delete
19
- # @return [Integer] the number of keys that were deleted. This is
20
- # best-effort: on a network error the operation is retried, and keys
21
- # deleted before the error are not recounted, so the result may
22
- # under-report the number actually removed when a failure occurs.
22
+ # @return [Integer] the number of keys the server found and acted on. Only
23
+ # a key that did not exist decrements this count, so with
24
+ # `req_options: {invalidate: true}` it reports how many keys were
25
+ # tombstoned rather than removed. This is best-effort: a transient
26
+ # network error is retried automatically, and keys handled before the
27
+ # error are not recounted, so the result may under-report when a retry
28
+ # occurs. If a server remains unreachable after retrying, raises
29
+ # Dalli::NetworkError.
23
30
  ##
24
- def process(keys)
31
+ def process(keys, req_options = nil)
25
32
  return 0 if keys.empty?
26
33
 
27
34
  @ring.lock do
28
- groups = setup_requests(keys)
35
+ groups = setup_requests(keys, req_options)
29
36
  finish_requests(groups)
30
37
  end
31
38
  rescue Dalli::RetryableNetworkError => e
@@ -36,9 +43,9 @@ module Dalli
36
43
 
37
44
  private
38
45
 
39
- def setup_requests(keys)
46
+ def setup_requests(keys, req_options = nil)
40
47
  groups = groups_for_keys(keys)
41
- make_delete_requests(groups)
48
+ make_delete_requests(groups, req_options)
42
49
  groups
43
50
  end
44
51
 
@@ -46,12 +53,20 @@ module Dalli
46
53
  # Loop through the server-grouped sets of keys, writing
47
54
  # the corresponding quiet delete requests to the appropriate servers
48
55
  ##
49
- def make_delete_requests(groups)
56
+ # NetworkError (which RetryableNetworkError subclasses) must propagate: the
57
+ # top-level rescue in #process retries the whole pipelined delete on it. A
58
+ # combined `rescue DalliError, NetworkError` would silently swallow
59
+ # RetryableNetworkError too -- since NetworkError < DalliError -- dropping
60
+ # this server's keys on a transient hiccup instead of retrying. Only a
61
+ # non-network DalliError should be swallowed here.
62
+ def make_delete_requests(groups, req_options = nil)
50
63
  groups.each do |server, keys_for_server|
51
64
  keys_for_server.select! do |key|
52
- server.request(:pipelined_delete, key)
65
+ server.request(:pipelined_delete, key, req_options)
53
66
  true
54
- rescue DalliError, NetworkError => e
67
+ rescue Dalli::NetworkError
68
+ raise
69
+ rescue DalliError => e
55
70
  Dalli.logger.debug { e.inspect }
56
71
  Dalli.logger.debug { "unable to delete key #{key} for server #{server.name}" }
57
72
  false
@@ -66,7 +81,9 @@ module Dalli
66
81
  def finish_requests(groups)
67
82
  groups.sum do |server, keys_for_server|
68
83
  server.request(:finish_pipelined_delete, keys_for_server.size)
69
- rescue DalliError, NetworkError => e
84
+ rescue Dalli::NetworkError
85
+ raise
86
+ rescue DalliError => e
70
87
  Dalli.logger.debug { e.inspect }
71
88
  Dalli.logger.debug { "unable to complete pipelined delete on server #{server.name}" }
72
89
  0
@@ -20,25 +20,24 @@ module Dalli
20
20
  ##
21
21
  # Yields, one at a time, keys and their values+attributes.
22
22
  #
23
- def process(keys, &block)
23
+ # `req_options` accepts :p_token/:l_token, applied to every key in the batch.
24
+ #
25
+ # A transient network error is retried automatically. If a server remains
26
+ # unreachable after retrying, raises Dalli::NetworkError.
27
+ #
28
+ def process(keys, req_options = nil, &block)
24
29
  return {} if keys.empty?
25
30
 
26
31
  @ring.lock do
27
- # The servers with replies still to read, updated in place
28
- servers = []
29
- begin
30
- # Stores partial results collected during interleaved send phase
31
- @partial_results = {}
32
- setup_requests(servers, keys)
33
- start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
32
+ # Stores partial results collected during interleaved send phase
33
+ @partial_results = {}
34
+ servers = setup_requests(keys, req_options)
35
+ start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
34
36
 
35
- # First yield any partial results collected during interleaved send
36
- yield_partial_results(&block)
37
+ # First yield any partial results collected during interleaved send
38
+ yield_partial_results(&block)
37
39
 
38
- fetch_responses(servers, start_time, @ring.socket_timeout, &block) until servers.empty?
39
- ensure
40
- abort_unfinished(servers)
41
- end
40
+ servers = fetch_responses(servers, start_time, @ring.socket_timeout, &block) until servers.empty?
42
41
  end
43
42
  rescue Dalli::RetryableNetworkError => e
44
43
  Dalli.logger.debug { e.inspect }
@@ -46,6 +45,40 @@ module Dalli
46
45
  retry
47
46
  end
48
47
 
48
+ ##
49
+ # Stale-aware bulk get across servers. Returns { key => metadata Hash } for
50
+ # the keys that were found; see Protocol::Meta#read_multi_with_metadata_req
51
+ # for why misses are absent rather than present with miss: true.
52
+ #
53
+ # Unlike #process this issues one request per server and reads its full
54
+ # response before moving on, rather than pipelining across servers: the
55
+ # metadata path has no interleaving support, and the stale-aware callers it
56
+ # serves fetch far smaller batches than get_multi does.
57
+ #
58
+ # `req_options` accepts :p_token/:l_token, applied to every key in the batch.
59
+ #
60
+ def process_with_metadata(keys, req_options = nil)
61
+ return {} if keys.empty?
62
+
63
+ @ring.lock do
64
+ results = {}
65
+ groups_for_keys(keys).each do |server, keys_for_server|
66
+ results.merge!(server.request(:read_multi_with_metadata_req, keys_for_server, req_options))
67
+ rescue Dalli::RetryableNetworkError
68
+ raise
69
+ rescue DalliError, NetworkError => e
70
+ Dalli.logger.debug { e.inspect }
71
+ Dalli.logger.debug { "unable to get keys for server #{server.name}" }
72
+ end
73
+ results.transform_keys! { |key| @key_manager.key_without_namespace(key) }
74
+ results
75
+ end
76
+ rescue Dalli::RetryableNetworkError => e
77
+ Dalli.logger.debug { e.inspect }
78
+ Dalli.logger.debug { 'retrying pipelined get with metadata because of network error' }
79
+ retry
80
+ end
81
+
49
82
  private
50
83
 
51
84
  def yield_partial_results
@@ -55,15 +88,12 @@ module Dalli
55
88
  @partial_results.clear
56
89
  end
57
90
 
58
- # Adds the servers with a pending response to servers before writing
59
- # their queries, so #process can abort them if it stops early.
60
- def setup_requests(servers, keys)
91
+ def setup_requests(keys, req_options = nil)
61
92
  groups = groups_for_keys(keys)
62
- servers.concat(groups.keys)
63
- make_getkq_requests(groups)
93
+ make_getkq_requests(groups, req_options)
64
94
 
65
95
  # TODO: How does this exit on a NetworkError
66
- finish_queries(servers)
96
+ finish_queries(groups.keys)
67
97
  end
68
98
 
69
99
  ##
@@ -74,17 +104,27 @@ module Dalli
74
104
  # on the wire by switching from getkq to getq, and using
75
105
  # the opaque value to match requests to responses.
76
106
  ##
77
- def make_getkq_requests(groups)
107
+ def make_getkq_requests(groups, req_options = nil)
78
108
  groups.each do |server, keys_for_server|
79
109
  if keys_for_server.size <= INTERLEAVE_THRESHOLD
80
110
  # Small batch - send all at once (existing behavior)
81
- server.request(:pipelined_get, keys_for_server)
111
+ server.request(:pipelined_get, keys_for_server, req_options)
82
112
  else
83
113
  # Large batch - interleave sends with response draining
84
114
  # Pass @partial_results directly to avoid hash allocation/merge overhead
85
- server.request(:pipelined_get_interleaved, keys_for_server, CHUNK_SIZE, @partial_results)
115
+ server.request(:pipelined_get_interleaved, keys_for_server, CHUNK_SIZE, @partial_results, req_options)
86
116
  end
87
- rescue DalliError, NetworkError => e
117
+ # NetworkError (which RetryableNetworkError subclasses) must propagate:
118
+ # #process's top-level rescue retries the whole pipelined get on it. This
119
+ # rescue used to catch DalliError and NetworkError together -- since
120
+ # NetworkError < DalliError, that silently swallowed RetryableNetworkError
121
+ # too, dropping this server's keys from the result on a transient hiccup
122
+ # instead of retrying, with nothing surfaced above debug-level logging.
123
+ # Only a non-network DalliError (this server genuinely can't serve these
124
+ # keys) should be swallowed here.
125
+ rescue Dalli::NetworkError
126
+ raise
127
+ rescue DalliError => e
88
128
  Dalli.logger.debug { e.inspect }
89
129
  Dalli.logger.debug { "unable to get keys for server #{server.name}" }
90
130
  end
@@ -125,39 +165,29 @@ module Dalli
125
165
  raise
126
166
  end
127
167
 
128
- # Swallows Dalli::NetworkError. Empties servers, so they aren't aborted
129
- # again.
168
+ # Swallows Dalli::NetworkError
130
169
  def abort_without_timeout(servers)
131
170
  servers.each(&:pipeline_abort)
132
- servers.clear
133
- end
134
-
135
- # When #process stops before reading every server's replies (the caller's
136
- # block raises or breaks, a Timeout.timeout fires, a value can't be
137
- # deserialized), the rest are still on the socket and some may be in the
138
- # response buffer. Closing those connections keeps them from being read
139
- # as a later request's replies. Aborts that #process already handled
140
- # emptied servers.
141
- def abort_unfinished(servers)
142
- servers.each { |server| server.pipeline_abort(timed_out: false) }
143
- servers.clear
144
171
  end
145
172
 
146
- # Reads the replies available, removing finished servers from servers
147
173
  def fetch_responses(servers, start_time, timeout, &block)
148
174
  # Remove any servers which are not connected
149
175
  servers.select!(&:connected?)
150
- return if servers.empty?
176
+ return [] if servers.empty?
151
177
 
152
178
  time_left = remaining_time(start_time, timeout)
153
179
  readable_servers = servers_with_response(servers, time_left)
154
- return abort_with_timeout(servers) if readable_servers.empty?
180
+ if readable_servers.empty?
181
+ abort_with_timeout(servers)
182
+ return []
183
+ end
155
184
 
156
185
  # Loop through the servers with responses, and
157
186
  # delete any from our list that are finished
158
187
  readable_servers.each do |server|
159
188
  servers.delete(server) if process_server(server, &block)
160
189
  end
190
+ servers
161
191
  rescue NetworkError
162
192
  # Abort and raise if we encountered a network error. This triggers
163
193
  # a retry at the top level on RetryableNetworkError.
@@ -174,10 +204,12 @@ module Dalli
174
204
 
175
205
  # Swallows Dalli::NetworkError
176
206
  def abort_with_timeout(servers)
207
+ abort_without_timeout(servers)
177
208
  servers.each do |server|
178
209
  Dalli.logger.debug { "memcached at #{server.name} did not response within timeout" }
179
210
  end
180
- abort_without_timeout(servers)
211
+
212
+ true # Required to simplify caller
181
213
  end
182
214
 
183
215
  # Processes responses from a server. Returns true if there are no
@@ -193,16 +225,6 @@ module Dalli
193
225
  def servers_with_response(servers, timeout)
194
226
  return [] if servers.empty?
195
227
 
196
- # A bounded read can stop while OpenSSL still holds decrypted bytes.
197
- # IO.select only sees the underlying socket, so process those bytes
198
- # before waiting for another network event.
199
- buffered = nil
200
- servers.each do |server|
201
- sock = server.sock
202
- (buffered ||= []) << server if sock.respond_to?(:pending_data?) && sock.pending_data?
203
- end
204
- return buffered if buffered
205
-
206
228
  sockets = servers.map(&:sock)
207
229
  readable, = IO.select(sockets, nil, nil, timeout)
208
230
  return [] if readable.nil?
@@ -14,10 +14,9 @@ module Dalli
14
14
 
15
15
  ##
16
16
  # Writes multiple key-value pairs to memcached.
17
- # Raises an error if any server is unavailable.
18
17
  #
19
- # A value that can't be marshalled or is over value_max_bytes is skipped;
20
- # the other keys are still stored, then the first such error is raised.
18
+ # A transient network error is retried automatically. If a server remains
19
+ # unreachable after retrying, raises Dalli::NetworkError.
21
20
  #
22
21
  # @param hash [Hash] key-value pairs to set
23
22
  # @param ttl [Integer] time-to-live in seconds
@@ -27,12 +26,10 @@ module Dalli
27
26
  def process(hash, ttl, req_options)
28
27
  return if hash.empty?
29
28
 
30
- @value_error = nil
31
29
  @ring.lock do
32
30
  servers = setup_requests(hash, ttl, req_options)
33
31
  finish_requests(servers)
34
32
  end
35
- raise @value_error if @value_error
36
33
  rescue Dalli::RetryableNetworkError => e
37
34
  Dalli.logger.debug { e.inspect }
38
35
  Dalli.logger.debug { 'retrying pipelined sets because of network error' }
@@ -41,12 +38,9 @@ module Dalli
41
38
 
42
39
  private
43
40
 
44
- # Values are looked up by each key as sent. The caller's key can't be
45
- # rebuilt from it: a long key is digested, and a Symbol becomes a String.
46
41
  def setup_requests(hash, ttl, req_options)
47
- pairs = hash.transform_keys { |k| @key_manager.validate_key(k.to_s) }
48
- groups = groups_for_keys(pairs.keys)
49
- make_set_requests(groups, pairs, ttl, req_options)
42
+ groups = groups_for_keys(hash.keys)
43
+ make_set_requests(groups, hash, ttl, req_options)
50
44
  groups.keys
51
45
  end
52
46
 
@@ -54,15 +48,21 @@ module Dalli
54
48
  # Loop through the server-grouped sets of keys, writing
55
49
  # the corresponding quiet set requests to the appropriate servers
56
50
  ##
57
- def make_set_requests(groups, pairs, ttl, req_options)
51
+ # NetworkError (which RetryableNetworkError subclasses) must propagate: the
52
+ # top-level rescue in #process retries the whole pipelined set on it. A
53
+ # combined `rescue DalliError, NetworkError` would silently swallow
54
+ # RetryableNetworkError too -- since NetworkError < DalliError -- dropping
55
+ # this server's keys on a transient hiccup instead of retrying. Only a
56
+ # non-network DalliError should be swallowed here.
57
+ def make_set_requests(groups, hash, ttl, req_options)
58
58
  groups.each do |server, keys_for_server|
59
59
  keys_for_server.each do |key|
60
- server.request(:pipelined_set, key, pairs[key], ttl, req_options)
61
- rescue Dalli::MarshalError, Dalli::ValueOverMaxSize => e
62
- # Nothing was written for this key, so the server's other keys are
63
- # unaffected; raised by #process once the batch is complete
64
- @value_error ||= e
65
- rescue DalliError, NetworkError => e
60
+ original_key = @key_manager.key_without_namespace(key)
61
+ value = hash[original_key]
62
+ server.request(:pipelined_set, key, value, ttl, req_options)
63
+ rescue Dalli::NetworkError
64
+ raise
65
+ rescue DalliError => e
66
66
  Dalli.logger.debug { e.inspect }
67
67
  Dalli.logger.debug { "unable to set key #{key} for server #{server.name}" }
68
68
  end
@@ -75,14 +75,17 @@ module Dalli
75
75
  def finish_requests(servers)
76
76
  servers.each do |server|
77
77
  server.request(:noop)
78
- rescue DalliError, NetworkError => e
78
+ rescue Dalli::NetworkError
79
+ raise
80
+ rescue DalliError => e
79
81
  Dalli.logger.debug { e.inspect }
80
82
  Dalli.logger.debug { "unable to complete pipelined set on server #{server.name}" }
81
83
  end
82
84
  end
83
85
 
84
86
  def groups_for_keys(keys)
85
- groups = @ring.keys_grouped_by_server(keys)
87
+ validated_keys = keys.map { |k| @key_manager.validate_key(k.to_s) }
88
+ groups = @ring.keys_grouped_by_server(validated_keys)
86
89
 
87
90
  if (unfound_keys = groups.delete(nil))
88
91
  Dalli.logger.debug do