dalli 5.1.10 → 5.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 67bfef8b95e20cd7ea8ed38c6c9b08383c89be7af26e9da8889287a5c95fa2d4
4
- data.tar.gz: 63b9016c7588a2839e35f627d12fba878f023d6188f48f4a653c78982dc0ba7a
3
+ metadata.gz: 23a3890b1ca95b3668eea5b0f2f6eabfb3ad6062daebf5723e5b99c2c7a74854
4
+ data.tar.gz: 4f0c1775badbf133dab91d32a19f84ffafab7f1c0a6c9d7c195f968bed01c089
5
5
  SHA512:
6
- metadata.gz: f4c994ca2ec09b66039d571524ecfa556ffa4e189cfd1d5eb249b9919fe1c82d57120680fea57b9f0f49d6ba44de7129409649a5122bb1f5c46714b531510ce1
7
- data.tar.gz: 9f40b38bb69d7f972ca3a80e722a69482ecd82b3f557ac48452de57f2a9a94174546a1f11c2b65c95bd06eac66d32d85eee0454bb117395f43949a4e891be59b
6
+ metadata.gz: b1624d8d1024956e90ab86a5d5b7f56833d9d195b95d2e8f7ed92774775eebb5ae19baf798773e17ce8fdb7b8fa5abf728a5899d085ecd11335fe11daac52bdb
7
+ data.tar.gz: 76c4e96a6ac88ec7ce86d213d58bf4f709f6ebc52e747ffa05661343173c654696e6e2625090b14d31874f160f3778a750e9cd524cb4f8985ea86716f267793e
data/CHANGELOG.md CHANGED
@@ -1,131 +1,49 @@
1
1
  Dalli Changelog
2
2
  =====================
3
3
 
4
- 5.1.10
4
+ Unreleased
5
5
  ==========
6
6
 
7
- Security:
8
-
9
- - Security fixes; details will follow in the advisory.
10
-
11
- 5.1.9
12
- ==========
13
-
14
- Security:
15
-
16
- - Bound memcached reply headers, incoming value sizes, and response counts, and enforce TLS timeouts for blocking operations (GHSA-5wpc-45jc-6ccc)
17
-
18
- 5.1.8
19
- ==========
20
-
21
- Bug fixes:
22
-
23
- - Raw values in an encoding that isn't ASCII-compatible, such as UTF-16, raised `Encoding::CompatibilityError` from `set`, `add`, `replace`, `append`, `prepend` and `set_multi`, as did a single-server `set_multi` mixing non-ASCII UTF-8 values with binary ones (such as raw Strings of both kinds, or with a JSON serializer, a value containing `é` next to a compressed one). A `p_token` or `l_token` with non-ASCII characters, such as `é`, did the same for any binary value, including every Marshal-serialized one. The error also closed the connection, so in a `quiet` block, or within one server's part of a multi-server `set_multi`, writes buffered before it were silently lost. Values are now sent as their bytes, which is what memcached stores (#1269)
24
-
25
- 5.1.7
26
- ==========
27
-
28
- Bug fixes:
29
-
30
- - `set_multi` across more than one server stored `nil` for a Symbol key or a key over 250 bytes, in place of the value given
31
-
32
- 5.1.6
33
- ==========
34
-
35
- Security:
36
-
37
- - Keep a connection shared by several threads or fibers in step during a `quiet` block (GHSA-5xvx-r8rg-5qm2)
38
- - A `quiet` (or `multi`) block is quiet only for the thread or fiber that runs it. memcached still replies to a quiet request that fails (for example an `add` of a key that exists), and another thread or fiber using the same client while the block was open read that reply as its own, so its later requests could return another key's value. A non-quiet request now reads any pending quiet replies first
39
- - Don't let a `get_multi` that stopped early leave replies for a later request (GHSA-5xvx-r8rg-5qm2)
40
- - A pipelined `get_multi` stopped by a non-network exception (its block raising or breaking, `Timeout.timeout`, or a value that can't be deserialized) left its unread replies in the response buffer, and a later `get_multi` large enough to use the interleaved path returned them as its own. The buffer is now cleared when a connection closes or a pipelined get starts, and unfinished pipelines are aborted
41
- - Affects every supported line (the `get_multi` issue, 4.3 and later); fixed in 5.2.4, 5.1.6, 5.0.12, 4.3.9 and 3.2.15
42
-
43
- Bug fixes:
44
-
45
- - A per-request `raw: true` write no longer compresses the value (backport of #1213)
46
- - Values at or above the compression threshold (4 KB by default) were compressed and flagged even with `raw: true`. Raw reads ignore flags, so reading them back with `raw: true` returned the compressed bytes
47
- - Raw values are now stored exactly as given. Callers that pass `raw: true` without `compress: false` store large values uncompressed; Rails' `MemCacheStore` passes `compress: false` and isn't affected
48
- - Handle failed TLS handshakes like other connection failures, and warn when TLS verification is off (backport of #1215)
49
- - A failed or timed-out handshake left the TCP socket open until GC and raised `OpenSSL::SSL::SSLError` directly, so the server was never marked down. The socket is now closed, and the error goes through the usual retry and `socket_max_failures` handling, raising `Dalli::NetworkError` (or `Dalli::RingError` once no server is available)
50
- - Certificate and hostname checks come only from the `ssl_context` you pass, and a bare `OpenSSL::SSL::SSLContext.new` checks neither. Dalli now logs a warning once per process when `verify_mode` doesn't include `VERIFY_PEER` or `verify_hostname` is false; see the new TLS section in the README
51
- - A reply line longer than 8 KiB without a CRLF, or one cut short by the connection closing, is now a network error that closes the connection. Before, the line had no length limit (backport of #1216)
52
- - One value that can't be stored no longer discards other buffered writes (backport of #1218)
53
- - A value that raised `Dalli::MarshalError` or `Dalli::ValueOverMaxSize` closed the connection, which dropped writes still buffered from the same `quiet` block or `set_multi`. Multi-server `set_multi` did this without raising
54
- - Both `set_multi` paths now store every other key, skip the bad one, and then raise. Single-server `set_multi` used to store nothing
55
- - When single-server `set_multi` failed to marshal a value, the error log included every value in the batch. It now lists only the keys
56
-
57
- 5.1.5
58
- ==========
59
-
60
- Security:
61
-
62
- - Don't rely on memcached's auto-create for keys that need base64 encoding (GHSA-r47x-6p6r-mvcp)
63
- - memcached stores an item made by auto-create (`ma` with `N`/`J`, or `mg` with `N`) for a base64-encoded key without its binary-key flag, and later replies name the item by its raw key bytes. A key containing spaces or CR/LF could then make a multi-get read the replies after it as different ones
64
- - `incr` and `decr` with an initial value now create such counters with an add instead. Return values are unchanged
65
- - The new `verify_reply_keys` option makes `get_multi`, `get_multi_cas` and `get_multi_with_metadata` ignore replies for keys they didn't request, which guards against items created by older Dalli versions or other clients until memcached is upgraded. It's off by default, since it costs a multi-get about 15%
66
- - Affects the meta protocol since 3.2.0; fixed in 5.2.3, 5.1.5, 5.0.11, 4.3.8 and 3.2.14. memcached 1.6.45 and earlier still name these items by their raw key bytes
67
-
68
- 5.1.4
69
- ==========
70
-
71
- Security:
72
-
73
- - Keep the caller's key when retrying a request (GHSA-m252-9cgf-vx2w)
74
- - With a `namespace`, a request retried after a transient network error (a timeout, or a connection closed by memcached or a proxy) applied the namespace a second time, so a retried read could return a different key's value and a retried write could overwrite a different key
75
- - Affects single-key operations since 5.0.3, single-server `get_multi` since 5.1.0, and `get_with_metadata` and `fetch_with_lock` since 4.1.0; fixed in 5.2.2, 5.1.4, 5.0.10 and 4.3.7. Clients without a namespace aren't affected
76
- - Complete the fix for per-request `raw: true` on reads (GHSA-wr87-m4jw-29x5)
77
- - A read made with `raw: true` doesn't ask for flags, but a reply carrying them anyway (from a proxy or a hostile server) still had its value deserialized. Raw reads now ignore flags in the reply
78
- - Affects 5.1.3 and earlier; fixed in 5.2.2, 5.1.4, 5.0.10, 4.3.7 and 3.2.13
79
-
80
- Bug fixes:
81
-
82
- - `get_with_metadata` and `fetch_with_lock` retried the final error raised when a server is marked down, so with `down_retry_delay: 0` they retried an unresponsive server forever. They now retry only retryable errors, like other operations
83
- - Fix a regression in 5.1.3: a `get_multi` that didn't finish within `socket_timeout` counted toward `socket_max_failures`, so two slow `get_multi` calls in a row marked a healthy server down. It now just closes the connection
84
- - Fix a regression in 5.1.3: over TLS, every request buffered in a `quiet` block was sent as its own TLS record and system call (2.5 times slower for a block of 2000 deletes). Each flush is one write again
85
- - Handle malformed replies from a broken or hostile server or proxy: a negative value size, a hit with no key, or a hit with no `s` flag could leave the connection out of step or raise a non-Dalli error
86
- - With `decompressed_max_bytes` in effect, data after the end of a compressed value's stream was returned as part of the value. It's now ignored, as without the limit
87
- - With a `digest_class` whose digests aren't short hex strings, shortening a long key could loop forever. It now raises `ArgumentError`
88
-
89
- Development:
90
-
91
- - Run the Tests, RuboCop and Profiles workflows on pushes to `main` and the `*-stable` branches only, so a pull request's branch isn't tested twice (backport of #1198)
92
- - Fix flaky failover tests: move their ports out of Linux's ephemeral port range, and wait for memcached to accept connections after starting it (backport of #1184)
93
-
94
- 5.1.3
7
+ 5.2.0
95
8
  ==========
96
9
 
97
- Security:
98
-
99
- - Fix pipelined `get_multi` returning one key's value for another after an error reply (GHSA-p6pm-ch9v-44vx)
100
- - The pipelined reply parser took any reply without a body for the end of the batch. An error reply for one key (`CLIENT_ERROR`, `SERVER_ERROR`, or `EN` from a proxy) ended it early, and the replies still on the connection were read as the replies to later commands, so a `get` could return another key's value
101
- - Keys are now measured in bytes as sent, after base64 encoding when the key needs it. A key under 250 characters but over 250 bytes on the wire (for example, one with many non-ASCII characters) was the easiest way to cause that error reply. Such keys are now truncated like other long keys; keys that worked before are unchanged
102
- - Affects the meta protocol since 3.2.0 (the default since 5.0.0); fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
103
- - Reject routing tokens that add meta flags, and stop retrying an unresponsive server forever (GHSA-4qp6-2jcr-596v)
104
- - `p_token` and `l_token` now reject whitespace and control characters, not just CR, LF and NUL. A space let a token add meta flags to the request it was sent with: changing an item's TTL on a read, creating stub items on a miss, turning a delete into a stale tombstone, or reading a different key
105
- - Affects 5.1.0 and later; fixed in 5.2.1 and 5.1.3
106
- - A server that accepted connections but never answered (or dropped the connection on a request) was retried forever, hanging the caller, because each successful reconnect reset the failure count. Requests now fail after `socket_max_failures` attempts and the server is marked down, as when it can't be reached at all; it gets a full set of attempts again after `down_retry_delay`
107
- - Affects all versions; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
108
- - Limit decompressed and reply value sizes (GHSA-3553-vcg5-72jw)
109
- - Values flagged as compressed were inflated without limit, so a small stored value could expand to gigabytes on read, whatever the client's `compress` or `serializer` settings. The new `decompressed_max_bytes` option (default 128 MiB; `nil` disables it) makes a read that would pass it raise `Dalli::UnmarshalError`. Custom compressors whose `decompress` takes only the data keep working, without the limit
110
- - The value size in a reply was used to read or buffer that many bytes, so a malicious server could make the client allocate gigabytes. Sizes over 1 GiB, memcached's largest item, now raise `Dalli::DalliError` before reading
111
- - Affects all versions; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
112
- - Honor per-request `raw: true` on reads, and add `Dalli::JSONSerializer` (GHSA-wr87-m4jw-29x5)
113
- - `get_multi`, `get_multi_cas`, `get_multi_with_metadata`, `get_cas` and `get_with_metadata` ignored a per-request `raw: true` and deserialized the value according to its stored flags, so a caller who asked for raw bytes could still have `Marshal.load` run on data someone else wrote to memcached. They now return the stored bytes
114
- - The `raw` part affects `get_with_metadata` since 4.2.0, and the other methods since they gained per-request options in 5.1.0
115
- - `serializer: JSON` reads values with `JSON.load`, which on json gem versions before 3.0 creates an object of the class named in a stored `json_class` key when the json additions are loaded. The new `Dalli::JSONSerializer` reads with `JSON.parse` and only returns plain JSON types. The README and the Marshal security warning now recommend it; `serializer: JSON` itself is unchanged
116
- - The `serializer: JSON` part affects any version used with the json gem before 3.0
117
- - Keep a forked child from writing to or closing the parent's connection (GHSA-w39f-xq2m-4g8x)
118
- - A child forked while the parent had requests buffered but not yet sent, such as quiet writes inside a `quiet` block, sent them again when it closed the client or reconnected: quiet writes ran twice, and the parent's later replies could be read as the replies to other requests, returning one key's value for another. Dalli now buffers requests itself and a forked child discards them
119
- - Affects 4.2.0 and later; fixed in 5.2.1, 5.1.3, 5.0.9 and 4.3.6
120
- - With TLS, a forked child that closed the client (or reconnected after detecting the fork) sent a TLS close on the connection the parent was still using, ending the parent's session. A forked child now closes only its own copy of the socket
121
- - Affects all versions with TLS; fixed in 5.2.1, 5.1.3, 5.0.9, 4.3.6 and 3.2.12
10
+ Features:
122
11
 
123
- Bug fixes:
12
+ - Add `Dalli::CacheResult`, returned by the new `#get_with_metadata_result` and `#get_multi_with_metadata_result` (#1156)
13
+ - An opt-in, typed view over the Hash that `#get_with_metadata` and `#get_multi_with_metadata` already return; those methods are unchanged, and changing their return type is left for a future major version (#1151)
14
+ - `value`, `cas`, `hit_before`, `last_access` and `ttl_remaining` readers (the last three are `nil` unless requested), plus `miss?`, `hit?`, `stale?`, `won_recache?` and `lost_recache?` predicates
15
+ - Results are frozen, and a Hash that claims to be both a miss and stale raises `ArgumentError`
16
+ - `#get_multi_with_metadata_result` omits misses and accepts `req_options:`, like `#get_multi_with_metadata`; it has no block form
17
+ - Add the opt-in `defer_drain` client option (#1168)
18
+ - With `defer_drain: true`, a `quiet`/`multi` block no longer waits at its end for the replies to its requests. The requests are still sent right away; the replies are read with one noop per server just before the next non-quiet request to that server
19
+ - Adds `Client#drain_deferred_responses`, to drain at a boundary of the caller's choosing (the end of a web request or job)
20
+ - Tradeoff: an error reply to a quiet request surfaces (and is discarded) at that later point, not at the end of the block
21
+ - Off by default, so existing behavior is unchanged
22
+ - Replies memcached sends for quiet requests wait on the connection until they're drained, so a client that only makes quiet requests should call `drain_deferred_responses` periodically; see "Deferred Draining" in the README
23
+ - Thanks to Julian Richard Contreras and Matt Dick for this contribution
124
24
 
125
- - An exception raised by a `get_multi` block (such as `Timeout::Error`) was treated as a network failure: swallowed, with the whole `get_multi` retried and keys yielded twice. It now reaches the caller
25
+ Performance:
126
26
 
127
- 5.1.2
128
- ==========
27
+ - Skip the empty read at the end of each pipelined `read_available` call (#1164)
28
+ - A read shorter than the chunk size means the socket is drained, so the extra `read_nonblock` that only returned `:wait_readable` is gone; the `IO.select` loop still picks up anything that arrives later
29
+ - Saves one syscall per server per multi-server `get_multi`; on 4 servers a 3-key `get_multi` goes from 16% to 5% slower than 2.7.11 in the #930 benchmark
30
+ - TLS sockets also check `SSLSocket#pending`, since `IO.select` cannot see data OpenSSL has buffered
31
+ - Thanks to Julian Richard Contreras for this contribution
32
+ - Reduce Ruby overhead on plain `set` and `delete` (#1166)
33
+ - A `set` with no CAS, routing tokens or quiet mode builds its `ms` request with one string interpolation (`RequestFormatter.plain_meta_set`), and a `delete` with no options uses `plain_meta_delete`; both produce the same bytes as before
34
+ - `HD c<cas>`, `HD` and `NF` replies are parsed without splitting them into tokens
35
+ - Allocations per `set` drop from 22 to 18, and per `delete` from 12 to 7
36
+ - Thanks to Julian Richard Contreras for this contribution
37
+ - Only drain servers that were sent quiet requests when a `quiet`/`multi` block ends (#1167)
38
+ - Ending the block used to send a noop to every server in the ring and wait for each reply, one after another, so its cost grew with ring size even when the block touched one server (or none)
39
+ - Each connection now records when a quiet request is written, and the block's drain skips the others; servers that were never connected are no longer connected just to be drained
40
+ - With ~300us of network round trip, `multi { set }` on a 16-server ring goes from 4.9ms to 0.32ms; an empty block no longer touches the network
41
+ - Thanks to Julian Richard Contreras for this contribution
42
+ - Reduce Ruby overhead in `get_multi` reply parsing and key routing (#1169)
43
+ - `VA` reply headers are read in place instead of being split into tokens, on both the multi-server (pipelined) and single-server paths; results are unchanged, and unusual headers still take the token path
44
+ - A key's server is found through a bucket table over the ring's continuum instead of a binary search, and the key's own server is tried before the failover loop; the server chosen for every key is unchanged
45
+ - Allocations for a 100-key `get_multi` on 4 servers drop from 1,500 to 1,104; over loopback it goes from 301us to 243us
46
+ - Thanks to Julian Richard Contreras for this contribution
129
47
 
130
48
  Bug fixes:
131
49
 
@@ -136,10 +54,6 @@ Bug fixes:
136
54
  - Affects the meta protocol since 3.2.0 (the default since 5.0.0)
137
55
  - Thanks to Julian Richard Contreras for this contribution
138
56
 
139
- Development:
140
-
141
- - Add property tests for request building and fuzz tests for the reply parsers
142
-
143
57
  5.1.1
144
58
  ==========
145
59
 
data/README.md CHANGED
@@ -49,46 +49,41 @@ Dalli::Client.new('localhost:11211', namespace: 'myapp', namespace_separator: '/
49
49
 
50
50
  The separator must be a single non-alphanumeric character. Valid examples: `:`, `/`, `|`, `.`, `-`, `_`, `#`
51
51
 
52
- ### Maximum Value Size
52
+ ### Deferred Draining
53
53
 
54
- `value_max_bytes` limits values written to memcached (1 MiB by default). Values read from a server have the same default limit. If another client writes larger values that this client must read, configure `max_response_bytes` explicitly.
55
-
56
- ## Security Note
57
-
58
- By default, Dalli uses Ruby's Marshal for serialization. Deserializing untrusted data with Marshal can lead to remote code execution. If you cache user-controlled data, consider using a safer serializer:
54
+ By default, a `quiet` (or `multi`) block ends by waiting for the replies memcached still sends for its quiet requests, one round trip for each server the block wrote to. With `defer_drain: true`, the block returns without waiting:
59
55
 
60
56
  ```ruby
61
- Dalli::Client.new('localhost:11211', serializer: Dalli::JSONSerializer)
57
+ dc = Dalli::Client.new('localhost:11211', defer_drain: true)
58
+
59
+ dc.quiet { dc.set('key', 'value') } # returns without a round trip
60
+ dc.get('key') # first drains that connection with a noop, then gets the value
62
61
  ```
63
62
 
64
- `Dalli::JSONSerializer` reads values with `JSON.parse`, so it only ever returns plain hashes, arrays, strings, numbers, booleans and `nil`. Passing the `JSON` module itself (`serializer: JSON`) reads values with `JSON.load`, which can create objects of other classes from a stored `json_class` key and is not recommended for data an attacker might write.
63
+ The requests are still sent right away. Their replies stay unread on the connection until the next non-quiet request to that server, which reads them first with one `noop`. Error replies to quiet requests are discarded either way. With `defer_drain` they're discarded at that later point instead of at the end of the block.
65
64
 
66
- Per-request `raw: true` returns the stored bytes without deserializing or decompressing them, on every read method (`get`, `get_multi`, `get_cas`, `get_with_metadata` and `fetch`).
65
+ **Replies accumulate until a non-quiet request drains them.** memcached still replies to some quiet requests: `NF` for a quiet `delete`, `incr` or `decr` of a missing key, `NS` for an `add` or `replace` that didn't store, and error replies. Those replies wait on the socket. A client that mixes quiet writes with reads (or other non-quiet requests) to the same servers drains them as it goes, and needs nothing more.
67
66
 
68
- See the [5.0-Upgrade.md](5.0-Upgrade.md) guide for upgrade information.
67
+ A client that only ever makes quiet requests, such as a worker that only issues quiet deletes, never sends that next request. Its unread replies keep growing, and if they fill the connection's socket buffers, the connection can stall until a socket timeout closes it and Dalli reconnects. Workloads like that should call `drain_deferred_responses` periodically, for example after each batch or job:
69
68
 
70
- ### Counters and verify_reply_keys
69
+ ```ruby
70
+ jobs.each do |job|
71
+ job.keys.each { |key| dc.quiet { dc.delete(key) } }
72
+ dc.drain_deferred_responses # reads and discards the replies waiting on each server
73
+ end
74
+ ```
71
75
 
72
- memcached names an item made by auto-create for a base64-encoded key (one with whitespace, control or non-ASCII characters) by its raw key bytes in later replies. Since 5.1.5, Dalli creates counters for such keys with an add rather than auto-create. Items created before then, or by other clients, can still be named that way until memcached releases a fix (1.6.45 and earlier behave this way). If keys passed to `incr` or `decr` with an initial value can contain untrusted input, set `verify_reply_keys: true` until then: multi-gets then ignore replies for keys they didn't request, at a cost of about 15% per multi-get.
76
+ `drain_deferred_responses` only sends a `noop` to servers that were sent quiet requests since they were last drained, so calling it when nothing is pending costs nothing.
73
77
 
74
- ## TLS
78
+ ## Security Note
75
79
 
76
- Pass an `OpenSSL::SSL::SSLContext` as `ssl_context:` to connect over TLS. Certificate and hostname verification come only from that context: Dalli adds no checks of its own. A bare `OpenSSL::SSL::SSLContext.new` verifies nothing, so it accepts any certificate from any server. Configure the context to verify both:
80
+ By default, Dalli uses Ruby's Marshal for serialization. Deserializing untrusted data with Marshal can lead to remote code execution. If you cache user-controlled data, consider using a safer serializer:
77
81
 
78
82
  ```ruby
79
- ssl_context = OpenSSL::SSL::SSLContext.new
80
- ssl_context.set_params(
81
- verify_mode: OpenSSL::SSL::VERIFY_PEER,
82
- verify_hostname: true,
83
- ca_file: '/path/to/ca.crt' # omit to use the system's trusted certificates
84
- )
85
-
86
- Dalli::Client.new('memcached.example.com:11211', ssl_context: ssl_context)
83
+ Dalli::Client.new('localhost:11211', serializer: JSON)
87
84
  ```
88
85
 
89
- Dalli logs a warning once per process when the context's `verify_mode` is `VERIFY_NONE`, or when it is `VERIFY_PEER` but `verify_hostname` is false.
90
-
91
- A failed TLS handshake counts as a failed connection attempt, like a refused connection: once `socket_max_failures` attempts have failed, the server is marked down and requests fail over to the other servers.
86
+ See the [5.0-Upgrade.md](5.0-Upgrade.md) guide for upgrade information.
92
87
 
93
88
  ## OpenTelemetry Tracing
94
89
 
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dalli
4
+ ##
5
+ # An immutable, typed view over the Hash returned by Client#get_with_metadata
6
+ # and Client#get_multi_with_metadata.
7
+ #
8
+ # This is an interim adapter (see #1130 / #1151): #get_with_metadata and
9
+ # #get_multi_with_metadata keep returning a Hash for now, since changing
10
+ # their return type is a breaking change reserved for a future major
11
+ # version. #get_with_metadata_result and #get_multi_with_metadata_result
12
+ # wrap that Hash in this type instead, so the structured shape can be
13
+ # validated by callers ahead of that change.
14
+ ##
15
+ class CacheResult
16
+ attr_reader :value, :cas, :hit_before, :last_access, :ttl_remaining
17
+
18
+ # @param hash [Hash] a Hash as returned by Client#get_with_metadata, or a
19
+ # single value from the Hash returned by Client#get_multi_with_metadata
20
+ def initialize(hash)
21
+ @value = hash[:value]
22
+ @cas = hash[:cas]
23
+ @miss = hash.fetch(:miss, false)
24
+ @stale = hash.fetch(:stale, false)
25
+ @won_recache = hash.fetch(:won_recache, false)
26
+ @lost_recache = hash.fetch(:lost_recache, false)
27
+ @hit_before = hash[:hit_before]
28
+ @last_access = hash[:last_access]
29
+ @ttl_remaining = hash[:ttl_remaining]
30
+
31
+ raise ArgumentError, 'a result cannot be both a miss and stale' if @miss && @stale
32
+
33
+ freeze
34
+ end
35
+
36
+ # True when the key did not exist. Prefer this over a nil #value, which
37
+ # cannot distinguish a miss from a stored nil under cache_nils.
38
+ def miss?
39
+ @miss
40
+ end
41
+
42
+ # The inverse of #miss?.
43
+ def hit?
44
+ !@miss
45
+ end
46
+
47
+ # True when the item is a tombstone (marked stale via the meta protocol's
48
+ # invalidate flag) rather than removed. Not a miss: #value is still the
49
+ # last-known value unless the tombstone also dropped it.
50
+ def stale?
51
+ @stale
52
+ end
53
+
54
+ # True if this call won the right to regenerate the value under
55
+ # thundering-herd protection (see Client#fetch_with_lock).
56
+ def won_recache?
57
+ @won_recache
58
+ end
59
+
60
+ # True if another client already won the recache race for this key.
61
+ def lost_recache?
62
+ @lost_recache
63
+ end
64
+ end
65
+ end
data/lib/dalli/client.rb CHANGED
@@ -35,30 +35,29 @@ module Dalli
35
35
  # to memcached. Default: true.
36
36
  # - :compression_min_size - the minimum size (in bytes) for which Dalli will compress values sent to Memcached.
37
37
  # Defaults to 4K.
38
- # - :value_max_bytes - largest value Dalli will write, 1MB by default.
39
- # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1MB by default).
40
- # Set this explicitly when reading larger items written by another client.
41
38
  # - :serializer - defaults to Marshal
42
39
  # - :compressor - defaults to Dalli::Compressor, a Zlib-based implementation
43
40
  # - :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for
44
41
  # #fetch operations.
45
42
  # - :raw - If set, disables serialization and compression entirely at the client level.
46
43
  # Only String values are supported. This is useful when the caller handles its own
47
- # serialization (e.g., Rails' ActiveSupport::Cache). The per-request :raw option
48
- # (e.g. set(key, value, ttl, raw: true)) does the same for a single call: String
49
- # values are stored as-is, uncompressed, and non-String values raise
50
- # Dalli::MarshalError.
44
+ # serialization (e.g., Rails' ActiveSupport::Cache). Note: this is different from
45
+ # the per-request :raw option which converts values to strings but still uses the
46
+ # serialization pipeline.
51
47
  # - :digest_class - defaults to Digest::MD5, allows you to pass in an object that responds to the hexdigest method,
52
48
  # useful for injecting a FIPS compliant hash object.
53
49
  # - :otel_db_statement - controls the +db.query.text+ span attribute when OpenTelemetry is loaded.
54
50
  # +:include+ logs the full operation and key(s), +:obfuscate+ replaces keys with "?",
55
51
  # +nil+ (default) omits the attribute entirely.
56
52
  # - :otel_peer_service - when set, adds a +peer.service+ span attribute with this value for logical service naming.
57
- # - :verify_reply_keys - defaults to false. When true, get_multi, get_multi_cas and get_multi_with_metadata only
58
- # accept replies for the keys they requested; after a reply naming another key, the rest of
59
- # that server's replies are treated as misses. memcached can name an item by its raw key
60
- # bytes when the item was created by auto-create from a base64-encoded key, which Dalli no
61
- # longer does. Costs a multi-get about 15%.
53
+ # - :defer_drain - defaults to false. When true, a quiet/multi block no longer waits at its end for the replies
54
+ # to its requests. The requests are still sent right away; their replies are read (with one noop
55
+ # per server) just before the next non-quiet request to that server, or by
56
+ # #drain_deferred_responses. The tradeoff: an error reply to a quiet request surfaces, and is
57
+ # discarded, at that later point rather than when the block ends. Replies memcached sends for
58
+ # quiet requests (NF, NS, errors) wait on the connection until then, so a client that only makes
59
+ # quiet requests should call #drain_deferred_responses periodically. See "Deferred Draining" in
60
+ # the README.
62
61
  #
63
62
  def initialize(servers = nil, options = {})
64
63
  @normalized_servers = ::Dalli::ServersArgNormalizer.normalize_servers(servers)
@@ -145,23 +144,35 @@ module Dalli
145
144
  #
146
145
  def get_with_metadata(key, options = {})
147
146
  validate_routing_tokens!(options)
148
- # A retry re-runs this method with its original arguments, so `key` must
149
- # stay as the caller gave it; reassigning it would add the namespace again.
150
- validated_key = @key_manager.validate_key(key.to_s)
147
+ key = key.to_s
148
+ key = @key_manager.validate_key(key)
151
149
 
152
- server = ring.server_for_key(validated_key)
153
- Instrumentation.trace('get_with_metadata', trace_attrs('get_with_metadata', validated_key, server)) do
154
- server.request(:meta_get, validated_key, options)
150
+ server = ring.server_for_key(key)
151
+ Instrumentation.trace('get_with_metadata', trace_attrs('get_with_metadata', key, server)) do
152
+ server.request(:meta_get, key, options)
155
153
  end
156
- # Only a retryable error is retried. The NetworkError raised when a server
157
- # is marked down is final, as in #perform; retrying it looped forever once
158
- # down_retry_delay let the same server be tried again.
159
- rescue RetryableNetworkError => e
154
+ rescue NetworkError => e
160
155
  Dalli.logger.debug { e.inspect }
161
156
  Dalli.logger.debug { 'retrying get_with_metadata with new server' }
162
157
  retry
163
158
  end
164
159
 
160
+ ##
161
+ # Like #get_with_metadata, but wraps the result in a Dalli::CacheResult
162
+ # instead of returning a Hash.
163
+ #
164
+ # Interim adapter (see #1130 / #1151): #get_with_metadata itself keeps
165
+ # returning a Hash, since changing that return type is a breaking change
166
+ # reserved for a future major version. This lets callers opt in to the
167
+ # structured shape today.
168
+ #
169
+ # @param key [String] the cache key
170
+ # @param options [Hash] see #get_with_metadata
171
+ # @return [Dalli::CacheResult]
172
+ def get_with_metadata_result(key, options = {})
173
+ CacheResult.new(get_with_metadata(key, options))
174
+ end
175
+
165
176
  ##
166
177
  # Fetch multiple keys efficiently.
167
178
  # If a block is given, yields key/value pairs one at a time.
@@ -241,6 +252,27 @@ module Dalli
241
252
  results
242
253
  end
243
254
 
255
+ ##
256
+ # Like #get_multi_with_metadata, but wraps each entry's Hash in a
257
+ # Dalli::CacheResult instead. Missing keys are still omitted; no block
258
+ # form.
259
+ #
260
+ # Interim adapter (see #1130 / #1151): #get_multi_with_metadata itself
261
+ # keeps returning a Hash of Hashes, since changing that return type is a
262
+ # breaking change reserved for a future major version. This lets callers
263
+ # opt in to the structured shape today.
264
+ #
265
+ # Result key order follows #get_multi_with_metadata's own: request order
266
+ # only when every key lands on the same server, per-server response order
267
+ # otherwise.
268
+ #
269
+ # @param keys [Array<String>] the keys to fetch
270
+ # @param req_options [Hash, nil] see #get_multi_with_metadata
271
+ # @return [Hash] key => Dalli::CacheResult
272
+ def get_multi_with_metadata_result(*keys, req_options: nil)
273
+ get_multi_with_metadata(*keys, req_options: req_options).transform_values { |hash| CacheResult.new(hash) }
274
+ end
275
+
244
276
  ##
245
277
  # Fetch multiple keys efficiently, including available metadata such as CAS.
246
278
  # If a block is given, yields key/data pairs one a time. Data is an array:
@@ -315,17 +347,14 @@ module Dalli
315
347
  validate_integer!(:lock_ttl, lock_ttl)
316
348
  validate_integer!(:recache_threshold, recache_threshold)
317
349
  validate_routing_tokens!(req_options)
318
- # Left unchanged for the retry below; see get_with_metadata
319
- validated_key = @key_manager.validate_key(key.to_s)
350
+ key = key.to_s
351
+ key = @key_manager.validate_key(key)
320
352
 
321
- server = ring.server_for_key(validated_key)
322
- Instrumentation.trace('fetch_with_lock', trace_attrs('fetch_with_lock', validated_key, server)) do
323
- fetch_with_lock_request(validated_key, ttl, lock_ttl, recache_threshold, req_options, &block)
353
+ server = ring.server_for_key(key)
354
+ Instrumentation.trace('fetch_with_lock', trace_attrs('fetch_with_lock', key, server)) do
355
+ fetch_with_lock_request(key, ttl, lock_ttl, recache_threshold, req_options, &block)
324
356
  end
325
- # Only a retryable error is retried. The NetworkError raised when a server
326
- # is marked down is final, as in #perform; retrying it looped forever once
327
- # down_retry_delay let the same server be tried again.
328
- rescue RetryableNetworkError => e
357
+ rescue NetworkError => e
329
358
  Dalli.logger.debug { e.inspect }
330
359
  Dalli.logger.debug { 'retrying fetch_with_lock with new server' }
331
360
  retry
@@ -371,24 +400,34 @@ module Dalli
371
400
  # arithmetic (incr, decr), flush and delete operations. Use of
372
401
  # unsupported operations inside a block will raise an error.
373
402
  #
374
- # Any error replies will be discarded at the end of the block, and
403
+ # Any error replies will be discarded at the end of the block (or, with
404
+ # the defer_drain option, before the next non-quiet request), and
375
405
  # Dalli client methods invoked inside the block will not
376
406
  # have return values
377
- #
378
- # The block is quiet only for the thread or fiber that runs it. Another
379
- # thread or fiber sharing this client can make requests meanwhile; a
380
- # non-quiet one first sends the block's buffered requests and discards
381
- # their replies, so it reads only its own.
382
407
  def quiet
383
408
  old = Thread.current[::Dalli::QUIET]
384
409
  Thread.current[::Dalli::QUIET] = true
385
410
  yield
386
411
  ensure
387
- @ring&.pipeline_consume_and_ignore_responses
412
+ @ring&.pipeline_consume_and_ignore_responses unless @options[:defer_drain]
388
413
  Thread.current[::Dalli::QUIET] = old
389
414
  end
390
415
  alias multi quiet
391
416
 
417
+ ##
418
+ # Reads and discards the replies still pending from quiet requests, on the
419
+ # servers that have any. Only needed with the defer_drain option.
420
+ #
421
+ # Normally the next non-quiet request to a server drains its pending
422
+ # replies first. A client that only makes quiet requests (for example, a
423
+ # worker that only issues quiet deletes) never does, so its replies keep
424
+ # accumulating on the socket; call this periodically, such as after each
425
+ # batch or job. It sends nothing to servers with no quiet requests pending.
426
+ def drain_deferred_responses
427
+ @ring&.pipeline_consume_and_ignore_responses
428
+ nil
429
+ end
430
+
392
431
  def set(key, value, ttl = nil, req_options = nil)
393
432
  set_cas(key, value, 0, ttl, req_options)
394
433
  end
@@ -748,22 +787,16 @@ module Dalli
748
787
  # to route to at all is still silent, matching Ring#keys_grouped_by_server
749
788
  # dropping a key it can't route on both the single- and multi-server paths.
750
789
  def single_server_get_multi(keys, req_options = nil)
751
- # A new array, so the retry below starts again from the caller's keys
752
- validated_keys = keys.map { |k| @key_manager.validate_key(k.to_s) }
790
+ keys.map! { |k| @key_manager.validate_key(k.to_s) }
753
791
  return {} unless (server = single_server)
754
792
 
755
- result = server.request(:read_multi_req, validated_keys, req_options)
793
+ result = server.request(:read_multi_req, keys, req_options)
756
794
  result.transform_keys! { |k| @key_manager.key_without_namespace(k) }
757
795
  result
758
796
  rescue Dalli::RetryableNetworkError => e
759
797
  Dalli.logger.debug { e.inspect }
760
798
  Dalli.logger.debug { 'retrying single-server get_multi because of network error' }
761
799
  retry
762
- rescue Dalli::UnexpectedReplyKeyError => e
763
- # The connection is closed and the keys are treated as missing, as the
764
- # pipelined get_multi does for a server whose replies are out of step
765
- Dalli.logger.warn { e.message }
766
- {}
767
800
  end
768
801
 
769
802
  def single_server_get_multi_with_metadata(keys, req_options = nil)
@@ -775,9 +808,6 @@ module Dalli
775
808
  result
776
809
  rescue Dalli::NetworkError
777
810
  {}
778
- rescue Dalli::UnexpectedReplyKeyError => e
779
- Dalli.logger.warn { e.message }
780
- {}
781
811
  end
782
812
 
783
813
  def single_server_set_multi(hash, ttl, req_options)
@@ -851,7 +881,7 @@ module Dalli
851
881
  # check means unwinding through Protocol::Base#request, which logs the
852
882
  # failure as unexpected and closes the connection -- a caller passing a
853
883
  # bad token should get a clean ArgumentError and keep its connection.
854
- ROUTING_TOKEN_FORBIDDEN = /[\x00-\x20\x7F]/
884
+ ROUTING_TOKEN_FORBIDDEN = /[\r\n\0]/
855
885
  private_constant :ROUTING_TOKEN_FORBIDDEN
856
886
 
857
887
  def validate_routing_tokens!(req_options)
@@ -867,9 +897,7 @@ module Dalli
867
897
  # here (it would also excuse [] / {} from the type check below).
868
898
  return if value.nil? || (value.is_a?(String) && value.empty?)
869
899
  raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
870
- return unless value.match?(ROUTING_TOKEN_FORBIDDEN)
871
-
872
- raise ArgumentError, "#{name} must not contain whitespace or control characters"
900
+ raise ArgumentError, "#{name} must not contain CRLF or null bytes" if value.match?(ROUTING_TOKEN_FORBIDDEN)
873
901
  end
874
902
 
875
903
  def cas_core(key, always_set, ttl = nil, req_options = nil)
@@ -927,20 +955,18 @@ module Dalli
927
955
  # rubocop:enable Naming/MethodParameterName
928
956
  return yield if block_given?
929
957
 
930
- # `retry` below re-runs this method with its original arguments, so `key`
931
- # must stay as the caller gave it: reassigning it would apply the
932
- # namespace a second time and send the retry to a different key.
933
- validated_key = @key_manager.validate_key(key.to_s)
958
+ key = key.to_s
959
+ key = @key_manager.validate_key(key)
934
960
 
935
- server = ring.server_for_key(validated_key)
961
+ server = ring.server_for_key(key)
936
962
 
937
963
  if Instrumentation.enabled?
938
964
  op_name = op.name
939
- Instrumentation.trace(op_name, trace_attrs(op_name, validated_key, server)) do
940
- server.request(op, validated_key, ...)
965
+ Instrumentation.trace(op_name, trace_attrs(op_name, key, server)) do
966
+ server.request(op, key, ...)
941
967
  end
942
968
  else
943
- server.request(op, validated_key, ...)
969
+ server.request(op, key, ...)
944
970
  end
945
971
  rescue RetryableNetworkError => e
946
972
  Dalli.logger.debug { e.inspect }