Class: Redis::KeyspaceNotifications::Manager

Inherits:
Object
  • Object
show all
Defined in:
lib/redis/keyspace_notifications/manager.rb

Overview

Owns a dedicated connection and a background listener thread, and dispatches parsed Notification objects to per-pattern handlers.

Every subscription is a psubscribe pattern (a pattern without glob characters matches itself literally): the listener loop stays terminable, handler routing is an exact lookup on the matched pattern, and database wildcards work. When several subscribed patterns match one message, each handler fires once.

Handlers run on the listener thread: they should be fast and must not call blocking Redis commands on the manager's own connection. Handler exceptions and parse errors are reported to the error handler and never kill the listener.

On connection loss the manager reconnects (per reconnect_attempts, an exponential 0.5s → 30s ladder by default) and re-subscribes every registered pattern. A pattern the server rejects on that replay (e.g. permissions revoked since it was subscribed) is evicted and reported instead of failing every reconnect. Notifications published while the connection was down are lost (pub/sub is fire-and-forget) — use #on_reconnect to reconcile after a gap.

Constant Summary collapse

DEFAULT_CLOSE_TIMEOUT =
2
DEFAULT_RECONNECT_ATTEMPTS =

Sleep per consecutive reconnect attempt; exhausted = give up. The budget resets after every healthy session.

[0.5, 1, 2, 4, 8, 16, 30, 30, 30, 30].freeze
SUBSCRIBE_ACK_TIMEOUT =
5

Typed subscriptions collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis:, error_handler: nil, reconnect_attempts: DEFAULT_RECONNECT_ATTEMPTS) ⇒ Manager

Returns a new instance of Manager.

Parameters:

  • redis (Redis) —

    a dedicated client the manager takes ownership of (it is closed by #close; it must not be used for anything else)

  • error_handler (#call, nil) (defaults to: nil) —

    receives every background error; defaults to warning on $stderr

  • reconnect_attempts (Integer, Array<Integer, Float>) (defaults to: DEFAULT_RECONNECT_ATTEMPTS) —

    number of attempts trying to reconnect (with no sleep in between), or a list of sleep durations between attempts — the same semantics as the reconnect_attempts option of Redis#initialize. The budget resets after every successful (re)subscription; an empty list disables reconnection entirely



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/redis/keyspace_notifications/manager.rb', line 46

def initialize(redis:, error_handler: nil, reconnect_attempts: DEFAULT_RECONNECT_ATTEMPTS)
  @redis = redis
  @error_handler = error_handler
  # Validated here so a bad value fails at the call site instead of killing
  # the listener thread (outside its rescue) after the first connection loss.
  @reconnect_attempts = case reconnect_attempts
  when Integer
    Array.new(reconnect_attempts, 0).freeze
  when Array
    # NaN/Infinity/Complex satisfy Numeric but blow up the backoff
    # arithmetic; real? first — Complex has no #>=.
    unless reconnect_attempts.all? { |delay| delay.is_a?(Numeric) && delay.real? && delay.finite? && delay >= 0 }
      raise ArgumentError, "reconnect_attempts must contain only finite, non-negative sleep durations"
    end

    reconnect_attempts.dup.freeze
  else
    raise ArgumentError,
          "reconnect_attempts must be an Integer or an Array of sleep durations, " \
          "got #{reconnect_attempts.class}"
  end
  @handlers = {} # pattern (BINARY String) => handler (Proc, nil for default)
  # pattern => confirmation GENERATION (monotonic) acked on the current
  # session. Presence answers "is it subscribed?"; a re-subscribing wait
  # compares the generation against its install-time snapshot so only an
  # ack that arrived AFTER the install satisfies it — the entry survives a
  # same-session replacement (the server-side subscription persists).
  @confirmed = {}
  @confirm_seq = 0
  # pattern => queue of unconsumed psubscribe acks in wire order; each entry
  # is the issuing blocking batch's seq (nil for writes with no waiter).
  # Acks arrive in command order, so each shifts the OLDEST entry. A
  # non-final ack resolves nothing pattern-wide but retires its own batch
  # from rejection attribution. Dies with its session.
  @pending_acks = {}
  @default_handler = nil
  @reconnect_handler = nil
  @lock = Monitor.new
  @cond = @lock.new_cond
  @thread = nil
  @listener_error = nil
  @listener_error_epoch = 0
  @reconnect_now = false
  @removing = {} # pattern => the Registration an in-flight unsubscribe targets
  # pattern => { entry:, batch:, seq: } for in-handler registrations not yet
  # server-acked; a session rejection evicts only the oldest (culprit) batch.
  # Age is an explicit seq — re-marking keeps the original Hash position, so
  # map order lies about command order. Dies with its session: a stale
  # marker would win the next session's rejection attribution over the
  # replay itself (cross-session poison is the probing replay's job).
  @unvalidated = {}
  # pattern => { entry:, seq: } for a probing session's unacked single-pattern
  # replay commands. Dies with its session; a lost probe just re-probes.
  @probe_inflight = {}
  # Unacked patterns of the session-opening batch, with @opening_seq its
  # position on the @issue_seq axis: represents the opening in rejection
  # attribution, or its rejection would be pinned on a later command. Dies
  # with its session.
  @opening_pending = {}
  @opening_seq = nil
  # True from opening-ack tracking until the first ack arrives. The
  # subscription client becomes visible to writers a beat before the opening
  # write hits the socket; a write in that gap would precede the opening on
  # the wire and invert @pending_acks against reply order, so
  # write_to_session refuses writes while set. Lifted at session end.
  @establishing = false
  # Issue seq of the blocking subscribe a session-killing rejection was
  # attributed to (nil otherwise). A waiter raises a fresh CommandError only
  # when it names ITS command — raising to every waiter sharing the session
  # rolled back valid registrations (and misled the cluster manager's probes).
  @rejected_wait = nil
  # Set when a rejection was unattributable (the batch replay itself was
  # rejected): the next session replays one pattern per command so the
  # rejection lands on exactly the poisoned pattern.
  @probe_replay = false
  # Set when the listener died with registrations still on the books: the
  # next start is a restart after a lossy gap and must run as a reconnect
  # so {#on_reconnect} announces it.
  @resume_reconnecting = false
  # Wire-orders every issued subscribe batch (assigned under @lock at write
  # time); rejection attribution spans blocking, in-handler, probe and
  # opening commands on this one axis.
  @issue_seq = 0
  # issue seq => the blocking subscribe's patterns still awaiting their own
  # acks. An entry lives until its wait exits or every one of its command's
  # acks was consumed (per-command tokens, not pattern-wide confirmation —
  # an acked batch must retire from rejection attribution immediately).
  @inflight_waits = {}
  # Bumped per session-opening command; waits re-issue an unconfirmed
  # pattern at most ONCE per session (duplicates stack pending acks the
  # final-ack gate must drain).
  @session_seq = 0
  @closing = false
  @closed = false
end

Instance Method Details

#close(timeout: DEFAULT_CLOSE_TIMEOUT) ⇒ void Also known as: stop

This method returns an undefined value.

Stop listening, terminate the background thread and close the connection. Idempotent; safe to call from within a handler.

Parameters:

  • timeout (Numeric) (defaults to: DEFAULT_CLOSE_TIMEOUT) —

    seconds to wait for the listener thread before force-closing the connection under it



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/redis/keyspace_notifications/manager.rb', line 439

def close(timeout: DEFAULT_CLOSE_TIMEOUT)
  thread = @lock.synchronize do
    return if @closed

    @closing = true
    # Wake a listener parked in a reconnect backoff — closing the socket
    # can't interrupt a plain sleep.
    @cond.broadcast
    @thread
  end

  begin
    @redis.punsubscribe if thread&.alive? && @redis.subscribed?
  rescue StandardError
    nil # the listener may be mid-teardown; the force-close below covers it
  end

  begin
    # Thread#join re-raises whatever killed the listener; the ensure keeps
    # teardown complete either way (no leaked connection, no half-closed
    # manager).
    if thread && !thread.equal?(Thread.current) && !thread.join(timeout)
      force_close_redis
      thread.join(timeout)
    end
  ensure
    force_close_redis
    # Under @lock (paired with closed?'s read) so the state is visible the
    # moment close returns.
    @lock.synchronize { @closed = true }
  end
  nil
end

#closed? ⇒ Boolean

Returns:

  • (Boolean)


427
428
429
430
431
# File 'lib/redis/keyspace_notifications/manager.rb', line 427

def closed?
  # Synchronized for the happens-before edge non-GVL runtimes need
  # (NodeListener#healthy? relies on it).
  @lock.synchronize { @closed }
end

#on_error {|error| ... } ⇒ Object

Replaces the error handler. Receives parse errors, handler exceptions and connection errors; must not raise.

Yield Parameters:

  • error (StandardError)


392
393
394
395
396
# File 'lib/redis/keyspace_notifications/manager.rb', line 392

def on_error(&block)
  # Synchronized for the happens-before edge non-GVL runtimes need.
  @lock.synchronize { @error_handler = block }
  nil
end

#on_notification {|notification| ... } ⇒ Object

Default handler for notifications whose pattern has no dedicated handler.

Yield Parameters:



384
385
386
387
# File 'lib/redis/keyspace_notifications/manager.rb', line 384

def on_notification(&block)
  @lock.synchronize { @default_handler = block }
  nil
end

#on_reconnect(&block) ⇒ Object

Called (on the listener thread) after the manager re-established a lost connection and re-subscribed. Notifications emitted during the gap are lost; use this to reconcile (e.g. invalidate caches).



401
402
403
404
# File 'lib/redis/keyspace_notifications/manager.rb', line 401

def on_reconnect(&block)
  @lock.synchronize { @reconnect_handler = block }
  nil
end

#patterns ⇒ Array<String>

Returns the patterns currently confirmed by the server.

Returns:

  • (Array<String>) —

    the patterns currently confirmed by the server



407
408
409
# File 'lib/redis/keyspace_notifications/manager.rb', line 407

def patterns
  @lock.synchronize { @confirmed.keys }
end

#registered_patterns ⇒ Array<String>

The registered intent, regardless of server confirmation — the set a reconnect replay will re-subscribe. Differs from #patterns while the connection is down or acknowledgments are in flight; reconciliation must compare against this.

Returns:

  • (Array<String>) —

    the registered patterns



417
418
419
# File 'lib/redis/keyspace_notifications/manager.rb', line 417

def registered_patterns
  @lock.synchronize { @handlers.keys }
end

#subscribe(*patterns, handler: nil, &block) ⇒ void

This method returns an undefined value.

Subscribe to notification channel patterns (build them with Channels). Re-subscribing a known pattern replaces its handler. Blocks until the server confirms every pattern, so no notification is missed after it returns. When it raises instead, no trace is left: the registration is rolled back and any pattern the server did confirm in the meantime is reverted. When called from inside a handler it cannot wait for the confirmation (only the listener thread itself reads acknowledgments) and returns immediately after issuing the command instead.

Parameters:

  • patterns (Array<String>) —

    channel names or psubscribe patterns

  • handler (#call, nil) (defaults to: nil) —

    receives each Notification; falls back to the #on_notification default handler when nil

Raises:



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/redis/keyspace_notifications/manager.rb', line 156

def subscribe(*patterns, handler: nil, &block)
  raise ArgumentError, "no patterns given" if patterns.empty?

  handler ||= block
  patterns = patterns.map { |pattern| pattern.to_s.b }
  previous = {}
  installed = {}
  stale_confirmations = {}
  issue_seq = nil
  error_epoch = nil
  @lock.synchronize do
    raise SubscriptionError, "keyspace notifications manager is closed" if @closed || @closing

    patterns.each do |pattern|
      # Snapshot the previous registration for rollback. The handler must be
      # registered before the command is issued: matching messages can
      # arrive ahead of our ack processing.
      unless previous.key?(pattern)
        previous[pattern] = @handlers.key?(pattern) ? { entry: @handlers[pattern] } : nil
      end
      @handlers[pattern] = installed[pattern] = Registration.new(handler)
      # A (re-)subscribe demands a FRESH acknowledgment: the wait accepts
      # only a generation newer than this snapshot, so a replaced
      # registration's confirmation can't report success for a command the
      # server may still reject. The entry itself is kept — the server-side
      # subscription persists across a same-session replacement.
      stale_confirmations[pattern] = @confirmed[pattern]
    end
    # Sequenced in the same hold as the write, so batch age reflects true
    # wire order.
    issue_seq = (@issue_seq += 1)
    # The error-freshness epoch is sampled in this same hold too: sampled at
    # wait entry instead, the listener could process our own rejection in
    # the gap and the waiter would read it as stale (converging via seconds
    # of replay bounces instead of raising promptly).
    error_epoch = @listener_error_epoch
    @inflight_waits[issue_seq] = patterns.uniq unless listener_thread?
    if listening?
      if write_to_session(:psubscribe, patterns)
        track_pending_acks(patterns, issue_seq)
      else
        # Session down (possibly parked in a long backoff): reconnect NOW so
        # the replay covers this pattern within the wait.
        @reconnect_now = true
        @cond.broadcast
      end
    else
      # A dead listener still has every prior registration: restart with the
      # COMPLETE registry (as a reconnect — see start_listener), or earlier
      # subscriptions would silently stop receiving.
      start_listener(@handlers.keys)
    end
  end

  # In-handler call: this is the listener thread, the only one that can read
  # acks, so waiting would stall delivery. Nobody can roll back a rejection
  # either — mark the registrations unvalidated so a session-killing
  # rejection evicts them instead of poisoning every replay.
  if listener_thread?
    @lock.synchronize do
      seq = issue_seq
      patterns.each do |pattern|
        # Mark only the still-live registration (a stale marker matches no
        # future ack). `installed` doubles as the batch token: a rejection
        # is attributable to the OLDEST outstanding batch.
        if @handlers[pattern].equal?(installed[pattern])
          @unvalidated[pattern] = { entry: installed[pattern], batch: installed, seq: seq }
        end
      end
    end
    return
  end

  begin
    wait_for_confirmation(patterns, installed, issue_seq, stale_confirmations, error_epoch)
  rescue StandardError
    rollback_registration(previous, installed)
    raise
  ensure
    # Resolved either way; attribution must stop considering this batch.
    @lock.synchronize { @inflight_waits.delete(issue_seq) }
  end
end

#subscribe_keyevent(event = "*", db: 0, &handler) ⇒ Object

Watch every key receiving events matching event.

Parameters:

  • event (String) (defaults to: "*") —

    event name (e.g. "expired") or glob pattern

  • db (Integer, String) (defaults to: 0) —

    database index or "*"



343
344
345
# File 'lib/redis/keyspace_notifications/manager.rb', line 343

def subscribe_keyevent(event = "*", db: 0, &handler)
  subscribe(Channels.keyevent(event, db: db), handler: handler)
end

#subscribe_keyspace(key = "*", db: 0, &handler) ⇒ Object

Watch every event happening to keys matching key.

Parameters:

  • key (String) (defaults to: "*") —

    key name or glob pattern

  • db (Integer, String) (defaults to: 0) —

    database index or "*"



336
337
338
# File 'lib/redis/keyspace_notifications/manager.rb', line 336

def subscribe_keyspace(key = "*", db: 0, &handler)
  subscribe(Channels.keyspace(key, db: db), handler: handler)
end

#subscribe_subkeyevent(event = "*", db: 0, &handler) ⇒ Object

Watch subkey-level events matching event (Redis 8.8+, flag T).

Parameters:

  • event (String) (defaults to: "*") —

    event name (e.g. "hdel") or glob pattern

  • db (Integer, String) (defaults to: 0) —

    database index or "*"



357
358
359
# File 'lib/redis/keyspace_notifications/manager.rb', line 357

def subscribe_subkeyevent(event = "*", db: 0, &handler)
  subscribe(Channels.subkeyevent(event, db: db), handler: handler)
end

#subscribe_subkeyspace(key = "*", db: 0, &handler) ⇒ Object

Watch subkey-level events on keys matching key (Redis 8.8+, flag S).

Parameters:

  • key (String) (defaults to: "*") —

    key name or glob pattern

  • db (Integer, String) (defaults to: 0) —

    database index or "*"



350
351
352
# File 'lib/redis/keyspace_notifications/manager.rb', line 350

def subscribe_subkeyspace(key = "*", db: 0, &handler)
  subscribe(Channels.subkeyspace(key, db: db), handler: handler)
end

#subscribe_subkeyspaceevent(event = "*", key = "*", db: 0, &handler) ⇒ Object

Watch subkeys affected by event on keys matching key (Redis 8.8+, flag V).

Parameters:

  • event (String) (defaults to: "*") —

    event name or glob pattern

  • key (String) (defaults to: "*") —

    key name or glob pattern

  • db (Integer, String) (defaults to: 0) —

    database index or "*"



376
377
378
# File 'lib/redis/keyspace_notifications/manager.rb', line 376

def subscribe_subkeyspaceevent(event = "*", key = "*", db: 0, &handler)
  subscribe(Channels.subkeyspaceevent(event, key, db: db), handler: handler)
end

#subscribe_subkeyspaceitem(key, subkey = "*", db: 0, &handler) ⇒ Object

Watch events on one exact key + subkey pair (Redis 8.8+, flag I). The key is treated literally — glob metacharacters in it are escaped, since every manager subscription is a psubscribe pattern — while the subkey keeps its documented glob behavior.

Parameters:

  • key (String) —

    key name (must not contain "\n")

  • subkey (String) (defaults to: "*") —

    subkey (e.g. hash field) or glob pattern

  • db (Integer, String) (defaults to: 0) —

    database index or "*"



368
369
370
# File 'lib/redis/keyspace_notifications/manager.rb', line 368

def subscribe_subkeyspaceitem(key, subkey = "*", db: 0, &handler)
  subscribe(Channels.subkeyspaceitem(Channels.glob_escape(key), subkey, db: db), handler: handler)
end

#subscribed? ⇒ Boolean

Returns whether the listener is running with at least one confirmed pattern.

Returns:

  • (Boolean) —

    whether the listener is running with at least one confirmed pattern



422
423
424
# File 'lib/redis/keyspace_notifications/manager.rb', line 422

def subscribed?
  @lock.synchronize { listening? && !@confirmed.empty? }
end

#unsubscribe(*patterns) ⇒ void

This method returns an undefined value.

Unsubscribe patterns; with no arguments, everything. Blocks until the server acknowledges, and only then removes the local registration — when it raises, local state still matches the server (the patterns remain subscribed) and the call can simply be retried. In-flight notifications received before the server's acknowledgment are still dispatched to their handler. When called from inside a handler (the one-shot subscription pattern) it cannot wait for the confirmation (only the listener thread itself reads acknowledgments) and commits the removal immediately after issuing the command; no further notifications reach the handler either way. Unsubscribing the last pattern stops the listener thread — a later #subscribe restarts it.

Parameters:

  • patterns (Array<String>)

Raises:



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/redis/keyspace_notifications/manager.rb', line 255

def unsubscribe(*patterns)
  patterns = patterns.map { |pattern| pattern.to_s.b }
  targets = nil
  owned = {}
  @lock.synchronize do
    targets = patterns.empty? ? @handlers.keys : patterns.select { |pattern| @handlers.key?(pattern) }
    return if targets.empty?

    # Capture the exact registrations being removed: a concurrent
    # replacement must neither be deleted nor fought. The @removing marks
    # tell the punsubscribe-ack invariant which registration each ack
    # targets, so it can re-establish a replacement our command killed.
    targets.each do |pattern|
      owned[pattern] = @handlers[pattern]
      @removing[pattern] = owned[pattern]
    end

    if listening?
      # Always the captured targets, never a blanket PUNSUBSCRIBE (which
      # would also drop patterns added after our capture). A false return
      # means the session is down — removal is already consistent.
      write_to_session(:punsubscribe, targets)
    end
  end

  begin
    if listener_thread?
      # In-handler call (one-shot pattern): can't wait for the ack — commit
      # the removal now. In-flight messages are dropped by dispatch's
      # registry check; a replay race is reverted at ack time.
      @lock.synchronize do
        targets.each do |pattern|
          # Dead for good: a failed subscribe's rollback must never
          # resurrect this registration.
          owned[pattern].failed = true
          next unless @handlers[pattern].equal?(owned[pattern])

          @handlers.delete(pattern)
          # Purge the pre-ack validation marker too, or it leaks forever.
          @unvalidated.delete(pattern) if @unvalidated[pattern]&.fetch(:entry).equal?(owned[pattern])
        end
      end
      return
    end

    wait_for_removal(targets, owned)
    @lock.synchronize do
      targets.each do |pattern|
        # Dead for good: a failed subscribe's rollback must never
        # resurrect this registration.
        owned[pattern].failed = true
        next unless @handlers[pattern].equal?(owned[pattern])

        @handlers.delete(pattern)
        # Purge the pre-ack validation marker too, or it leaks forever.
        @unvalidated.delete(pattern) if @unvalidated[pattern]&.fetch(:entry).equal?(owned[pattern])
      end
      # A reconnect replay may have re-subscribed a target meanwhile; sweep
      # anything still acknowledged that no registration owns.
      sweep = targets.select { |pattern| @confirmed.key?(pattern) && !@handlers.key?(pattern) }
      punsubscribe_quietly(sweep)
      # The listener may have exited on this removal's ack while a
      # replacement landed after its recheck — revive it for the survivors.
      restart_dead_listener
    end
  ensure
    # Late acks are then judged purely by the live registry: a
    # still-registered pattern is re-established instead of matching a
    # stale mark.
    @lock.synchronize do
      targets.each { |pattern| @removing.delete(pattern) if @removing[pattern].equal?(owned[pattern]) }
    end
  end
  nil
end