redis 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.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +114 -0
  3. data/README.md +172 -5
  4. data/lib/redis/client.rb +5 -1
  5. data/lib/redis/commands/arrays.rb +358 -0
  6. data/lib/redis/commands/bitmaps.rb +24 -0
  7. data/lib/redis/commands/bless.rb +115 -0
  8. data/lib/redis/commands/cluster.rb +9 -2
  9. data/lib/redis/commands/hashes.rb +250 -7
  10. data/lib/redis/commands/keys.rb +48 -11
  11. data/lib/redis/commands/modules/json.rb +27 -2
  12. data/lib/redis/commands/modules/search/aggregation.rb +2 -1
  13. data/lib/redis/commands/modules/search/field.rb +11 -2
  14. data/lib/redis/commands/modules/search/hybrid.rb +3 -0
  15. data/lib/redis/commands/modules/search/index.rb +2 -1
  16. data/lib/redis/commands/modules/search/miscellaneous.rb +2 -1
  17. data/lib/redis/commands/modules/search/query.rb +2 -2
  18. data/lib/redis/commands/modules/search/schema.rb +4 -0
  19. data/lib/redis/commands/scripting.rb +109 -0
  20. data/lib/redis/commands/server.rb +158 -7
  21. data/lib/redis/commands/sets.rb +270 -0
  22. data/lib/redis/commands/sorted_sets.rb +131 -6
  23. data/lib/redis/commands/streams.rb +284 -33
  24. data/lib/redis/commands/strings.rb +232 -6
  25. data/lib/redis/commands/transactions.rb +6 -1
  26. data/lib/redis/commands/vector_sets.rb +407 -0
  27. data/lib/redis/commands.rb +169 -6
  28. data/lib/redis/distributed.rb +539 -22
  29. data/lib/redis/hash_ring.rb +2 -1
  30. data/lib/redis/keyspace_notifications/channels.rb +121 -0
  31. data/lib/redis/keyspace_notifications/manager.rb +1121 -0
  32. data/lib/redis/keyspace_notifications/notification.rb +95 -0
  33. data/lib/redis/keyspace_notifications/parser.rb +170 -0
  34. data/lib/redis/keyspace_notifications.rb +59 -0
  35. data/lib/redis/pipeline.rb +17 -5
  36. data/lib/redis/ractorize.rb +6 -0
  37. data/lib/redis/subscribe.rb +80 -2
  38. data/lib/redis/version.rb +1 -1
  39. data/lib/redis/xxh3.rb +354 -0
  40. data/lib/redis.rb +29 -8
  41. metadata +16 -6
@@ -0,0 +1,1121 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Redis
4
+ module KeyspaceNotifications
5
+ # Owns a dedicated connection and a background listener thread, and dispatches
6
+ # parsed {Notification} objects to per-pattern handlers.
7
+ #
8
+ # Every subscription is a +psubscribe+ pattern (a pattern without glob characters
9
+ # matches itself literally): the listener loop stays terminable, handler routing
10
+ # is an exact lookup on the matched pattern, and database wildcards work. When
11
+ # several subscribed patterns match one message, each handler fires once.
12
+ #
13
+ # Handlers run on the listener thread: they should be fast and must not call
14
+ # blocking Redis commands on the manager's own connection. Handler exceptions
15
+ # and parse errors are reported to the error handler and never kill the listener.
16
+ #
17
+ # On connection loss the manager reconnects (per +reconnect_attempts+, an
18
+ # exponential 0.5s → 30s ladder by default) and re-subscribes every registered
19
+ # pattern. A pattern the server rejects on that replay (e.g. permissions revoked
20
+ # since it was subscribed) is evicted and reported instead of failing every
21
+ # reconnect. Notifications published while the connection was down are lost
22
+ # (pub/sub is fire-and-forget) — use {#on_reconnect} to reconcile after a gap.
23
+ class Manager
24
+ DEFAULT_CLOSE_TIMEOUT = 2
25
+ # A fresh object per (re-)subscription, so concurrent operations can tell "the
26
+ # registration I captured" from "the same pattern re-registered meanwhile".
27
+ # +failed+ marks it dead for good (its subscribe rolled back, or an unsubscribe
28
+ # targeting it completed) so a rollback never resurrects it; a timed-out
29
+ # unsubscribe does NOT mark — that registration legitimately lives on.
30
+ Registration = Struct.new(:handler, :failed)
31
+ private_constant :Registration
32
+ # Sleep per consecutive reconnect attempt; exhausted = give up. The budget
33
+ # resets after every healthy session.
34
+ DEFAULT_RECONNECT_ATTEMPTS = [0.5, 1, 2, 4, 8, 16, 30, 30, 30, 30].freeze
35
+ SUBSCRIBE_ACK_TIMEOUT = 5
36
+
37
+ # @param redis [Redis] a dedicated client the manager takes ownership of
38
+ # (it is closed by {#close}; it must not be used for anything else)
39
+ # @param error_handler [#call, nil] receives every background error; defaults
40
+ # to warning on $stderr
41
+ # @param reconnect_attempts [Integer, Array<Integer, Float>] number of attempts
42
+ # trying to reconnect (with no sleep in between), or a list of sleep durations
43
+ # between attempts — the same semantics as the `reconnect_attempts` option of
44
+ # {Redis#initialize}. The budget resets after every successful
45
+ # (re)subscription; an empty list disables reconnection entirely
46
+ def initialize(redis:, error_handler: nil, reconnect_attempts: DEFAULT_RECONNECT_ATTEMPTS)
47
+ @redis = redis
48
+ @error_handler = error_handler
49
+ # Validated here so a bad value fails at the call site instead of killing
50
+ # the listener thread (outside its rescue) after the first connection loss.
51
+ @reconnect_attempts = case reconnect_attempts
52
+ when Integer
53
+ Array.new(reconnect_attempts, 0).freeze
54
+ when Array
55
+ # NaN/Infinity/Complex satisfy Numeric but blow up the backoff
56
+ # arithmetic; real? first — Complex has no #>=.
57
+ unless reconnect_attempts.all? { |delay| delay.is_a?(Numeric) && delay.real? && delay.finite? && delay >= 0 }
58
+ raise ArgumentError, "reconnect_attempts must contain only finite, non-negative sleep durations"
59
+ end
60
+
61
+ reconnect_attempts.dup.freeze
62
+ else
63
+ raise ArgumentError,
64
+ "reconnect_attempts must be an Integer or an Array of sleep durations, " \
65
+ "got #{reconnect_attempts.class}"
66
+ end
67
+ @handlers = {} # pattern (BINARY String) => handler (Proc, nil for default)
68
+ # pattern => confirmation GENERATION (monotonic) acked on the current
69
+ # session. Presence answers "is it subscribed?"; a re-subscribing wait
70
+ # compares the generation against its install-time snapshot so only an
71
+ # ack that arrived AFTER the install satisfies it — the entry survives a
72
+ # same-session replacement (the server-side subscription persists).
73
+ @confirmed = {}
74
+ @confirm_seq = 0
75
+ # pattern => queue of unconsumed psubscribe acks in wire order; each entry
76
+ # is the issuing blocking batch's seq (nil for writes with no waiter).
77
+ # Acks arrive in command order, so each shifts the OLDEST entry. A
78
+ # non-final ack resolves nothing pattern-wide but retires its own batch
79
+ # from rejection attribution. Dies with its session.
80
+ @pending_acks = {}
81
+ @default_handler = nil
82
+ @reconnect_handler = nil
83
+ @lock = Monitor.new
84
+ @cond = @lock.new_cond
85
+ @thread = nil
86
+ @listener_error = nil
87
+ @listener_error_epoch = 0
88
+ @reconnect_now = false
89
+ @removing = {} # pattern => the Registration an in-flight unsubscribe targets
90
+ # pattern => { entry:, batch:, seq: } for in-handler registrations not yet
91
+ # server-acked; a session rejection evicts only the oldest (culprit) batch.
92
+ # Age is an explicit seq — re-marking keeps the original Hash position, so
93
+ # map order lies about command order. Dies with its session: a stale
94
+ # marker would win the next session's rejection attribution over the
95
+ # replay itself (cross-session poison is the probing replay's job).
96
+ @unvalidated = {}
97
+ # pattern => { entry:, seq: } for a probing session's unacked single-pattern
98
+ # replay commands. Dies with its session; a lost probe just re-probes.
99
+ @probe_inflight = {}
100
+ # Unacked patterns of the session-opening batch, with @opening_seq its
101
+ # position on the @issue_seq axis: represents the opening in rejection
102
+ # attribution, or its rejection would be pinned on a later command. Dies
103
+ # with its session.
104
+ @opening_pending = {}
105
+ @opening_seq = nil
106
+ # True from opening-ack tracking until the first ack arrives. The
107
+ # subscription client becomes visible to writers a beat before the opening
108
+ # write hits the socket; a write in that gap would precede the opening on
109
+ # the wire and invert @pending_acks against reply order, so
110
+ # write_to_session refuses writes while set. Lifted at session end.
111
+ @establishing = false
112
+ # Issue seq of the blocking subscribe a session-killing rejection was
113
+ # attributed to (nil otherwise). A waiter raises a fresh CommandError only
114
+ # when it names ITS command — raising to every waiter sharing the session
115
+ # rolled back valid registrations (and misled the cluster manager's probes).
116
+ @rejected_wait = nil
117
+ # Set when a rejection was unattributable (the batch replay itself was
118
+ # rejected): the next session replays one pattern per command so the
119
+ # rejection lands on exactly the poisoned pattern.
120
+ @probe_replay = false
121
+ # Set when the listener died with registrations still on the books: the
122
+ # next start is a restart after a lossy gap and must run as a reconnect
123
+ # so {#on_reconnect} announces it.
124
+ @resume_reconnecting = false
125
+ # Wire-orders every issued subscribe batch (assigned under @lock at write
126
+ # time); rejection attribution spans blocking, in-handler, probe and
127
+ # opening commands on this one axis.
128
+ @issue_seq = 0
129
+ # issue seq => the blocking subscribe's patterns still awaiting their own
130
+ # acks. An entry lives until its wait exits or every one of its command's
131
+ # acks was consumed (per-command tokens, not pattern-wide confirmation —
132
+ # an acked batch must retire from rejection attribution immediately).
133
+ @inflight_waits = {}
134
+ # Bumped per session-opening command; waits re-issue an unconfirmed
135
+ # pattern at most ONCE per session (duplicates stack pending acks the
136
+ # final-ack gate must drain).
137
+ @session_seq = 0
138
+ @closing = false
139
+ @closed = false
140
+ end
141
+
142
+ # Subscribe to notification channel patterns (build them with {Channels}).
143
+ # Re-subscribing a known pattern replaces its handler. Blocks until the server
144
+ # confirms every pattern, so no notification is missed after it returns. When
145
+ # it raises instead, no trace is left: the registration is rolled back and any
146
+ # pattern the server did confirm in the meantime is reverted.
147
+ # When called from inside a handler it cannot wait for the confirmation (only
148
+ # the listener thread itself reads acknowledgments) and returns immediately
149
+ # after issuing the command instead.
150
+ #
151
+ # @param patterns [Array<String>] channel names or psubscribe patterns
152
+ # @param handler [#call, nil] receives each {Notification}; falls back to the
153
+ # {#on_notification} default handler when nil
154
+ # @return [void]
155
+ # @raise [SubscriptionError] when the manager is closed or confirmation times out
156
+ def subscribe(*patterns, handler: nil, &block)
157
+ raise ArgumentError, "no patterns given" if patterns.empty?
158
+
159
+ handler ||= block
160
+ patterns = patterns.map { |pattern| pattern.to_s.b }
161
+ previous = {}
162
+ installed = {}
163
+ stale_confirmations = {}
164
+ issue_seq = nil
165
+ error_epoch = nil
166
+ @lock.synchronize do
167
+ raise SubscriptionError, "keyspace notifications manager is closed" if @closed || @closing
168
+
169
+ patterns.each do |pattern|
170
+ # Snapshot the previous registration for rollback. The handler must be
171
+ # registered before the command is issued: matching messages can
172
+ # arrive ahead of our ack processing.
173
+ unless previous.key?(pattern)
174
+ previous[pattern] = @handlers.key?(pattern) ? { entry: @handlers[pattern] } : nil
175
+ end
176
+ @handlers[pattern] = installed[pattern] = Registration.new(handler)
177
+ # A (re-)subscribe demands a FRESH acknowledgment: the wait accepts
178
+ # only a generation newer than this snapshot, so a replaced
179
+ # registration's confirmation can't report success for a command the
180
+ # server may still reject. The entry itself is kept — the server-side
181
+ # subscription persists across a same-session replacement.
182
+ stale_confirmations[pattern] = @confirmed[pattern]
183
+ end
184
+ # Sequenced in the same hold as the write, so batch age reflects true
185
+ # wire order.
186
+ issue_seq = (@issue_seq += 1)
187
+ # The error-freshness epoch is sampled in this same hold too: sampled at
188
+ # wait entry instead, the listener could process our own rejection in
189
+ # the gap and the waiter would read it as stale (converging via seconds
190
+ # of replay bounces instead of raising promptly).
191
+ error_epoch = @listener_error_epoch
192
+ @inflight_waits[issue_seq] = patterns.uniq unless listener_thread?
193
+ if listening?
194
+ if write_to_session(:psubscribe, patterns)
195
+ track_pending_acks(patterns, issue_seq)
196
+ else
197
+ # Session down (possibly parked in a long backoff): reconnect NOW so
198
+ # the replay covers this pattern within the wait.
199
+ @reconnect_now = true
200
+ @cond.broadcast
201
+ end
202
+ else
203
+ # A dead listener still has every prior registration: restart with the
204
+ # COMPLETE registry (as a reconnect — see start_listener), or earlier
205
+ # subscriptions would silently stop receiving.
206
+ start_listener(@handlers.keys)
207
+ end
208
+ end
209
+
210
+ # In-handler call: this is the listener thread, the only one that can read
211
+ # acks, so waiting would stall delivery. Nobody can roll back a rejection
212
+ # either — mark the registrations unvalidated so a session-killing
213
+ # rejection evicts them instead of poisoning every replay.
214
+ if listener_thread?
215
+ @lock.synchronize do
216
+ seq = issue_seq
217
+ patterns.each do |pattern|
218
+ # Mark only the still-live registration (a stale marker matches no
219
+ # future ack). `installed` doubles as the batch token: a rejection
220
+ # is attributable to the OLDEST outstanding batch.
221
+ if @handlers[pattern].equal?(installed[pattern])
222
+ @unvalidated[pattern] = { entry: installed[pattern], batch: installed, seq: seq }
223
+ end
224
+ end
225
+ end
226
+ return
227
+ end
228
+
229
+ begin
230
+ wait_for_confirmation(patterns, installed, issue_seq, stale_confirmations, error_epoch)
231
+ rescue StandardError
232
+ rollback_registration(previous, installed)
233
+ raise
234
+ ensure
235
+ # Resolved either way; attribution must stop considering this batch.
236
+ @lock.synchronize { @inflight_waits.delete(issue_seq) }
237
+ end
238
+ end
239
+
240
+ # Unsubscribe patterns; with no arguments, everything. Blocks until the server
241
+ # acknowledges, and only then removes the local registration — when it raises,
242
+ # local state still matches the server (the patterns remain subscribed) and the
243
+ # call can simply be retried. In-flight notifications received before the
244
+ # server's acknowledgment are still dispatched to their handler.
245
+ # When called from inside a handler (the one-shot subscription pattern) it
246
+ # cannot wait for the confirmation (only the listener thread itself reads
247
+ # acknowledgments) and commits the removal immediately after issuing the
248
+ # command; no further notifications reach the handler either way.
249
+ # Unsubscribing the last pattern stops the listener thread — a later
250
+ # {#subscribe} restarts it.
251
+ #
252
+ # @param patterns [Array<String>]
253
+ # @return [void]
254
+ # @raise [SubscriptionError] when the server's acknowledgment times out
255
+ def unsubscribe(*patterns)
256
+ patterns = patterns.map { |pattern| pattern.to_s.b }
257
+ targets = nil
258
+ owned = {}
259
+ @lock.synchronize do
260
+ targets = patterns.empty? ? @handlers.keys : patterns.select { |pattern| @handlers.key?(pattern) }
261
+ return if targets.empty?
262
+
263
+ # Capture the exact registrations being removed: a concurrent
264
+ # replacement must neither be deleted nor fought. The @removing marks
265
+ # tell the punsubscribe-ack invariant which registration each ack
266
+ # targets, so it can re-establish a replacement our command killed.
267
+ targets.each do |pattern|
268
+ owned[pattern] = @handlers[pattern]
269
+ @removing[pattern] = owned[pattern]
270
+ end
271
+
272
+ if listening?
273
+ # Always the captured targets, never a blanket PUNSUBSCRIBE (which
274
+ # would also drop patterns added after our capture). A false return
275
+ # means the session is down — removal is already consistent.
276
+ write_to_session(:punsubscribe, targets)
277
+ end
278
+ end
279
+
280
+ begin
281
+ if listener_thread?
282
+ # In-handler call (one-shot pattern): can't wait for the ack — commit
283
+ # the removal now. In-flight messages are dropped by dispatch's
284
+ # registry check; a replay race is reverted at ack time.
285
+ @lock.synchronize do
286
+ targets.each do |pattern|
287
+ # Dead for good: a failed subscribe's rollback must never
288
+ # resurrect this registration.
289
+ owned[pattern].failed = true
290
+ next unless @handlers[pattern].equal?(owned[pattern])
291
+
292
+ @handlers.delete(pattern)
293
+ # Purge the pre-ack validation marker too, or it leaks forever.
294
+ @unvalidated.delete(pattern) if @unvalidated[pattern]&.fetch(:entry).equal?(owned[pattern])
295
+ end
296
+ end
297
+ return
298
+ end
299
+
300
+ wait_for_removal(targets, owned)
301
+ @lock.synchronize do
302
+ targets.each do |pattern|
303
+ # Dead for good: a failed subscribe's rollback must never
304
+ # resurrect this registration.
305
+ owned[pattern].failed = true
306
+ next unless @handlers[pattern].equal?(owned[pattern])
307
+
308
+ @handlers.delete(pattern)
309
+ # Purge the pre-ack validation marker too, or it leaks forever.
310
+ @unvalidated.delete(pattern) if @unvalidated[pattern]&.fetch(:entry).equal?(owned[pattern])
311
+ end
312
+ # A reconnect replay may have re-subscribed a target meanwhile; sweep
313
+ # anything still acknowledged that no registration owns.
314
+ sweep = targets.select { |pattern| @confirmed.key?(pattern) && !@handlers.key?(pattern) }
315
+ punsubscribe_quietly(sweep)
316
+ # The listener may have exited on this removal's ack while a
317
+ # replacement landed after its recheck — revive it for the survivors.
318
+ restart_dead_listener
319
+ end
320
+ ensure
321
+ # Late acks are then judged purely by the live registry: a
322
+ # still-registered pattern is re-established instead of matching a
323
+ # stale mark.
324
+ @lock.synchronize do
325
+ targets.each { |pattern| @removing.delete(pattern) if @removing[pattern].equal?(owned[pattern]) }
326
+ end
327
+ end
328
+ nil
329
+ end
330
+
331
+ # @!group Typed subscriptions
332
+
333
+ # Watch every event happening to keys matching +key+.
334
+ # @param key [String] key name or glob pattern
335
+ # @param db [Integer, String] database index or "*"
336
+ def subscribe_keyspace(key = "*", db: 0, &handler)
337
+ subscribe(Channels.keyspace(key, db: db), handler: handler)
338
+ end
339
+
340
+ # Watch every key receiving events matching +event+.
341
+ # @param event [String] event name (e.g. "expired") or glob pattern
342
+ # @param db [Integer, String] database index or "*"
343
+ def subscribe_keyevent(event = "*", db: 0, &handler)
344
+ subscribe(Channels.keyevent(event, db: db), handler: handler)
345
+ end
346
+
347
+ # Watch subkey-level events on keys matching +key+ (Redis 8.8+, flag `S`).
348
+ # @param key [String] key name or glob pattern
349
+ # @param db [Integer, String] database index or "*"
350
+ def subscribe_subkeyspace(key = "*", db: 0, &handler)
351
+ subscribe(Channels.subkeyspace(key, db: db), handler: handler)
352
+ end
353
+
354
+ # Watch subkey-level events matching +event+ (Redis 8.8+, flag `T`).
355
+ # @param event [String] event name (e.g. "hdel") or glob pattern
356
+ # @param db [Integer, String] database index or "*"
357
+ def subscribe_subkeyevent(event = "*", db: 0, &handler)
358
+ subscribe(Channels.subkeyevent(event, db: db), handler: handler)
359
+ end
360
+
361
+ # Watch events on one exact key + subkey pair (Redis 8.8+, flag `I`).
362
+ # The key is treated literally — glob metacharacters in it are escaped, since
363
+ # every manager subscription is a psubscribe pattern — while the subkey keeps
364
+ # its documented glob behavior.
365
+ # @param key [String] key name (must not contain "\n")
366
+ # @param subkey [String] subkey (e.g. hash field) or glob pattern
367
+ # @param db [Integer, String] database index or "*"
368
+ def subscribe_subkeyspaceitem(key, subkey = "*", db: 0, &handler)
369
+ subscribe(Channels.subkeyspaceitem(Channels.glob_escape(key), subkey, db: db), handler: handler)
370
+ end
371
+
372
+ # Watch subkeys affected by +event+ on keys matching +key+ (Redis 8.8+, flag `V`).
373
+ # @param event [String] event name or glob pattern
374
+ # @param key [String] key name or glob pattern
375
+ # @param db [Integer, String] database index or "*"
376
+ def subscribe_subkeyspaceevent(event = "*", key = "*", db: 0, &handler)
377
+ subscribe(Channels.subkeyspaceevent(event, key, db: db), handler: handler)
378
+ end
379
+
380
+ # @!endgroup
381
+
382
+ # Default handler for notifications whose pattern has no dedicated handler.
383
+ # @yieldparam notification [Notification]
384
+ def on_notification(&block)
385
+ @lock.synchronize { @default_handler = block }
386
+ nil
387
+ end
388
+
389
+ # Replaces the error handler. Receives parse errors, handler exceptions and
390
+ # connection errors; must not raise.
391
+ # @yieldparam error [StandardError]
392
+ def on_error(&block)
393
+ # Synchronized for the happens-before edge non-GVL runtimes need.
394
+ @lock.synchronize { @error_handler = block }
395
+ nil
396
+ end
397
+
398
+ # Called (on the listener thread) after the manager re-established a lost
399
+ # connection and re-subscribed. Notifications emitted during the gap are lost;
400
+ # use this to reconcile (e.g. invalidate caches).
401
+ def on_reconnect(&block)
402
+ @lock.synchronize { @reconnect_handler = block }
403
+ nil
404
+ end
405
+
406
+ # @return [Array<String>] the patterns currently confirmed by the server
407
+ def patterns
408
+ @lock.synchronize { @confirmed.keys }
409
+ end
410
+
411
+ # The registered intent, regardless of server confirmation — the set a
412
+ # reconnect replay will re-subscribe. Differs from {#patterns} while the
413
+ # connection is down or acknowledgments are in flight; reconciliation must
414
+ # compare against this.
415
+ #
416
+ # @return [Array<String>] the registered patterns
417
+ def registered_patterns
418
+ @lock.synchronize { @handlers.keys }
419
+ end
420
+
421
+ # @return [Boolean] whether the listener is running with at least one confirmed pattern
422
+ def subscribed?
423
+ @lock.synchronize { listening? && !@confirmed.empty? }
424
+ end
425
+
426
+ # @return [Boolean]
427
+ def closed?
428
+ # Synchronized for the happens-before edge non-GVL runtimes need
429
+ # (NodeListener#healthy? relies on it).
430
+ @lock.synchronize { @closed }
431
+ end
432
+
433
+ # Stop listening, terminate the background thread and close the connection.
434
+ # Idempotent; safe to call from within a handler.
435
+ #
436
+ # @param timeout [Numeric] seconds to wait for the listener thread before
437
+ # force-closing the connection under it
438
+ # @return [void]
439
+ def close(timeout: DEFAULT_CLOSE_TIMEOUT)
440
+ thread = @lock.synchronize do
441
+ return if @closed
442
+
443
+ @closing = true
444
+ # Wake a listener parked in a reconnect backoff — closing the socket
445
+ # can't interrupt a plain sleep.
446
+ @cond.broadcast
447
+ @thread
448
+ end
449
+
450
+ begin
451
+ @redis.punsubscribe if thread&.alive? && @redis.subscribed?
452
+ rescue StandardError
453
+ nil # the listener may be mid-teardown; the force-close below covers it
454
+ end
455
+
456
+ begin
457
+ # Thread#join re-raises whatever killed the listener; the ensure keeps
458
+ # teardown complete either way (no leaked connection, no half-closed
459
+ # manager).
460
+ if thread && !thread.equal?(Thread.current) && !thread.join(timeout)
461
+ force_close_redis
462
+ thread.join(timeout)
463
+ end
464
+ ensure
465
+ force_close_redis
466
+ # Under @lock (paired with closed?'s read) so the state is visible the
467
+ # moment close returns.
468
+ @lock.synchronize { @closed = true }
469
+ end
470
+ nil
471
+ end
472
+ alias stop close
473
+
474
+ private
475
+
476
+ def listening?
477
+ @thread&.alive? || false
478
+ end
479
+
480
+ def listener_thread?
481
+ Thread.current.equal?(@thread)
482
+ end
483
+
484
+ # Waits up to +delay+ seconds between reconnect attempts, waking immediately
485
+ # on close or when a subscribe requests an immediate reconnect. Returns false
486
+ # when the manager is closing.
487
+ def interruptible_backoff(delay)
488
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + delay
489
+ @lock.synchronize do
490
+ until @closing
491
+ if @reconnect_now
492
+ @reconnect_now = false
493
+ return true
494
+ end
495
+
496
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
497
+ return true if remaining <= 0
498
+
499
+ @cond.wait(remaining)
500
+ end
501
+ end
502
+ false
503
+ end
504
+
505
+ # Revives a listener that exited while registrations remain (an unsubscribe
506
+ # race: its clean-exit recheck saw only removal targets, but a timeout or a
507
+ # concurrent replacement left a live registration behind). Runs as a
508
+ # reconnect — the survivors' server-side subscriptions died with the
509
+ # session. Called under @lock.
510
+ def restart_dead_listener
511
+ return if listening? || @handlers.empty? || @closing || @closed
512
+
513
+ @resume_reconnecting = true
514
+ start_listener(@handlers.keys)
515
+ end
516
+
517
+ # Called under @lock (all call sites hold it).
518
+ def start_listener(patterns)
519
+ @listener_error = nil
520
+ # A restart after a lossy death runs as a reconnect so on_reconnect
521
+ # announces the gap's end; a first start has no gap and stays silent.
522
+ reconnecting = @resume_reconnecting
523
+ @resume_reconnecting = false
524
+ @thread = Thread.new { run_listener(patterns, reconnecting: reconnecting) }
525
+ @thread.name = "redis-keyspace-notifications"
526
+ end
527
+
528
+ def run_listener(patterns, reconnecting: false)
529
+ attempts = 0
530
+
531
+ loop do
532
+ @session_confirmed = false
533
+ begin
534
+ listen(patterns, reconnecting)
535
+ # Clean termination (everything unsubscribed, or close) — except a
536
+ # registration that replaced or arrived alongside the final
537
+ # unsubscribe: the loop exited on the punsubscribe ack without ever
538
+ # reading the replacement's ack, so it must be replayed on a fresh
539
+ # session. Compare REGISTRATIONS, not patterns: the unsubscriber's
540
+ # own target legitimately lingers until this very ack wakes it and
541
+ # must be skipped, while a replacement under the same pattern is a
542
+ # different registration.
543
+ patterns = @lock.synchronize do
544
+ @handlers.reject { |pattern, entry| entry.equal?(@removing[pattern]) }.keys
545
+ end
546
+ break if patterns.empty? || @closing
547
+
548
+ reconnecting = false
549
+ attempts = 0
550
+ next
551
+ rescue StandardError => error
552
+ break if @closing
553
+
554
+ # The subscription loop bypasses Redis::Client's rescue wrappers.
555
+ error = translate_error(error)
556
+ # Attribution and error publication share ONE lock hold: observed
557
+ # separately, a waiter could see its registration evicted without
558
+ # ever seeing the rejection that names it.
559
+ @lock.synchronize do
560
+ if error.is_a?(CommandError)
561
+ # The server rejected a command on this session. Replies arrive
562
+ # in command order, so the rejected command is the OLDEST
563
+ # outstanding one — attribute it to whichever candidate is
564
+ # oldest on the @issue_seq axis and evict only that; later
565
+ # batches may be valid and get replayed.
566
+ @rejected_wait = nil
567
+ # min_by seq, NOT map order: a re-marked pattern keeps its
568
+ # original Hash position.
569
+ oldest_marker = @unvalidated.values.min_by { |record| record[:seq] }
570
+ # A wait is a candidate only through tokens of its OWN commands
571
+ # still outstanding on THIS session (direct write or re-issue) —
572
+ # a wait whose command died with an older session must not
573
+ # absorb this session's rejection. The opening command's credit
574
+ # token (queue head while the opening ack is outstanding) is the
575
+ # OPENING's command, not the wait's, and is excluded.
576
+ live_wait_tokens = @pending_acks.flat_map do |pattern, tokens|
577
+ @opening_pending[pattern] ? tokens.drop(1) : tokens
578
+ end
579
+ oldest_wait = live_wait_tokens.select { |token| token && @inflight_waits.key?(token) }.min
580
+ oldest_probe = @probe_inflight.min_by { |_, record| record[:seq] }
581
+ candidates = {}
582
+ candidates[:marker] = oldest_marker[:seq] if oldest_marker
583
+ candidates[:wait] = oldest_wait if oldest_wait
584
+ candidates[:probe] = oldest_probe[1][:seq] if oldest_probe
585
+ # The unacknowledged opening replay competes too — it is the
586
+ # oldest command on this session and must win over commands
587
+ # issued after it.
588
+ candidates[:opening] = @opening_seq unless @opening_pending.empty?
589
+ case candidates.min_by { |_, seq| seq }&.first
590
+ when :marker
591
+ oldest_batch = oldest_marker[:batch]
592
+ @unvalidated.each do |pattern, record|
593
+ next unless record[:batch].equal?(oldest_batch)
594
+
595
+ # Dead for good even if already replaced: a concurrent
596
+ # rollback must not restore the rejected entry as "the
597
+ # previous registration".
598
+ record[:entry].failed = true
599
+ @handlers.delete(pattern) if @handlers[pattern].equal?(record[:entry])
600
+ end
601
+ @unvalidated.delete_if { |_, record| record[:batch].equal?(oldest_batch) }
602
+ when :probe
603
+ # A probe carries exactly one pattern: the culprit. Evict it;
604
+ # the un-probed remainder may hide more poison, so probe again.
605
+ pattern, record = oldest_probe
606
+ record[:entry].failed = true
607
+ @handlers.delete(pattern) if @handlers[pattern].equal?(record[:entry])
608
+ # A wait awaiting the evicted pattern must raise the rejection
609
+ # instead of resolving the eviction's delete as a replacement.
610
+ @rejected_wait = @inflight_waits.find { |_, awaiting| awaiting.include?(pattern) }&.first
611
+ @probe_replay = true
612
+ when :opening
613
+ # The batch replay names no culprit: probe next session.
614
+ @probe_replay = true
615
+ when :wait
616
+ # Name the blocking subscribe: its waiter (and only its)
617
+ # observes the error and rolls back.
618
+ @rejected_wait = oldest_wait
619
+ else
620
+ # Nothing outstanding is attributable — the replay itself was
621
+ # rejected (e.g. permissions revoked on a long-registered
622
+ # pattern). Probe next session so the rejection lands on
623
+ # exactly the poisoned pattern.
624
+ @probe_replay = true
625
+ end
626
+ end
627
+ @listener_error = error
628
+ # Waits compare against this epoch to tell a FRESH error from a
629
+ # stale one left over from before they started.
630
+ @listener_error_epoch += 1
631
+ # The session's server-side subscriptions died with it: clear
632
+ # confirmations BEFORE the error reaches user code, and everything
633
+ # else whose commands died with the session (a stale @unvalidated
634
+ # marker would misdirect the next session's rejection attribution).
635
+ @confirmed.clear
636
+ @pending_acks.clear
637
+ @probe_inflight.clear
638
+ @opening_pending.clear
639
+ @unvalidated.clear
640
+ # A session that died before its first ack must lift the opening
641
+ # gate, or every future write would be refused forever.
642
+ @establishing = false
643
+ @cond.broadcast
644
+ end
645
+ report_error(error)
646
+ ensure
647
+ # Clean exits pass through here too; after an error exit this is a no-op.
648
+ @lock.synchronize do
649
+ @confirmed.clear
650
+ @pending_acks.clear
651
+ @probe_inflight.clear
652
+ @opening_pending.clear
653
+ @unvalidated.clear
654
+ @establishing = false
655
+ @cond.broadcast
656
+ end
657
+ end
658
+
659
+ attempts = 0 if @session_confirmed # the previous session was healthy; fresh budget
660
+ delay = @reconnect_attempts[attempts]
661
+ attempts += 1
662
+ if delay.nil? # the reconnect schedule is exhausted
663
+ # Registrations outlive this death; a later subscribe restarts the
664
+ # listener, and that restart must run as a reconnect.
665
+ @lock.synchronize { @resume_reconnecting = true unless @handlers.empty? }
666
+ break
667
+ end
668
+ break unless interruptible_backoff(delay) # close woke us mid-delay
669
+
670
+ patterns = @lock.synchronize { @handlers.keys }
671
+ break if patterns.empty? || @closing
672
+
673
+ reconnecting = true
674
+ end
675
+ ensure
676
+ @lock.synchronize do
677
+ @confirmed.clear
678
+ @pending_acks.clear
679
+ @probe_inflight.clear
680
+ @opening_pending.clear
681
+ @unvalidated.clear
682
+ @establishing = false
683
+ @cond.broadcast
684
+ end
685
+ end
686
+
687
+ def listen(patterns, reconnected)
688
+ # on_reconnect is documented to fire AFTER the manager re-subscribed:
689
+ # once every replayed pattern is confirmed or no longer registered.
690
+ announce_pending = reconnected ? patterns.dup : nil
691
+ # A probing session replays one pattern per command (opening carries the
692
+ # first; the rest go out on the first ack), so a rejection attributes to
693
+ # exactly one pattern.
694
+ probing = @lock.synchronize do
695
+ probe = @probe_replay
696
+ @probe_replay = false
697
+ probe
698
+ end
699
+ opening = probing ? patterns.first(1) : patterns
700
+ probe_queue = probing ? patterns.drop(1) : nil
701
+ # Track the opening acks before the connect (a failed connect discards
702
+ # them via the session-end clear). @session_seq is bumped alongside so a
703
+ # wait that sampled the old session can retry against this one.
704
+ @lock.synchronize do
705
+ @session_seq += 1
706
+ # No command may reach the new session's socket before the opening
707
+ # command: a write slipping into the establishment gap would invert
708
+ # @pending_acks against reply order. write_to_session refuses writes
709
+ # until the first ack proves the opening went out.
710
+ @establishing = true
711
+ probing ? mark_probes(opening) : track_opening_acks(opening)
712
+ end
713
+ @redis.psubscribe(*opening) do |on|
714
+ on.psubscribe do |pattern, _count|
715
+ key = pattern.b
716
+ registered = false
717
+ pending = false
718
+ announce = false
719
+ @lock.synchronize do
720
+ @session_confirmed = true
721
+ # This ack proves the opening command is on the wire: writes may flow.
722
+ @establishing = false
723
+ # The listener demonstrably recovered: a stale error must not be
724
+ # re-raised by a later wait.
725
+ @listener_error = nil
726
+ # Consume the OLDEST expected ack — replies arrive in command
727
+ # order, so the shifted token names exactly the command this ack
728
+ # answers. The batch is credited on EVERY ack, gated or not: a
729
+ # fully-acked batch can no longer be the rejected command and must
730
+ # retire from attribution immediately.
731
+ tokens = @pending_acks[key]
732
+ token = tokens&.shift
733
+ @pending_acks.delete(key) if tokens && tokens.empty?
734
+ # A pattern's FIRST ack this session is the opening's.
735
+ @opening_pending.delete(key)
736
+ if token && (awaiting = @inflight_waits[token])
737
+ awaiting.delete(key)
738
+ @inflight_waits.delete(token) if awaiting.empty?
739
+ end
740
+ # In-handler markers and probes retire the same way — on THEIR OWN
741
+ # command's ack.
742
+ marker = @unvalidated[key]
743
+ @unvalidated.delete(key) if marker && token && marker[:seq] == token
744
+ probe = @probe_inflight[key]
745
+ @probe_inflight.delete(key) if probe && token && probe[:seq] == token
746
+ # A non-final ack answers an EARLIER command than the pattern's
747
+ # newest one and resolves nothing pattern-wide: confirming here
748
+ # would report success for a command the server may still reject.
749
+ pending = tokens ? !tokens.empty? : false
750
+ next if pending
751
+
752
+ # Any final ack retires the validation marker (a non-matching one
753
+ # is stale and would otherwise leak).
754
+ @unvalidated.delete(key)
755
+ if @handlers.key?(key)
756
+ # Fresh generation per final ack: only an ack consumed AFTER a
757
+ # caller's install satisfies its wait.
758
+ @confirmed[key] = (@confirm_seq += 1)
759
+ @cond.broadcast
760
+ registered = true
761
+ end
762
+ if announce_pending
763
+ announce_pending.reject! { |p| @confirmed.key?(p) || !@handlers.key?(p) }
764
+ if announce_pending.empty?
765
+ announce_pending = nil
766
+ announce = true
767
+ end
768
+ end
769
+ end
770
+ # A probing session's deferred patterns go out on the first ack.
771
+ if probe_queue
772
+ deferred = probe_queue
773
+ probe_queue = nil
774
+ issue_probes(deferred)
775
+ end
776
+ # The server confirmed a pattern nobody is registered for anymore
777
+ # (an unsubscribe or rollback raced this ack): revert it. A pending
778
+ # ack resolved nothing above and is not reverted either.
779
+ revert_subscription(pattern) unless registered || pending
780
+ fire_reconnect if announce
781
+ end
782
+ on.punsubscribe do |pattern, _count|
783
+ key = pattern.b
784
+ @lock.synchronize do
785
+ @confirmed.delete(key)
786
+ @cond.broadcast
787
+ entry = @handlers[key]
788
+ # Wanted again unless this ack answers the unsubscribe targeting
789
+ # the live registration, or close's blanket punsubscribe
790
+ # (re-establishing would fight the teardown).
791
+ still_wanted = !@closing && !entry.nil? && !entry.equal?(@removing[key])
792
+ # A registered pattern lost its subscription to an unsubscribe
793
+ # aimed at an older, since-replaced registration: re-establish it.
794
+ # Inside the lock hold so the write and its ack tracking stay in
795
+ # wire order against concurrent subscribes.
796
+ psubscribe_quietly([pattern]) if still_wanted
797
+ end
798
+ end
799
+ on.pmessage do |pattern, channel, payload|
800
+ dispatch(pattern, channel, payload)
801
+ end
802
+ end
803
+ end
804
+
805
+ def dispatch(pattern, channel, payload)
806
+ notification = Parser.parse(channel, payload, pattern: pattern)
807
+ if notification.nil?
808
+ error = ParseError.new(
809
+ "received a non-notification message on #{channel.inspect}",
810
+ channel: channel, payload: payload
811
+ )
812
+ report_error(error)
813
+ return
814
+ end
815
+
816
+ key = pattern.b
817
+ handler = @lock.synchronize do
818
+ # Messages for a pattern being unsubscribed are dropped rather than
819
+ # leaked to the default handler.
820
+ entry = @handlers[key]
821
+ entry ? (entry.handler || @default_handler) : nil
822
+ end
823
+ handler&.call(notification)
824
+ rescue StandardError => error
825
+ report_error(error)
826
+ end
827
+
828
+ # Waits for every pattern that is still THIS call's to confirm. A pattern
829
+ # removed or replaced by a concurrent operation stops being waited for — it
830
+ # resolves to that operation's outcome (timing out on it would tear down
831
+ # the batch's innocent siblings).
832
+ def wait_for_confirmation(patterns, installed, issue_seq, stale_confirmations, entry_epoch)
833
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + SUBSCRIBE_ACK_TIMEOUT
834
+ restarted = false
835
+ reissued_session = nil
836
+ @lock.synchronize do
837
+ # entry_epoch was sampled in the same hold that issued the command, so
838
+ # a rejection processed before this wait entered still reads as fresh.
839
+ loop do
840
+ # A fresh CommandError is raised promptly — but ONLY when attribution
841
+ # named THIS wait's command; a rejection pinned elsewhere must not
842
+ # tear down an innocent waiter (its command is replayed and confirms).
843
+ # The epoch is consumed either way so the same error is not
844
+ # re-examined every wake. Checked BEFORE the resolution break: a
845
+ # probe eviction deletes this call's registration in the same stroke
846
+ # as it names this wait, and the raise must win over "resolved by
847
+ # replacement".
848
+ if (rejection = @listener_error).is_a?(CommandError) && @listener_error_epoch > entry_epoch
849
+ raise rejection if @rejected_wait == issue_seq
850
+
851
+ entry_epoch = @listener_error_epoch
852
+ end
853
+
854
+ break if patterns.all? { |pattern| confirmed_or_replaced?(pattern, installed, stale_confirmations) }
855
+
856
+ unless listening?
857
+ raise @listener_error if @listener_error && @listener_error_epoch > entry_epoch
858
+ if @closing || @closed || restarted || @handlers.empty?
859
+ raise SubscriptionError, "keyspace notifications listener died before confirming"
860
+ end
861
+
862
+ # The previous listener ended naturally (e.g. a racing
863
+ # unsubscribe-all); restart it once.
864
+ start_listener(@handlers.keys)
865
+ restarted = true
866
+ end
867
+
868
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
869
+ raise SubscriptionError, "timed out waiting for subscription confirmation" if remaining <= 0
870
+
871
+ @cond.wait([remaining, 0.05].min)
872
+ # At most ONE re-issue per listener session: it exists to cover the
873
+ # session-establishment window, and duplicates stack pending acks the
874
+ # final-ack gate must drain. Marked only when the write went out.
875
+ if @session_seq != reissued_session &&
876
+ reissue_unconfirmed(patterns, installed, issue_seq, stale_confirmations)
877
+ reissued_session = @session_seq
878
+ end
879
+ end
880
+ end
881
+ nil
882
+ end
883
+
884
+ # Re-issues psubscribe for patterns the server hasn't acked yet (covers a
885
+ # pattern registered while the session wasn't established). Re-subscribing
886
+ # is harmless — the server re-acks. Carries the batch's seq: when the
887
+ # original write died with its session, the re-issue IS the batch's command.
888
+ def reissue_unconfirmed(patterns, installed, issue_seq, stale_confirmations)
889
+ unconfirmed = patterns.select do |pattern|
890
+ @handlers[pattern].equal?(installed[pattern]) && !fresh_confirmation?(pattern, stale_confirmations)
891
+ end
892
+ psubscribe_quietly(unconfirmed, issue_seq)
893
+ end
894
+
895
+ # A pattern stops being waited for once its confirmation is newer than the
896
+ # caller's install-time snapshot, or once its registration was replaced or
897
+ # removed (it then resolves to that operation's outcome). Called under @lock.
898
+ def confirmed_or_replaced?(pattern, installed, stale_confirmations)
899
+ fresh_confirmation?(pattern, stale_confirmations) || !@handlers[pattern].equal?(installed[pattern])
900
+ end
901
+
902
+ # Whether the pattern's confirmation was minted AFTER the caller's install:
903
+ # a kept-but-stale entry reports the pattern as subscribed to the world but
904
+ # must not satisfy the replacing call's wait. Called under @lock.
905
+ def fresh_confirmation?(pattern, stale_confirmations)
906
+ confirmation = @confirmed[pattern]
907
+ !confirmation.nil? && confirmation != stale_confirmations[pattern]
908
+ end
909
+
910
+ # Blocks until the server no longer acknowledges any still-owned target as
911
+ # subscribed. A dead or restarting session counts as removed (its
912
+ # confirmations are cleared); a target replaced by a concurrent subscribe
913
+ # stops being waited for — it is that subscribe's to confirm.
914
+ def wait_for_removal(patterns, owned)
915
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + SUBSCRIBE_ACK_TIMEOUT
916
+ reissued_session = nil
917
+ @lock.synchronize do
918
+ until patterns.none? { |pattern| @confirmed.key?(pattern) && @handlers[pattern].equal?(owned[pattern]) }
919
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
920
+ if remaining <= 0
921
+ # Clear the marks ATOMICALLY with the timeout decision: after the
922
+ # raise the registration stays (caller retries), and a late ack
923
+ # must see no stale mark.
924
+ patterns.each { |pattern| @removing.delete(pattern) if @removing[pattern].equal?(owned[pattern]) }
925
+ # The listener may have exited believing this removal completes
926
+ # it; the surviving registrations would sit deaf — revive it.
927
+ restart_dead_listener
928
+ raise SubscriptionError, "timed out waiting for unsubscription confirmation"
929
+ end
930
+
931
+ @cond.wait([remaining, 0.05].min)
932
+ # At most ONE re-issue per session (it exists to catch a reconnect
933
+ # replay re-subscribing a removal target); every-wake duplicates
934
+ # flap `subscribed?`, which the cluster wrapper prunes nodes on.
935
+ pending = patterns.select do |pattern|
936
+ @confirmed.key?(pattern) && @handlers[pattern].equal?(owned[pattern])
937
+ end
938
+ if @session_seq != reissued_session && punsubscribe_quietly(pending)
939
+ reissued_session = @session_seq
940
+ end
941
+ end
942
+ end
943
+ nil
944
+ end
945
+
946
+ # Mirror of reissue_unconfirmed for the removal path. Returns whether the
947
+ # command actually went out on the session.
948
+ def punsubscribe_quietly(patterns)
949
+ return false if patterns.empty? || !@redis.subscribed?
950
+
951
+ write_to_session(:punsubscribe, patterns)
952
+ end
953
+
954
+ def psubscribe_quietly(patterns, batch_seq = nil)
955
+ return false if patterns.empty? || !@redis.subscribed?
956
+
957
+ written = write_to_session(:psubscribe, patterns)
958
+ track_pending_acks(patterns, batch_seq) if written
959
+ written
960
+ end
961
+
962
+ # Records one expected ack per pattern for a psubscribe that went out,
963
+ # remembering WHICH command it was (the blocking batch's seq, nil for writes
964
+ # with no waiter). EVERY psubscribe write must pass through here, or its ack
965
+ # would be credited to another command's token.
966
+ def track_pending_acks(patterns, batch_seq = nil)
967
+ @lock.synchronize do
968
+ patterns.each { |pattern| (@pending_acks[pattern.b] ||= []) << batch_seq }
969
+ end
970
+ end
971
+
972
+ # Tracks the opening batch's acks, crediting each pattern to the oldest
973
+ # blocking wait awaiting it — the opening IS the session's (re-)issue of
974
+ # that wait's command. Left uncredited, a completed wait would linger in
975
+ # rejection attribution until its caller thread is scheduled.
976
+ def track_opening_acks(patterns)
977
+ @lock.synchronize do
978
+ # Sequenced before any later write on this session can take a seq, so
979
+ # "opening still unacknowledged" outranks everything issued after it.
980
+ @opening_seq = (@issue_seq += 1)
981
+ patterns.each do |pattern|
982
+ @opening_pending[pattern] = true
983
+ token = @inflight_waits.select { |_, awaiting| awaiting.include?(pattern) }.keys.min
984
+ track_pending_acks([pattern], token)
985
+ end
986
+ end
987
+ end
988
+
989
+ # Probe bookkeeping for the probing session's opening command.
990
+ def mark_probes(patterns)
991
+ @lock.synchronize do
992
+ patterns.each do |pattern|
993
+ entry = @handlers[pattern]
994
+ next unless entry
995
+
996
+ seq = (@issue_seq += 1)
997
+ @probe_inflight[pattern] = { entry: entry, seq: seq }
998
+ track_pending_acks([pattern], seq)
999
+ end
1000
+ end
1001
+ end
1002
+
1003
+ # Issues one single-pattern psubscribe per remaining pattern of a probing
1004
+ # session (listener thread, after the opening ack). Sequenced and written
1005
+ # under one lock hold apiece so probe age reflects wire order; a dead
1006
+ # session stops the loop with no dangling probe entries.
1007
+ def issue_probes(patterns)
1008
+ patterns.each do |pattern|
1009
+ alive = @lock.synchronize do
1010
+ entry = @handlers[pattern]
1011
+ next true unless entry
1012
+
1013
+ seq = (@issue_seq += 1)
1014
+ if write_to_session(:psubscribe, [pattern])
1015
+ @probe_inflight[pattern] = { entry: entry, seq: seq }
1016
+ track_pending_acks([pattern], seq)
1017
+ true
1018
+ else
1019
+ false
1020
+ end
1021
+ end
1022
+ break unless alive
1023
+ end
1024
+ end
1025
+
1026
+ # Block-less writes race the session's teardown; SubscriptionError, a
1027
+ # connection error, or redis-client's discarded-connection NoMethodError all
1028
+ # mean "session gone" — the replay and ack-time invariants own convergence.
1029
+ # Returns false then, true when the write went out.
1030
+ def write_to_session(verb, patterns)
1031
+ # The opening command must be FIRST on the wire: until its ack arrives,
1032
+ # every other write is refused exactly like a down session.
1033
+ return false if @establishing
1034
+
1035
+ @redis.public_send(verb, *patterns)
1036
+ true
1037
+ rescue SubscriptionError, BaseConnectionError, RedisClient::ConnectionError
1038
+ false
1039
+ rescue NoMethodError => error
1040
+ # NoMethodError#receiver raises ArgumentError when the error carries no
1041
+ # receiver information — treat that as "not the torn-down shape".
1042
+ receiver_nil = begin
1043
+ error.receiver.nil?
1044
+ rescue ArgumentError
1045
+ false
1046
+ end
1047
+ raise unless error.name == :write && receiver_nil
1048
+
1049
+ false
1050
+ end
1051
+
1052
+ # A raised subscribe must leave no trace: restore each pattern's previous
1053
+ # registration exactly, and revert any newly-added pattern the server did
1054
+ # confirm meanwhile. Later acks are reverted by the listener's registry check.
1055
+ def rollback_registration(previous, installed)
1056
+ revert = []
1057
+ @lock.synchronize do
1058
+ previous.each do |pattern, entry|
1059
+ # Dead wherever it ends up: a concurrent failed subscribe's rollback
1060
+ # must not restore it as "the previous registration".
1061
+ installed[pattern].failed = true
1062
+ # Re-registered by a concurrent subscribe meanwhile: theirs, not ours.
1063
+ next unless @handlers[pattern].equal?(installed[pattern])
1064
+
1065
+ if entry && !entry[:entry].failed
1066
+ @handlers[pattern] = entry[:entry]
1067
+ else
1068
+ @handlers.delete(pattern)
1069
+ revert << pattern if @confirmed.key?(pattern)
1070
+ end
1071
+ end
1072
+ end
1073
+ return if revert.empty?
1074
+
1075
+ write_to_session(:punsubscribe, revert)
1076
+ end
1077
+
1078
+ # Best-effort punsubscribe of a single server-confirmed but unregistered
1079
+ # pattern (called from the listener thread's ack handling).
1080
+ def revert_subscription(pattern)
1081
+ write_to_session(:punsubscribe, [pattern])
1082
+ end
1083
+
1084
+ def fire_reconnect
1085
+ # Read under @lock, called outside it — user code must never run while
1086
+ # the manager lock is held.
1087
+ handler = @lock.synchronize { @reconnect_handler }
1088
+ handler&.call
1089
+ rescue StandardError => error
1090
+ report_error(error)
1091
+ end
1092
+
1093
+ def report_error(error)
1094
+ handler = @lock.synchronize { @error_handler }
1095
+ if handler
1096
+ handler.call(error)
1097
+ else
1098
+ warn("Redis keyspace notifications error: #{error.class}: #{error.message}")
1099
+ end
1100
+ rescue StandardError
1101
+ nil # a broken error handler must never kill the listener
1102
+ end
1103
+
1104
+ def force_close_redis
1105
+ @redis.close
1106
+ rescue StandardError
1107
+ nil
1108
+ end
1109
+
1110
+ def translate_error(error)
1111
+ return error unless error.is_a?(RedisClient::Error)
1112
+
1113
+ begin
1114
+ Client.translate_error!(error)
1115
+ rescue StandardError => translated
1116
+ translated
1117
+ end
1118
+ end
1119
+ end
1120
+ end
1121
+ end