redis-clustering 6.0.0 → 6.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2e9c31d780e291ac7df46dc423f6460bdd92e357d490c13a45ec83094dd078f3
4
- data.tar.gz: 5125a590e44be00d49640e82354dbffc7baf8d819219c512a2896809aabab3c7
3
+ metadata.gz: 3754d3c6b3e69d16dabe0f1a76c3958ba93c2d95288a4ba2a3d249702b173fb9
4
+ data.tar.gz: cf89493f5f98b85a741380b2135ab2b92712fad5b6e68e11958ffe3c4c782764
5
5
  SHA512:
6
- metadata.gz: 86f573a8390cba746e75d4585101e05070f4a709c2e9eddc22130189379d8e2b7580dd7595d54b80842a121a8f17ebe693a3b7664e1bc4f791d07e1a8c1a489f
7
- data.tar.gz: 221e1b270ee3838413598d3dc2280e3021c627daabddbb0454fd32fd2e5cab11507e1fa16b940163379b362bb9945230ffc5237ece4d7705d648b22f9255c77a
6
+ metadata.gz: 84f69e83f4392f3a1b2c00923f4d1fc9cb6c51ea064e69066a5353596954d85f63da3aff191fe68d37d2262e06c5f39f7864abfb6aeff5edd38709b034838e61
7
+ data.tar.gz: 92bd706e516f5cd0bf1ec51a4c5f833367cb449539d8160a56e75cda5adcc97acc317f81e347c31266076a7a50558ab2db7f92ddce9438773770c127ab7fdf34
data/CHANGELOG.md CHANGED
@@ -1,3 +1,42 @@
1
+ # 6.1.0
2
+
3
+ All commands added to the `redis` gem in 6.1.0 are available on `Redis::Cluster` (see the main
4
+ [CHANGELOG](../CHANGELOG.md)); the entries below cover cluster-specific behaviour.
5
+
6
+ ## New features
7
+
8
+ - Add the `BLESS` key-protection commands (Redis 8.12): `bless_get`, `bless_set` and
9
+ `bless_clear` route by the key's hash slot; `bless_scan` and `bless_scan_each` walk every
10
+ shard the way `scan` does, with the node index encoded in the returned cursor, so a full
11
+ iteration covers the whole cluster. Inside `pipelined`/`multi`, `bless_scan` is sent to a
12
+ single node and returns only that node's keys. (#1395)
13
+ - Add `Redis::Cluster#keyspace_notifications`: a cluster-aware keyspace notification manager
14
+ that subscribes on **every primary** (notifications are node-local in cluster and are not
15
+ forwarded on the cluster bus, so a plain `subscribe` silently receives ~1/N of the events),
16
+ dispatches parsed notifications from a single dispatcher thread, and reconciles reactively on
17
+ node connection errors (`#refresh` is also public for post-scale-out reconciliation). Requires
18
+ `notify-keyspace-events` to be enabled on every node, replicas included. See
19
+ specs/keyspace-notifications/user-guide.md. (#1375)
20
+ - The `HOTKEYS` commands (Redis 8.6) raise `NotImplementedError` on `Redis::Cluster`, also
21
+ inside `pipelined`/`multi`: a tracking session is state of a single node, so connect to that
22
+ node with `Redis.new(host:, port:)` instead. (#1408)
23
+ - `waitaof` (Redis 7.2) is sent to every primary and each count in the reply is the minimum
24
+ across primaries, so thresholds keep their single-node meaning. `Redis::Cluster.new` now
25
+ accepts `command_routings:`, a `{ 'command' => { request_policy:, response_policy: } }` hash
26
+ merged over the driver's routing table. (#1387)
27
+ - `cluster('slot-stats', ...)` replies (Redis 8.2) are reshaped into `[slot, Hash]` pairs.
28
+ (#1391)
29
+ - Freeze `Redis::Cluster::Client::ERROR_MAPPING` from `redis/ractorize` so that errors can be
30
+ translated in non-main Ractors. (#1403)
31
+
32
+ ## Maintenance
33
+
34
+ - Bump the exact `redis-cluster-client` pin from `0.16.7` to `0.18.0`: adds the node-by-node
35
+ `BLESS SCAN` routing `bless_scan` relies on (0.17.3), routes the informational `CLUSTER`,
36
+ `SCRIPT`, `MEMORY` and `CLIENT` subcommands by their command tips instead of rejecting them,
37
+ follows `MOVED` redirections to nodes not yet in the topology, and splits multi-key `unlink`,
38
+ `exists` and `touch` across slots the way `del` already was. (#1375, #1395)
39
+
1
40
  # 6.0.0
2
41
 
3
42
  ## Breaking changes
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'delegate'
3
4
  require 'redis-cluster-client'
4
5
  require 'redis/cluster/transaction_adapter'
5
6
 
@@ -91,12 +92,33 @@ class Redis
91
92
  handle_errors { super(timeout, command, &block) }
92
93
  end
93
94
 
94
- def pipelined(exception: true, &block)
95
- handle_errors { super(exception: exception, &block) }
95
+ # Inside a pipeline or transaction the driver routes the keyless HOTKEYS verbs to an
96
+ # arbitrary node, so they are rejected there just as Redis::Cluster rejects direct calls.
97
+ class HotkeysGuard < SimpleDelegator
98
+ def call_v(command, &block)
99
+ reject_hotkeys(command)
100
+ super
101
+ end
102
+
103
+ def blocking_call_v(timeout, command, &block)
104
+ reject_hotkeys(command)
105
+ super
106
+ end
107
+
108
+ private
109
+
110
+ def reject_hotkeys(command)
111
+ raise NotImplementedError, HOTKEYS_NOT_SUPPORTED if command.first.to_s.casecmp?('hotkeys')
112
+ end
113
+ end
114
+ private_constant :HotkeysGuard
115
+
116
+ def pipelined(exception: true)
117
+ handle_errors { super(exception: exception) { |pipeline| yield HotkeysGuard.new(pipeline) } }
96
118
  end
97
119
 
98
- def multi(watch: nil, &block)
99
- handle_errors { super(watch: watch, &block) }
120
+ def multi(watch: nil)
121
+ handle_errors { super(watch: watch) { |transaction| yield HotkeysGuard.new(transaction) } }
100
122
  end
101
123
 
102
124
  def watch(*keys, &block)
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Redis
4
+ class Cluster
5
+ class KeyspaceNotifications
6
+ # One cluster primary: owns a dedicated standalone connection and a core-layer
7
+ # standalone manager whose listener thread forwards every parsed notification
8
+ # into the cluster manager's shared dispatch queue. Reader threads never run
9
+ # user code — handlers are invoked serially by the cluster dispatcher.
10
+ class NodeListener
11
+ # @return [String] "host:port" of the primary this listener is attached to
12
+ attr_reader :node_key
13
+
14
+ # @param node_key [String] "host:port"
15
+ # @param redis_options [Hash] options for the sidecar ::Redis connection
16
+ # @param queue [SizedQueue] the cluster manager's dispatch queue
17
+ # @param on_error [#call] receives (node_key, error) for every background error
18
+ # @param on_reconnect [#call] receives (node_key) after the core manager
19
+ # re-established a lost connection and replayed its subscriptions
20
+ def initialize(node_key, redis_options, queue, on_error:, on_reconnect:)
21
+ @node_key = node_key
22
+ @queue = queue
23
+ # One shared wrapper for every pattern: it only enqueues; the user
24
+ # handler is resolved from the cluster registry at dispatch time. A
25
+ # full queue blocks this node's reads (backpressure).
26
+ @enqueue = lambda do |notification|
27
+ @queue.push(notification)
28
+ rescue ClosedQueueError
29
+ nil # the cluster manager closed concurrently; drop the notification
30
+ end
31
+ @redis = ::Redis.new(redis_options)
32
+ @manager = ::Redis::KeyspaceNotifications::Manager.new(
33
+ redis: @redis,
34
+ error_handler: ->(error) { on_error.call(node_key, error) }
35
+ )
36
+ # The core manager announces its own successful reconnect replays; the
37
+ # rebuild path (a refresh replacing a torn-down listener with a fresh
38
+ # one) is announced by the refresh itself.
39
+ @manager.on_reconnect { on_reconnect.call(node_key) }
40
+ end
41
+
42
+ # Per-node convergence step run by every refresh: subscribe every
43
+ # registered pattern (idempotent) and remove leftovers that are no
44
+ # longer registered.
45
+ #
46
+ # @param patterns [Array<String>] the registered patterns
47
+ # @return [NodeListener] self
48
+ def catch_up(patterns)
49
+ subscribe(patterns) unless patterns.empty?
50
+ # Compare against registered INTENT, not confirmations: a
51
+ # registered-but-unconfirmed leftover would be resurrected by the
52
+ # reconnect replay if reconciliation couldn't see it.
53
+ extra = @manager.registered_patterns - patterns
54
+ @manager.unsubscribe(*extra) unless extra.empty?
55
+ self
56
+ end
57
+
58
+ # @param patterns [Array<String>]
59
+ def subscribe(patterns)
60
+ @manager.subscribe(*patterns, handler: @enqueue)
61
+ end
62
+
63
+ # @param patterns [Array<String>] never empty — an empty list would mean
64
+ # "everything" to the core manager and race concurrent subscriptions
65
+ def unsubscribe(patterns)
66
+ return if patterns.empty?
67
+
68
+ @manager.unsubscribe(*patterns)
69
+ end
70
+
71
+ # Whether this listener needs no rebuild: with subscriptions expected it
72
+ # must be actively subscribed (mid-reconnect or budget-exhausted
73
+ # listeners report false and are rebuilt by the asking refresh).
74
+ #
75
+ # @param expect_subscribed [Boolean] whether the cluster registry has patterns
76
+ # @return [Boolean]
77
+ def healthy?(expect_subscribed)
78
+ return false if @manager.closed?
79
+
80
+ !expect_subscribed || @manager.subscribed?
81
+ end
82
+
83
+ # Close the core manager (kills its listener thread) and the sidecar connection.
84
+ def close
85
+ @manager.close
86
+ rescue StandardError
87
+ nil
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,691 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require "redis/keyspace_notifications"
5
+ require "redis/cluster/keyspace_notifications/node_listener"
6
+
7
+ class Redis
8
+ class Cluster
9
+ # Keyspace/keyevent/subkey notification manager for Redis Cluster.
10
+ #
11
+ # In a cluster, keyspace notifications are node-local (not forwarded on the
12
+ # cluster bus), so a plain subscribe on one node silently receives only a
13
+ # fraction of the events. This manager fans every subscription out to **all
14
+ # primaries** (one dedicated pub/sub connection each), funnels the parsed
15
+ # {Redis::KeyspaceNotifications::Notification} objects through one queue, and
16
+ # invokes handlers serially on a single dispatcher thread — per-node ordering
17
+ # is preserved, cross-node ordering is unspecified, handlers need not be
18
+ # thread-safe.
19
+ #
20
+ # Topology changes are handled reactively: a node connection error triggers a
21
+ # {#refresh}, which re-enumerates the primaries via `CLUSTER NODES` (membership,
22
+ # not slot coverage — a scale-out primary is discovered before it owns a slot),
23
+ # drops vanished/demoted nodes and subscribes new primaries to every registered
24
+ # pattern. There is no proactive polling — after adding primaries call
25
+ # {#refresh} yourself before resharding, since a brand-new node emits no error
26
+ # signal.
27
+ #
28
+ # Like all keyspace notifications, delivery is fire-and-forget: events emitted
29
+ # while a node was unreachable are lost. Duplicates are possible too: a primary
30
+ # demoted WITHOUT its connections dropping (e.g. a manual `CLUSTER FAILOVER`)
31
+ # emits no error signal, and as a replica it re-emits every replicated write
32
+ # until a {#refresh} observes the settled topology and prunes it. Handlers
33
+ # should tolerate both. In cluster mode `db` is always 0.
34
+ class KeyspaceNotifications
35
+ DEFAULT_QUEUE_SIZE = 1024
36
+
37
+ # @param cluster [Redis::Cluster] the owning cluster client (used to enumerate
38
+ # primaries; its connections are not used for the subscriptions themselves)
39
+ # @param base_options [Hash] the cluster client's options, used to derive the
40
+ # per-node sidecar connection options (auth, TLS, timeouts, driver)
41
+ # @param error_handler [#call, nil] receives (error, node_key) for every
42
+ # background error; node_key is nil for dispatcher-level errors. Defaults to
43
+ # warning on $stderr
44
+ # @param queue_size [Integer] bound of the shared dispatch queue; when handlers
45
+ # are slower than the notification rate, node reader threads block on the full
46
+ # queue, which back-pressures their sockets
47
+ def initialize(cluster, base_options:, error_handler: nil, queue_size: DEFAULT_QUEUE_SIZE)
48
+ @cluster = cluster
49
+ @base_options = base_options.dup
50
+ @error_handler = error_handler
51
+ @registry = {} # pattern (BINARY String) => user handler (nil for default) — canonical truth
52
+ @default_handler = nil
53
+ @reconnect_handler = nil
54
+ @listeners = {} # "host:port" => NodeListener
55
+ @queue = SizedQueue.new(queue_size)
56
+ @lock = Monitor.new
57
+ @refresh_cond = @lock.new_cond
58
+ @refresh_lock = Mutex.new
59
+ @refresh_needed = false
60
+ @closed = false
61
+ @dispatcher = spawn_dispatcher
62
+ @refresher = spawn_refresher
63
+ begin
64
+ refresh
65
+ rescue StandardError
66
+ # A failed construction must not leak the background threads or any
67
+ # listeners a partial refresh already created.
68
+ close
69
+ raise
70
+ end
71
+ end
72
+
73
+ # Subscribe to notification channel patterns on every primary (build them with
74
+ # {Redis::KeyspaceNotifications::Channels}; remember `db` is always 0 in cluster).
75
+ # Re-subscribing a known pattern replaces its handler. Per-node failures are
76
+ # reported to the error handler and healed by the next {#refresh}; the registry
77
+ # is always updated.
78
+ #
79
+ # @param patterns [Array<String>] channel names or psubscribe patterns
80
+ # @param handler [#call, nil] receives each {Redis::KeyspaceNotifications::Notification};
81
+ # falls back to the {#on_notification} default handler when nil
82
+ # @return [void]
83
+ # @raise [Redis::CommandError] when the server rejects a pattern (e.g. an
84
+ # ACL-forbidden channel): the rejected pattern is evicted from the registry
85
+ # — it could never succeed and would poison every future refresh — while
86
+ # the call's other patterns stay registered
87
+ def subscribe(*patterns, handler: nil, &block)
88
+ raise ArgumentError, "no patterns given" if patterns.empty?
89
+
90
+ handler ||= block
91
+ patterns = patterns.map { |pattern| pattern.to_s.b }
92
+ listeners = @lock.synchronize do
93
+ raise SubscriptionError, "keyspace notifications manager is closed" if @closed
94
+
95
+ patterns.each { |pattern| @registry[pattern] = handler }
96
+ @listeners.to_a
97
+ end
98
+ # In-handler calls run on the dispatcher thread: an ack-blocking fan-out
99
+ # would deadlock against node readers stuck on a full queue. Defer to the
100
+ # refresher, which reconciles from the already-updated registry.
101
+ return request_refresh(nil) if dispatcher_thread?
102
+
103
+ # Fan out WITHOUT holding the lock (each per-node subscribe blocks on that
104
+ # node's ack). One pattern per call: under the core manager's rejection
105
+ # attribution a CommandError raised here names THIS pattern, so the
106
+ # culprit is identified directly — no probing pass racing the reactive
107
+ # refresh's prune-and-rebuild.
108
+ rejected = {}
109
+ failures = {}
110
+ listeners.each do |node_key, listener|
111
+ patterns.each do |pattern|
112
+ listener.subscribe([pattern])
113
+ rescue ::Redis::CommandError => error
114
+ # Deterministic server rejection: left registered, it would fail
115
+ # every future catch-up on every primary. Evicted below, then raised.
116
+ rejected[pattern] ||= error
117
+ end
118
+ rescue StandardError => error
119
+ failures[node_key] = error
120
+ end
121
+ unless rejected.empty?
122
+ # Unconditional delete: the server rejects by pattern name, so a
123
+ # concurrent re-registration is just as poisoned. The refresher's
124
+ # catch-up unsubscribes nodes that accepted an evicted pattern.
125
+ @lock.synchronize { rejected.each_key { |pattern| @registry.delete(pattern) } }
126
+ end
127
+ # Every failed node is reported individually and healed by the refresher.
128
+ failures.each { |node_key, error| report_error(error, node_key) }
129
+ request_refresh(nil) unless rejected.empty? && failures.empty?
130
+ raise rejected.values.first unless rejected.empty?
131
+
132
+ # Reconcile via the refresher when the fan-out could not have done the
133
+ # job: no listeners at all (no connections = no error signal), or a
134
+ # concurrent unsubscribe undid ours after the fact.
135
+ if listeners.empty? || @lock.synchronize { patterns.any? { |pattern| !@registry.key?(pattern) } }
136
+ request_refresh(nil)
137
+ end
138
+ # A close racing this call tore the listeners down after our snapshot:
139
+ # returning success would lie about a subscription on a closed manager.
140
+ raise SubscriptionError, "keyspace notifications manager is closed" if closed?
141
+
142
+ nil
143
+ end
144
+
145
+ # Unsubscribe patterns (everything when called without arguments) on every
146
+ # primary. Unlike the standalone manager, tracking is removed FIRST: with N
147
+ # nodes a partial failure is normal, and keeping the pattern registered for
148
+ # one failed node would make the next refresh re-subscribe it on the N-1
149
+ # nodes that already unsubscribed. A node whose unsubscribe failed is
150
+ # reported and converges on the next refresh.
151
+ #
152
+ # @param patterns [Array<String>]
153
+ # @return [void]
154
+ def unsubscribe(*patterns)
155
+ patterns = patterns.map { |pattern| pattern.to_s.b }
156
+ targets = nil
157
+ listeners = @lock.synchronize do
158
+ targets = patterns.empty? ? @registry.keys : patterns
159
+ patterns.empty? ? @registry.clear : patterns.each { |pattern| @registry.delete(pattern) }
160
+ @listeners.to_a
161
+ end
162
+ # Nothing registered: an empty fan-out would mean "everything" at the
163
+ # node level and wipe patterns a concurrent subscribe just installed.
164
+ return if targets.empty?
165
+
166
+ # In-handler calls defer the ack-blocking fan-out, like #subscribe.
167
+ return request_refresh(nil) if dispatcher_thread?
168
+
169
+ # Always the captured targets — an empty list would mean "everything" at
170
+ # the node level and drop patterns added after our capture.
171
+ each_listener_best_effort(listeners) { |listener| listener.unsubscribe(targets) }
172
+ # A concurrent subscribe may have re-registered a target and had its node
173
+ # subscriptions undone by our fan-out; the refresher reconciles.
174
+ request_refresh(nil) if @lock.synchronize { targets.any? { |pattern| @registry.key?(pattern) } }
175
+ nil
176
+ end
177
+
178
+ # @!group Typed subscriptions (db is always 0 in cluster)
179
+
180
+ # Watch every event happening to keys matching +key+ on all primaries.
181
+ # @param key [String] key name or glob pattern
182
+ def subscribe_keyspace(key = "*", &handler)
183
+ subscribe(::Redis::KeyspaceNotifications::Channels.keyspace(key), handler: handler)
184
+ end
185
+
186
+ # Watch every key receiving events matching +event+ on all primaries.
187
+ # @param event [String] event name (e.g. "expired") or glob pattern
188
+ def subscribe_keyevent(event = "*", &handler)
189
+ subscribe(::Redis::KeyspaceNotifications::Channels.keyevent(event), handler: handler)
190
+ end
191
+
192
+ # Watch subkey-level events on keys matching +key+ (Redis 8.8+, flag `S`).
193
+ # @param key [String] key name or glob pattern
194
+ def subscribe_subkeyspace(key = "*", &handler)
195
+ subscribe(::Redis::KeyspaceNotifications::Channels.subkeyspace(key), handler: handler)
196
+ end
197
+
198
+ # Watch subkey-level events matching +event+ (Redis 8.8+, flag `T`).
199
+ # @param event [String] event name (e.g. "hdel") or glob pattern
200
+ def subscribe_subkeyevent(event = "*", &handler)
201
+ subscribe(::Redis::KeyspaceNotifications::Channels.subkeyevent(event), handler: handler)
202
+ end
203
+
204
+ # Watch events on one exact key + subkey pair (Redis 8.8+, flag `I`).
205
+ # The key is treated literally — glob metacharacters in it are escaped, since
206
+ # every manager subscription is a psubscribe pattern — while the subkey keeps
207
+ # its documented glob behavior.
208
+ # @param key [String] key name (must not contain "\n")
209
+ # @param subkey [String] subkey (e.g. hash field) or glob pattern
210
+ def subscribe_subkeyspaceitem(key, subkey = "*", &handler)
211
+ channels = ::Redis::KeyspaceNotifications::Channels
212
+ subscribe(channels.subkeyspaceitem(channels.glob_escape(key), subkey), handler: handler)
213
+ end
214
+
215
+ # Watch subkeys affected by +event+ on keys matching +key+ (Redis 8.8+, flag `V`).
216
+ # @param event [String] event name or glob pattern
217
+ # @param key [String] key name or glob pattern
218
+ def subscribe_subkeyspaceevent(event = "*", key = "*", &handler)
219
+ subscribe(::Redis::KeyspaceNotifications::Channels.subkeyspaceevent(event, key), handler: handler)
220
+ end
221
+
222
+ # @!endgroup
223
+
224
+ # Default handler for notifications whose pattern has no dedicated handler.
225
+ # @yieldparam notification [Redis::KeyspaceNotifications::Notification]
226
+ def on_notification(&block)
227
+ @lock.synchronize { @default_handler = block }
228
+ nil
229
+ end
230
+
231
+ # Replaces the error handler. Receives (error, node_key); must not raise.
232
+ def on_error(&block)
233
+ # Synchronized for the happens-before edge non-GVL runtimes need.
234
+ @lock.synchronize { @error_handler = block }
235
+ nil
236
+ end
237
+
238
+ # Called with the node_key after a node's subscriptions were (re-)established
239
+ # following a gap — its listener reconnected on its own, a refresh rebuilt
240
+ # it, or a refresh attached a primary not listened to before (a promoted
241
+ # replica under a new address, or a scale-out node). Notifications the node
242
+ # emitted during the gap are lost; use this to reconcile. The callback may
243
+ # fire more than once per gap, runs on a background thread, and should be
244
+ # fast and must not raise.
245
+ def on_reconnect(&block)
246
+ @lock.synchronize { @reconnect_handler = block }
247
+ nil
248
+ end
249
+
250
+ # Reconcile the per-node listeners with the current set of primaries: drop
251
+ # vanished/demoted/broken nodes, connect new primaries, and (re-)subscribe every
252
+ # listener to every registered pattern (idempotent for already-subscribed nodes).
253
+ # Runs automatically when a node connection error is reported; call it manually
254
+ # after adding primaries to the cluster.
255
+ #
256
+ # @return [void]
257
+ # @raise [Redis::Cluster::KeyspaceNotificationsRefreshError] when one or more
258
+ # primaries could not be subscribed (see its #errors for the per-node causes).
259
+ # Called from inside a notification handler, the reconciliation is instead
260
+ # deferred to the background refresher and nothing is raised
261
+ def refresh
262
+ # In-handler calls run on the dispatcher thread: the ack-blocking
263
+ # catch-ups would deadlock against node readers stuck on a full queue.
264
+ return request_refresh(nil) if dispatcher_thread?
265
+
266
+ # Reports and reconnect announcements are delivered only after the
267
+ # refresh lock is released (see ensure): the error handler is user code
268
+ # that may call #close or #refresh, which need this non-reentrant lock.
269
+ deferred_reports = []
270
+ deferred_reconnects = []
271
+ @refresh_lock.synchronize do
272
+ return if closed?
273
+
274
+ # Raises (keeping existing listeners) on a view that is not a topology
275
+ # to reconcile against.
276
+ primaries = current_primaries
277
+
278
+ failures = {}
279
+
280
+ # Prune vanished/demoted/unhealthy listeners under the lock; the
281
+ # ack-blocking catch-ups below run without it so dispatch and the API
282
+ # stay responsive.
283
+ stale = @lock.synchronize do
284
+ expect_subscribed = !@registry.empty?
285
+ gone_keys = @listeners.keys - primaries.keys
286
+ primaries.each_key do |node_key|
287
+ listener = @listeners[node_key]
288
+ gone_keys << node_key if listener && !listener.healthy?(expect_subscribed)
289
+ end
290
+ gone_keys.map { |node_key| @listeners.delete(node_key) }
291
+ end
292
+ # In parallel, like #close: each close joins that node's threads, and a
293
+ # serial prune would hold @refresh_lock for O(nodes) while #close
294
+ # waits on it unboundedly.
295
+ stale.compact.map { |listener| Thread.new { listener.close } }.each(&:join)
296
+
297
+ # Failure-path listeners are detached in the loop but closed together
298
+ # (in parallel) afterwards — the same O(nodes) stall argument.
299
+ doomed = []
300
+ primaries.each do |node_key, (host, port)|
301
+ # A racing close raises @closed first, then waits on @refresh_lock:
302
+ # abort at the node boundary instead of sitting out every remaining
303
+ # catch-up.
304
+ break if closed?
305
+
306
+ listener = @lock.synchronize { @listeners[node_key] }
307
+ created = false
308
+ begin
309
+ unless listener
310
+ created = true
311
+ listener = NodeListener.new(
312
+ node_key, sidecar_options(host, port), @queue,
313
+ on_error: method(:handle_node_error), on_reconnect: method(:handle_node_reconnect)
314
+ )
315
+ # Committed before catch-up so a racing subscribe fans out to
316
+ # this node too (both are idempotent).
317
+ @lock.synchronize { @listeners[node_key] = listener }
318
+ end
319
+ # Converge on the LIVE registry: a subscribe/unsubscribe completing
320
+ # between snapshot and catch-up would otherwise be undone with no
321
+ # later signal to correct it. The bound is a livelock guard.
322
+ snapshot = @lock.synchronize { @registry.keys }
323
+ converged = false
324
+ 5.times do
325
+ break if closed?
326
+
327
+ begin
328
+ listener.catch_up(snapshot)
329
+ rescue ::Redis::CommandError
330
+ # A server rejection is deterministic, NOT a node failure: the
331
+ # generic handling would delete every listener (all primaries
332
+ # reject the same pattern) and loop the refresher forever.
333
+ # Evict the culprit(s); an unattributable failure re-raises
334
+ # into the per-node failure handling.
335
+ raise if evict_rejected(listener, node_key, snapshot, reports: deferred_reports).empty?
336
+ end
337
+ current = @lock.synchronize { @registry.keys }
338
+ if current == snapshot
339
+ converged = true
340
+ break
341
+ end
342
+
343
+ snapshot = current
344
+ end
345
+ # Registry still churning at the bound: schedule the next
346
+ # reconciliation rather than accept a possibly-stale node silently.
347
+ request_refresh(nil) unless converged || closed?
348
+ # A NEWLY ATTACHED listener converged with patterns registered:
349
+ # announce the gap's end (deferred — user code never runs under the
350
+ # refresh lock). Keying on creation covers rebuilt listeners,
351
+ # promoted replicas under a new node_key, and scale-out primaries.
352
+ deferred_reconnects << node_key if created && converged && !snapshot.empty?
353
+ rescue StandardError => error
354
+ failures[node_key] = error
355
+ # The gap is announced by the refresh that eventually re-creates
356
+ # the node. The detached listener runs until the deferred close.
357
+ doomed << @lock.synchronize { @listeners.delete(node_key) }
358
+ end
359
+ end
360
+ doomed.compact.map { |listener| Thread.new { listener.close } }.each(&:join)
361
+ # An aborted (closing) refresh reports nothing: close is tearing the
362
+ # remaining listeners down right behind this lock.
363
+ raise KeyspaceNotificationsRefreshError, failures unless failures.empty? || closed?
364
+ end
365
+ nil
366
+ ensure
367
+ # Checked per item: a concurrent close can complete mid-loop, and
368
+ # callbacks that haven't started by then are dropped, not delivered (one
369
+ # already running can still finish — the same bounded exposure as a
370
+ # mid-flight handler outliving close).
371
+ deferred_reports&.each { |error, node_key| report_error(error, node_key) unless closed? }
372
+ deferred_reconnects&.each { |node_key| handle_node_reconnect(node_key) unless closed? }
373
+ end
374
+
375
+ # @return [Array<String>] "host:port" of every primary currently listened to
376
+ def node_keys
377
+ @lock.synchronize { @listeners.keys }
378
+ end
379
+
380
+ # @return [Array<String>] the registered patterns
381
+ def patterns
382
+ @lock.synchronize { @registry.keys }
383
+ end
384
+
385
+ # @return [Boolean] whether at least one pattern is registered and listeners are attached
386
+ def subscribed?
387
+ @lock.synchronize { !@registry.empty? && !@listeners.empty? }
388
+ end
389
+
390
+ # @return [Boolean]
391
+ def closed?
392
+ # Synchronized for the happens-before edge non-GVL runtimes need.
393
+ @lock.synchronize { @closed }
394
+ end
395
+
396
+ # Close every node listener, stop the dispatcher and release all connections.
397
+ # Idempotent.
398
+ #
399
+ # @return [void]
400
+ def close
401
+ # @closed is raised BEFORE waiting on @refresh_lock: an in-flight refresh
402
+ # aborts at its next node boundary once the flag is up, so the wait below
403
+ # ends promptly without skipping the teardown.
404
+ @lock.synchronize do
405
+ @closed = true
406
+ @refresh_cond.broadcast # wake the refresher (idle or in backoff) so it exits
407
+ end
408
+ # Still serialized with refresh: otherwise a refresh past its closed
409
+ # checks could recreate listeners on a torn-down manager.
410
+ @refresh_lock.synchronize do
411
+ listeners = @lock.synchronize { @listeners.values.tap { @listeners.clear } }
412
+ # Queue first: node readers blocked pushing into a full queue are stuck
413
+ # in Ruby, not I/O — only ClosedQueueError frees them.
414
+ @queue.close
415
+ # In parallel: serial teardown would make close O(nodes).
416
+ listeners.map { |listener| Thread.new { listener.close } }.each(&:join)
417
+ end
418
+ join_timeout = Redis::KeyspaceNotifications::Manager::DEFAULT_CLOSE_TIMEOUT
419
+ # close may run on the dispatcher (in-handler) or the refresher (error
420
+ # handler of a failed reactive refresh); a self-join raises ThreadError.
421
+ @refresher.join(join_timeout) unless @refresher.equal?(Thread.current)
422
+ @dispatcher.join(join_timeout) unless @dispatcher.equal?(Thread.current)
423
+ nil
424
+ end
425
+ alias stop close
426
+
427
+ private
428
+
429
+ def current_primaries
430
+ # CLUSTER NODES rather than CLUSTER SLOTS: membership output lists
431
+ # zero-slot primaries too, so a scale-out node gets its listener before
432
+ # the first migrated key arrives (slots moving in emit no error signal).
433
+ masters, dropped = @cluster.cluster("nodes").partition do |node|
434
+ flags = node["flags"]
435
+ # "fail?" (suspected) is kept — its slots are still assigned to it;
436
+ # confirmed-failed, addressless and handshaking nodes are dropped.
437
+ flags.include?("master") && (flags & %w[fail noaddr handshake]).empty?
438
+ end
439
+ # A dropped master still owning slots is a mid-failover view: reconciling
440
+ # against it would succeed with N-1 listeners and stop the refresher's
441
+ # retries, silently missing the promoted primary. Raise and retry.
442
+ if dropped.any? { |node| node["flags"].include?("master") && node["slots"] }
443
+ raise KeyspaceNotificationsRefreshError.new(
444
+ {}, "CLUSTER NODES reports a failed primary still owning slots " \
445
+ "(failover in progress); keeping existing listeners"
446
+ )
447
+ end
448
+ # No slot-owning primary at all (mid-reset, or a degraded node's view):
449
+ # tearing everything down would leave nothing to emit the connection
450
+ # errors that drive reactive recovery. Raise and retry.
451
+ if masters.none? { |node| node["slots"] }
452
+ raise KeyspaceNotificationsRefreshError.new(
453
+ {}, "CLUSTER NODES reported no slot-owning primaries; keeping existing listeners"
454
+ )
455
+ end
456
+
457
+ # "ip:port@cport" (a ",hostname" may trail the cport since Redis 7);
458
+ # rpartition keeps a bare IPv6 address's own colons intact.
459
+ addresses = masters.map { |node| node["ip_port"].split("@", 2).first.rpartition(":").values_at(0, 2) }
460
+ # Concealed endpoints announce empty addresses (clients are meant to
461
+ # reuse existing connection info, which per-node sidecars cannot do).
462
+ # Unless fixed_hostname supplies the dial target, fail loudly.
463
+ if !@base_options[:fixed_hostname] && addresses.any? { |ip, _| ip.nil? || ip.empty? }
464
+ raise KeyspaceNotificationsRefreshError.new(
465
+ {}, "CLUSTER NODES conceals node endpoints; per-node notification " \
466
+ "sidecars need reachable addresses (or the fixed_hostname option)"
467
+ )
468
+ end
469
+
470
+ # Distinct primaries collapsing onto one dial target: one sidecar cannot
471
+ # listen to them all — fail loudly instead of silently dropping the rest.
472
+ # Keyed on the EFFECTIVE dial target, not the announced address:
473
+ # fixed_hostname replaces the host at connect time, so primaries
474
+ # differing only by IP collapse onto one "hostname:port".
475
+ fixed_hostname = @base_options[:fixed_hostname]
476
+ dial_targets = addresses.map { |ip, port| "#{fixed_hostname || ip}:#{port}" }.uniq
477
+ if dial_targets.size < masters.size
478
+ raise KeyspaceNotificationsRefreshError.new(
479
+ {}, "CLUSTER NODES reports #{masters.size} primaries but only " \
480
+ "#{dial_targets.size} distinguishable endpoints; per-node notification " \
481
+ "sidecars need a unique address per primary"
482
+ )
483
+ end
484
+ addresses.to_h { |ip, port| ["#{ip}:#{port}", [ip, port]] }
485
+ end
486
+
487
+ CLUSTER_ONLY_OPTIONS = %i[
488
+ nodes replica replica_affinity fixed_hostname concurrency
489
+ connect_with_original_config max_startup_sample slow_command_timeout
490
+ command_routings
491
+ ].freeze
492
+ private_constant :CLUSTER_ONLY_OPTIONS
493
+
494
+ def sidecar_options(host, port)
495
+ options = @base_options.reject { |key, _| CLUSTER_ONLY_OPTIONS.include?(key) }
496
+ options.delete(:url)
497
+ options.delete(:path)
498
+ options.delete(:sentinels)
499
+ options.delete(:name)
500
+ options.delete(:role)
501
+ # A single-endpoint TLS setup (fixed_hostname) must dial the FQDN, not the announced IP.
502
+ host = @base_options[:fixed_hostname] if @base_options[:fixed_hostname]
503
+ # Transport retries forced OFF: each sidecar's core manager owns its
504
+ # reconnection schedule, so a cluster-level retry ladder must not run
505
+ # inside every sidecar connect attempt too.
506
+ connection_options_from_nodes.merge(options)
507
+ .merge(host: host, port: Integer(port), db: 0, reconnect_attempts: 0)
508
+ end
509
+
510
+ # Top-level :username/:password/:ssl are the supported configuration; as a
511
+ # convenience, credentials and TLS embedded in the first configured node
512
+ # (a `rediss://` URL, or Hash keys) are reused for the sidecars — the node
513
+ # list is often the only place they exist.
514
+ def connection_options_from_nodes
515
+ node = Array(@base_options[:nodes]).first
516
+ case node
517
+ when String
518
+ options_from_node_url(node)
519
+ when Hash
520
+ # Pass everything through except the seed's addressing (:host/:port/
521
+ # :url/:path) — sidecars dial the discovered primaries. Explicit keys
522
+ # override what the :url says.
523
+ url_options = node[:url] ? options_from_node_url(node[:url]) : {}
524
+ url_options.merge(node.except(:host, :port, :url, :path))
525
+ else
526
+ {}
527
+ end
528
+ rescue URI::InvalidURIError
529
+ {}
530
+ end
531
+
532
+ # Mirrors redis-cluster-client's parse_node_url (including its form-style
533
+ # decoding): the sidecars must authenticate with byte-identical credentials
534
+ # to the cluster client's own node connections. Stricter URI semantics
535
+ # would belong upstream, where both sides inherit them together.
536
+ def options_from_node_url(url)
537
+ uri = URI.parse(url)
538
+ {
539
+ username: uri.user ? URI.decode_www_form_component(uri.user) : nil,
540
+ password: uri.password ? URI.decode_www_form_component(uri.password) : nil,
541
+ ssl: uri.scheme == "rediss"
542
+ }.reject { |_, value| value.nil? || value == "" || value == false }
543
+ end
544
+
545
+ def each_listener_best_effort(listeners)
546
+ listeners.each do |node_key, listener|
547
+ yield listener
548
+ rescue StandardError => error
549
+ report_error(error, node_key)
550
+ request_refresh(node_key)
551
+ end
552
+ end
553
+
554
+ # A CommandError from a batch subscribe means the server rejected one of
555
+ # the patterns — deterministically, so it must not stay registered.
556
+ # Identify the culprit(s) by subscribing one pattern at a time, evict them
557
+ # from the registry, report each. Returns the rejected patterns mapped to
558
+ # their errors; empty when the failure was not attributable to any single
559
+ # pattern. With +reports+ (the refresh path) rejections are collected there
560
+ # instead — the error handler must never run under the refresh lock.
561
+ def evict_rejected(listener, node_key, patterns, reports: nil)
562
+ rejected = {}
563
+ patterns.each do |pattern|
564
+ listener.subscribe([pattern])
565
+ rescue ::Redis::CommandError => error
566
+ rejected[pattern] = error
567
+ end
568
+ return rejected if rejected.empty?
569
+
570
+ # Unconditional delete: the server rejects by pattern name, so a
571
+ # concurrent re-registration is just as poisoned.
572
+ @lock.synchronize { rejected.each_key { |pattern| @registry.delete(pattern) } }
573
+ rejected.each_value do |error|
574
+ reports ? reports << [error, node_key] : report_error(error, node_key)
575
+ end
576
+ rejected
577
+ end
578
+
579
+ # Called from node listener threads on every background error. Connection
580
+ # loss warrants topology reconciliation. A CommandError (on a node thread
581
+ # that is a rejected reconnect replay — user handlers run on the
582
+ # dispatcher, never here) warrants REGISTRY reconciliation: the node
583
+ # evicted the pattern locally, and without a refresh the canonical
584
+ # registry would keep reporting it with no signal left to converge on.
585
+ # Parse errors trigger nothing — the listener stays healthy.
586
+ def handle_node_error(node_key, error)
587
+ report_error(error, node_key)
588
+ request_refresh(node_key) if connection_failure?(error) || error.is_a?(::Redis::CommandError)
589
+ end
590
+
591
+ # Called from a node listener's own thread after its replay, and from
592
+ # refresh (post-lock) when a newly attached listener converged. Muted once
593
+ # close began: no user code after close returned.
594
+ def handle_node_reconnect(node_key)
595
+ handler = @lock.synchronize { @closed ? nil : @reconnect_handler }
596
+ handler&.call(node_key)
597
+ rescue StandardError => error
598
+ report_error(error, node_key)
599
+ end
600
+
601
+ def connection_failure?(error)
602
+ error.is_a?(::Redis::BaseConnectionError) || error.is_a?(::RedisClient::ConnectionError)
603
+ end
604
+
605
+ def request_refresh(_node_key)
606
+ @lock.synchronize do
607
+ @refresh_needed = true
608
+ @refresh_cond.broadcast
609
+ end
610
+ nil
611
+ end
612
+
613
+ def dispatcher_thread?
614
+ Thread.current.equal?(@dispatcher)
615
+ end
616
+
617
+ def spawn_dispatcher
618
+ thread = Thread.new do
619
+ while (notification = @queue.pop)
620
+ # Buffered items surviving a close are dropped: callers may have torn
621
+ # down handler dependencies the moment close returned.
622
+ dispatch(notification) unless closed?
623
+ end
624
+ end
625
+ thread.name = "redis-cluster-keyspace-notifications"
626
+ thread
627
+ end
628
+
629
+ # Reactive refreshes run on their own thread, NOT the dispatcher: during a
630
+ # refresh the dispatcher must keep draining the queue so blocked node
631
+ # readers can process the acks the refresh waits for. The thread also owns
632
+ # failure retries (exponential backoff) — the original signal was already
633
+ # consumed, and a partially-rebuilt node may emit no new one.
634
+ def spawn_refresher
635
+ thread = Thread.new do
636
+ retry_delay = nil
637
+ loop do
638
+ @lock.synchronize do
639
+ @refresh_cond.wait_until { @refresh_needed || @closed }
640
+ break if @closed
641
+
642
+ @refresh_needed = false
643
+ end
644
+ break if closed?
645
+
646
+ begin
647
+ refresh
648
+ retry_delay = nil
649
+ rescue StandardError => error
650
+ report_error(error, nil)
651
+ retry_delay = [(retry_delay || 0.25) * 2, 30.0].min
652
+ @lock.synchronize do
653
+ @refresh_needed = true
654
+ # Doubles as an interruptible backoff: a request_refresh or
655
+ # close broadcast cuts it short.
656
+ @refresh_cond.wait(retry_delay) unless @closed
657
+ end
658
+ end
659
+ end
660
+ end
661
+ thread.name = "redis-cluster-keyspace-notifications-refresher"
662
+ thread
663
+ end
664
+
665
+ # The handler is resolved from the live registry at dispatch time, so
666
+ # buffered events honor unsubscribes and handler replacements, and events
667
+ # for unregistered patterns are dropped rather than leaked.
668
+ def dispatch(notification)
669
+ key = notification.pattern&.b
670
+ handler = @lock.synchronize do
671
+ @registry.key?(key) ? (@registry[key] || @default_handler) : nil
672
+ end
673
+ handler&.call(notification)
674
+ rescue StandardError => error
675
+ report_error(error, nil)
676
+ end
677
+
678
+ def report_error(error, node_key)
679
+ handler = @lock.synchronize { @error_handler }
680
+ if handler
681
+ handler.call(error, node_key)
682
+ else
683
+ warn("Redis cluster keyspace notifications error#{" (#{node_key})" if node_key}: " \
684
+ "#{error.class}: #{error.message}")
685
+ end
686
+ rescue StandardError
687
+ nil # a broken error handler must never kill the dispatcher
688
+ end
689
+ end
690
+ end
691
+ end
data/lib/redis/cluster.rb CHANGED
@@ -44,6 +44,20 @@ class Redis
44
44
  class NodeMightBeDown < BaseError
45
45
  end
46
46
 
47
+ # Raised by Redis::Cluster::KeyspaceNotifications#refresh when one or more
48
+ # primaries could not be (re)subscribed.
49
+ class KeyspaceNotificationsRefreshError < BaseError
50
+ attr_reader :errors
51
+
52
+ # @param errors [Hash{String => StandardError}] "host:port" => cause
53
+ # @param error_message [String]
54
+ def initialize(errors, error_message = 'Some primaries could not be subscribed for keyspace notifications')
55
+ @errors = errors
56
+ error_message = "#{error_message}: #{errors.keys.join(', ')}" unless errors.empty?
57
+ super(error_message)
58
+ end
59
+ end
60
+
47
61
  def connection
48
62
  raise NotImplementedError, "Redis::Cluster doesn't implement #connection"
49
63
  end
@@ -62,11 +76,18 @@ class Redis
62
76
  # @option options [Symbol] :replica_affinity scale reading strategy, currently supported: `:random`, `:latency`
63
77
  # @option options [String] :fixed_hostname Specify a FQDN if cluster mode enabled and
64
78
  # client has to connect nodes via single endpoint with SSL/TLS
65
- # @option options [Class] :connector Class of custom connector
66
79
  # @option options [String, Array<String>, false] :driver_info Identity a library built on top of
67
80
  # `redis-rb` reports to every node via `CLIENT SETINFO`, shown as `lib-name=redis-rb(<driver_info>)`
68
81
  # in `CLIENT LIST`. The recommended format is `<name>_v<version>`; an Array is joined with `;`.
69
82
  # Pass `false` to disable client identification entirely.
83
+ # @option options [Boolean] :himport_auto_prepare (true) Whether to automatically repair a lost
84
+ # `HIMPORT` fieldset (re-fan out the last prepared schema to all masters and retry the
85
+ # `himport_set` once) when a node reports it was lost (failover, topology reload, redirection).
86
+ # When `false`, the error is raised to the caller, who is responsible for retaining the schema
87
+ # and calling `himport_prepare` again.
88
+ # @option options [Hash] :command_routings Per-command `request_policy`/`response_policy`
89
+ # overrides passed to the driver, merged on top of redis-rb's own defaults (e.g. `waitaof`)
90
+ # so caller-supplied entries win.
70
91
  #
71
92
  # @return [Redis::Cluster] a new client instance
72
93
  def initialize(*)
@@ -79,9 +100,13 @@ class Redis
79
100
  # @see https://redis.io/commands#cluster Reference of cluster command
80
101
  #
81
102
  # @param subcommand [String, Symbol] the subcommand of cluster command
82
- # e.g. `:slots`, `:nodes`, `:slaves`, `:info`
103
+ # e.g. `:slots`, `:nodes`, `:slaves`, `:info`, `:'slot-stats'`
83
104
  #
84
105
  # @return [Object] depends on the subcommand
106
+ #
107
+ # @note `:'slot-stats'` (Redis 8.2) is sent to every primary and the per-node replies are
108
+ # concatenated, so `LIMIT n` yields up to `n` slots per primary. Each entry is reshaped
109
+ # into `[slot, { "key-count" => Integer, ... }]`.
85
110
  def cluster(subcommand, *args)
86
111
  subcommand = subcommand.to_s.downcase
87
112
  block = case subcommand
@@ -93,6 +118,8 @@ class Redis
93
118
  HashifyClusterSlaves
94
119
  when 'info'
95
120
  HashifyInfo
121
+ when 'slot-stats'
122
+ HashifyClusterSlotStats
96
123
  else
97
124
  Noop
98
125
  end
@@ -147,6 +174,20 @@ class Redis
147
174
  # last prepared schema is re-fanned out — through these overrides — and the SET retried
148
175
  # once) are inherited from the Redis superclass unchanged; `himport_set` needs no override.
149
176
 
177
+ # Build a cluster-aware keyspace-notification manager: it subscribes on **every
178
+ # primary** (notifications are node-local in cluster and never forwarded on the
179
+ # cluster bus — a plain subscribe/psubscribe on a notification channel would
180
+ # silently receive only ~1/N of the events) and dispatches parsed notifications
181
+ # to handlers from a single dispatcher thread. See
182
+ # Redis::Cluster::KeyspaceNotifications for the full semantics.
183
+ #
184
+ # @param error_handler [#call, nil] receives (error, node_key) for every background error
185
+ # @param queue_size [Integer] bound of the shared dispatch queue
186
+ # @return [Redis::Cluster::KeyspaceNotifications]
187
+ def keyspace_notifications(error_handler: nil, queue_size: KeyspaceNotifications::DEFAULT_QUEUE_SIZE)
188
+ KeyspaceNotifications.new(self, base_options: @options, error_handler: error_handler, queue_size: queue_size)
189
+ end
190
+
150
191
  def himport_prepare(fieldset_name, *fields)
151
192
  reply = super
152
193
  reply.is_a?(Array) ? reply.first : reply
@@ -162,12 +203,64 @@ class Redis
162
203
  reply.is_a?(Array) ? reply.max : reply
163
204
  end
164
205
 
206
+ HOTKEYS_NOT_SUPPORTED = 'HOTKEYS commands are not supported in cluster mode: the tracking ' \
207
+ 'session is state of a single node. Connect to that node with ' \
208
+ 'Redis.new(host:, port:) instead.'
209
+ private_constant :HOTKEYS_NOT_SUPPORTED
210
+
211
+ def hotkeys_start(**)
212
+ raise NotImplementedError, HOTKEYS_NOT_SUPPORTED
213
+ end
214
+
215
+ def hotkeys_get
216
+ raise NotImplementedError, HOTKEYS_NOT_SUPPORTED
217
+ end
218
+
219
+ def hotkeys_stop
220
+ raise NotImplementedError, HOTKEYS_NOT_SUPPORTED
221
+ end
222
+
223
+ def hotkeys_reset
224
+ raise NotImplementedError, HOTKEYS_NOT_SUPPORTED
225
+ end
226
+
227
+ # WAITAOF on cluster: the guarantee is per connection, so the command must reach every
228
+ # primary over the connection that carried this client's writes. The driver leaves it on
229
+ # single-node routing (no aggregation for its `agg_min` tip over array replies), so
230
+ # DEFAULT_COMMAND_ROUTINGS routes it to all shards and the driver returns one
231
+ # `[local, replicas]` pair per primary. Aggregation has to happen here rather than in a
232
+ # reply block on the shared command: the driver applies reply blocks per node, before it
233
+ # collects the fan-out. Each position is collapsed with its minimum, as the server's
234
+ # `response_policy:agg_min` tip prescribes, so the standalone thresholds keep their
235
+ # meaning: `local` is 1 only if every primary fsynced the writes, and `replicas` is the
236
+ # fewest acks any shard got, so `replicas >= numreplicas` holds on every shard. (A sum
237
+ # would let well-replicated shards mask one that is lagging.) Inside `pipelined`/`multi`
238
+ # the driver routes the command to one node and the plain pair comes back, so no
239
+ # aggregation is needed there — but that single node is picked by the driver
240
+ # (`any_replica_node_key`), not by which node carried the pipeline's writes, so the
241
+ # per-connection guarantee is still lost even though the reply shape is correct. The Array
242
+ # guard passes a plain pair through (caller-supplied routing, or a driver that aggregates
243
+ # natively).
244
+ def waitaof(numlocal, numreplicas, timeout)
245
+ reply = super
246
+ reply.first.is_a?(Array) ? reply.transpose.map(&:min) : reply
247
+ end
248
+
165
249
  private
166
250
 
251
+ # Routing overrides handed to redis-cluster-client for commands whose server tips it does
252
+ # not act on; see #waitaof. Caller-supplied `command_routings` are merged on top and win.
253
+ DEFAULT_COMMAND_ROUTINGS = {
254
+ 'waitaof' => { request_policy: 'all_shards' }.freeze
255
+ }.freeze
256
+ private_constant :DEFAULT_COMMAND_ROUTINGS
257
+
167
258
  def initialize_client(options)
259
+ command_routings = DEFAULT_COMMAND_ROUTINGS.merge((options[:command_routings] || {}).transform_keys(&:to_s))
168
260
  # protocol defaults to 3 (RESP3) but a caller-provided protocol: in options overrides it.
169
261
  cluster_config = RedisClient.cluster(
170
262
  protocol: 3, **options,
263
+ command_routings: command_routings,
171
264
  driver_info: ::Redis::LibIdentity.driver_info(options[:driver_info]),
172
265
  client_implementation: ::Redis::Cluster::Client
173
266
  )
@@ -177,3 +270,4 @@ class Redis
177
270
  end
178
271
 
179
272
  require "redis/cluster/client"
273
+ require "redis/cluster/keyspace_notifications"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: redis-clustering
3
3
  version: !ruby/object:Gem::Version
4
- version: 6.0.0
4
+ version: 6.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ezra Zygmuntowicz
@@ -15,7 +15,7 @@ authors:
15
15
  - Pieter Noordhuis
16
16
  bindir: bin
17
17
  cert_chain: []
18
- date: 2026-07-31 00:00:00.000000000 Z
18
+ date: 2026-11-23 00:00:00.000000000 Z
19
19
  dependencies:
20
20
  - !ruby/object:Gem::Dependency
21
21
  name: redis
@@ -23,28 +23,28 @@ dependencies:
23
23
  requirements:
24
24
  - - '='
25
25
  - !ruby/object:Gem::Version
26
- version: 6.0.0
26
+ version: 6.1.0
27
27
  type: :runtime
28
28
  prerelease: false
29
29
  version_requirements: !ruby/object:Gem::Requirement
30
30
  requirements:
31
31
  - - '='
32
32
  - !ruby/object:Gem::Version
33
- version: 6.0.0
33
+ version: 6.1.0
34
34
  - !ruby/object:Gem::Dependency
35
35
  name: redis-cluster-client
36
36
  requirement: !ruby/object:Gem::Requirement
37
37
  requirements:
38
38
  - - '='
39
39
  - !ruby/object:Gem::Version
40
- version: 0.16.7
40
+ version: 0.18.0
41
41
  type: :runtime
42
42
  prerelease: false
43
43
  version_requirements: !ruby/object:Gem::Requirement
44
44
  requirements:
45
45
  - - '='
46
46
  - !ruby/object:Gem::Version
47
- version: 0.16.7
47
+ version: 0.18.0
48
48
  description: |2
49
49
  A Ruby client that tries to match Redis' Cluster API one-to-one, while still
50
50
  providing an idiomatic interface.
@@ -60,6 +60,8 @@ files:
60
60
  - lib/redis-clustering.rb
61
61
  - lib/redis/cluster.rb
62
62
  - lib/redis/cluster/client.rb
63
+ - lib/redis/cluster/keyspace_notifications.rb
64
+ - lib/redis/cluster/keyspace_notifications/node_listener.rb
63
65
  - lib/redis/cluster/transaction_adapter.rb
64
66
  - lib/redis/cluster/version.rb
65
67
  homepage: https://github.com/redis/redis-rb/blob/master/cluster
@@ -68,9 +70,9 @@ licenses:
68
70
  metadata:
69
71
  bug_tracker_uri: https://github.com/redis/redis-rb/issues
70
72
  changelog_uri: https://github.com/redis/redis-rb/blob/master/cluster/CHANGELOG.md
71
- documentation_uri: https://www.rubydoc.info/gems/redis/6.0.0
73
+ documentation_uri: https://www.rubydoc.info/gems/redis/6.1.0
72
74
  homepage_uri: https://github.com/redis/redis-rb/blob/master/cluster
73
- source_code_uri: https://github.com/redis/redis-rb/tree/v6.0.0/cluster
75
+ source_code_uri: https://github.com/redis/redis-rb/tree/v6.1.0/cluster
74
76
  rdoc_options: []
75
77
  require_paths:
76
78
  - lib