Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/keyspace_notifications.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

813 statements  

1""" 

2Redis Keyspace Notifications support for redis-py. 

3 

4This module provides utilities for subscribing to and parsing Redis keyspace 

5notifications. Keyspace notifications allow clients to receive events when 

6keys are modified in Redis. 

7 

8Note: Keyspace notifications must be enabled on the Redis server via the 

9``notify-keyspace-events`` configuration option. This is a server-side 

10configuration that should be done by your infrastructure/operations team. 

11See the Redis documentation for details: 

12https://redis.io/docs/latest/develop/pubsub/keyspace-notifications/ 

13 

14Standalone Redis Example: 

15 >>> from redis import Redis 

16 >>> from redis.keyspace_notifications import ( 

17 ... KeyspaceNotifications, 

18 ... KeyspaceChannel, 

19 ... EventType, 

20 ... ) 

21 >>> 

22 >>> r = Redis() 

23 >>> # Server must have notify-keyspace-events configured (e.g., "KEA") 

24 >>> ksn = KeyspaceNotifications(r) 

25 >>> 

26 >>> # Subscribe using Channel class (patterns auto-detected) 

27 >>> channel = KeyspaceChannel("user:*") 

28 >>> ksn.subscribe(channel) 

29 >>> 

30 >>> # Or use convenience methods for specific event types 

31 >>> ksn.subscribe_keyevent(EventType.SET) 

32 >>> 

33 >>> for notification in ksn.listen(): 

34 ... print(f"Key: {notification.key}, Event: {notification.event_type}") 

35 

36Redis Cluster Example: 

37 >>> from redis.cluster import RedisCluster 

38 >>> from redis.keyspace_notifications import ( 

39 ... ClusterKeyspaceNotifications, 

40 ... KeyspaceChannel, 

41 ... EventType, 

42 ... ) 

43 >>> 

44 >>> rc = RedisCluster(host="localhost", port=7000) 

45 >>> # Server must have notify-keyspace-events configured (e.g., "KEA") 

46 >>> ksn = ClusterKeyspaceNotifications(rc) 

47 >>> 

48 >>> # Subscribe using Channel class (patterns auto-detected) 

49 >>> channel = KeyspaceChannel("user:*") 

50 >>> ksn.subscribe(channel) 

51 >>> 

52 >>> # Or use convenience methods for specific event types 

53 >>> ksn.subscribe_keyevent(EventType.SET) 

54 >>> 

55 >>> for notification in ksn.listen(): 

56 ... print(f"Key: {notification.key}, Event: {notification.event_type}") 

57""" 

58 

59from __future__ import annotations 

60 

61import logging 

62import re 

63import threading 

64import time 

65from abc import ABC, abstractmethod 

66from collections.abc import Callable 

67from dataclasses import dataclass 

68from enum import Enum 

69from typing import TYPE_CHECKING, Any, ClassVar, Union 

70 

71from redis.client import Redis 

72from redis.cluster import RedisCluster 

73from redis.exceptions import ( 

74 ConnectionError, 

75 RedisError, 

76 TimeoutError, 

77) 

78from redis.utils import safe_str 

79 

80logger = logging.getLogger(__name__) 

81 

82if TYPE_CHECKING: 

83 from typing import TypeAlias 

84 

85# Type alias for channel arguments - can be a string, bytes, or Channel object 

86# This is defined here and the actual types are added after class definitions 

87ChannelT: TypeAlias = Union[ 

88 str, 

89 bytes, 

90 "KeyspaceChannel", 

91 "KeyeventChannel", 

92 "SubkeyspaceChannel", 

93 "SubkeyeventChannel", 

94 "SubkeyspaceitemChannel", 

95 "SubkeyspaceeventChannel", 

96] 

97 

98 

99# Type alias for sync handlers 

100SyncHandlerT = Callable[["KeyNotification"], None] 

101 

102 

103# ============================================================================= 

104# Event Type Constants 

105# ============================================================================= 

106# These are common Redis keyspace notification event types provided for 

107# convenience. You can use any string as an event type - these constants 

108# are not exhaustive and Redis may add new events in future versions. 

109 

110 

111class EventType: 

112 """ 

113 Common Redis keyspace notification event type constants. 

114 

115 These are provided for convenience and IDE autocomplete. You can use 

116 any string as an event type - new Redis events will work without 

117 needing library updates. 

118 """ 

119 

120 # String commands 

121 SET = "set" 

122 SETEX = "setex" 

123 SETNX = "setnx" 

124 SETRANGE = "setrange" 

125 INCR = "incr" 

126 INCRBY = "incrby" 

127 INCRBYFLOAT = "incrbyfloat" 

128 DECR = "decr" 

129 DECRBY = "decrby" 

130 APPEND = "append" 

131 

132 # Generic commands 

133 DEL = "del" 

134 UNLINK = "unlink" 

135 RENAME = "rename" 

136 RENAME_FROM = "rename_from" 

137 RENAME_TO = "rename_to" 

138 COPY_TO = "copy_to" 

139 MOVE = "move" 

140 RESTORE = "restore" 

141 

142 # Expiration events 

143 EXPIRE = "expire" 

144 EXPIREAT = "expireat" 

145 PEXPIRE = "pexpire" 

146 PEXPIREAT = "pexpireat" 

147 EXPIRED = "expired" 

148 PERSIST = "persist" 

149 

150 # Eviction events 

151 EVICTED = "evicted" 

152 

153 # List commands 

154 LPUSH = "lpush" 

155 RPUSH = "rpush" 

156 LPOP = "lpop" 

157 RPOP = "rpop" 

158 LINSERT = "linsert" 

159 LSET = "lset" 

160 LTRIM = "ltrim" 

161 LMOVE = "lmove" 

162 BLPOP = "blpop" 

163 BRPOP = "brpop" 

164 BLMOVE = "blmove" 

165 

166 # Set commands 

167 SADD = "sadd" 

168 SREM = "srem" 

169 SPOP = "spop" 

170 SMOVE = "smove" 

171 SINTERSTORE = "sinterstore" 

172 SUNIONSTORE = "sunionstore" 

173 SDIFFSTORE = "sdiffstore" 

174 

175 # Sorted set commands 

176 ZADD = "zadd" 

177 ZINCRBY = "zincrby" 

178 ZREM = "zrem" 

179 ZREMRANGEBYRANK = "zremrangebyrank" 

180 ZREMRANGEBYSCORE = "zremrangebyscore" 

181 ZREMRANGEBYLEX = "zremrangebylex" 

182 ZPOPMIN = "zpopmin" 

183 ZPOPMAX = "zpopmax" 

184 BZPOPMIN = "bzpopmin" 

185 BZPOPMAX = "bzpopmax" 

186 ZINTERSTORE = "zinterstore" 

187 ZUNIONSTORE = "zunionstore" 

188 ZDIFFSTORE = "zdiffstore" 

189 ZRANGESTORE = "zrangestore" 

190 

191 # Hash commands 

192 HSET = "hset" 

193 HSETNX = "hsetnx" 

194 HDEL = "hdel" 

195 HINCRBY = "hincrby" 

196 HINCRBYFLOAT = "hincrbyfloat" 

197 

198 # Stream commands 

199 XADD = "xadd" 

200 XTRIM = "xtrim" 

201 XDEL = "xdel" 

202 XGROUP_CREATE = "xgroup-create" 

203 XGROUP_CREATECONSUMER = "xgroup-createconsumer" 

204 XGROUP_DELCONSUMER = "xgroup-delconsumer" 

205 XGROUP_DESTROY = "xgroup-destroy" 

206 XGROUP_SETID = "xgroup-setid" 

207 XSETID = "xsetid" 

208 XCLAIM = "xclaim" 

209 XAUTOCLAIM = "xautoclaim" 

210 XREADGROUP = "xreadgroup" 

211 

212 # Other 

213 NEW = "new" # Key created (when tracking new keys) 

214 SORTSTORE = "sortstore" 

215 GETEX = "getex" 

216 GETDEL = "getdel" 

217 SETIFGT = "setifgt" 

218 SETIFLT = "setiflt" 

219 SETIFEQ = "setifeq" 

220 SETIFNE = "setifne" 

221 

222 

223def _parse_length_prefixed_subkeys(s: bytes | str) -> list[str]: 

224 """Parse a length-prefixed subkey list. 

225 

226 The wire format is ``<len>:<subkey>[,<len>:<subkey>...]``. 

227 

228 The server writes ``<len>`` as the subkey size in **bytes** (it uses 

229 ``sdslen`` when formatting the notification), so parsing must happen in 

230 the byte domain; splitting the decoded string by character count 

231 corrupts every multi-byte subkey and desynchronizes the whole list. 

232 

233 Returns: 

234 A list of subkey strings. 

235 """ 

236 raw = s.encode("utf-8") if isinstance(s, str) else bytes(s) 

237 subkeys: list[str] = [] 

238 pos = 0 

239 while pos < len(raw): 

240 colon = raw.find(b":", pos) 

241 if colon < 0 or not raw[pos:colon].isdigit(): 

242 raise ValueError("Invalid subkey length prefix") 

243 length = int(raw[pos:colon]) 

244 start = colon + 1 

245 end = start + length 

246 if end > len(raw): 

247 raise ValueError("Truncated subkey") 

248 subkeys.append(raw[start:end].decode("utf-8", "replace")) 

249 pos = end 

250 if pos < len(raw): 

251 if raw[pos] != ord(",") or pos + 1 == len(raw): 

252 raise ValueError("Invalid subkey separator") 

253 pos += 1 

254 return subkeys 

255 

256 

257@dataclass 

258class KeyNotification: 

259 """ 

260 Represents a parsed Redis keyspace, keyevent, or subkey notification. 

261 

262 This class provides convenient access to the notification details 

263 like key, event type, database number, and affected subkeys. 

264 

265 Attributes: 

266 key: The Redis key that was affected (for keyspace notifications) 

267 or the key name from the message data (for keyevent notifications) 

268 event_type: The type of operation that occurred (e.g., "set", "del"). 

269 This is a plain string, so new Redis events work automatically. 

270 Compare against EventType constants or any string. 

271 database: The database number where the event occurred 

272 channel: The original channel name 

273 is_keyspace: True if this is a keyspace notification, False for keyevent 

274 data: The raw data payload from the notification message. 

275 subkeys: List of affected subkeys (fields) for subkey notifications. 

276 Empty list for regular keyspace/keyevent notifications. 

277 """ 

278 

279 # Regex patterns for parsing keyspace/keyevent channels 

280 # Pattern: __keyspace@<db>__:<key> or __keyevent@<db>__:<event> 

281 # A key may contain any byte, newlines included, so the patterns that capture 

282 # one need re.DOTALL: without it "." stops at a newline and "$" matches before 

283 # a trailing one, dropping or truncating the key. 

284 _KEYSPACE_PATTERN: ClassVar[re.Pattern] = re.compile( 

285 r"^__keyspace@(\d+|\*)__:(.*)$", re.DOTALL 

286 ) 

287 _KEYEVENT_PATTERN: ClassVar[re.Pattern] = re.compile( 

288 r"^__keyevent@(\d+|\*)__:(.+)$" 

289 ) 

290 _SUBKEYSPACE_PATTERN: ClassVar[re.Pattern] = re.compile( 

291 r"^__subkeyspace@(\d+|\*)__:(.*)$", re.DOTALL 

292 ) 

293 _SUBKEYEVENT_PATTERN: ClassVar[re.Pattern] = re.compile( 

294 r"^__subkeyevent@(\d+|\*)__:(.+)$" 

295 ) 

296 _SUBKEYSPACEITEM_PATTERN: ClassVar[re.Pattern] = re.compile( 

297 r"^__subkeyspaceitem@(\d+|\*)__:(.+)$", re.DOTALL 

298 ) 

299 _SUBKEYSPACEEVENT_PATTERN: ClassVar[re.Pattern] = re.compile( 

300 r"^__subkeyspaceevent@(\d+|\*)__:(.+)$", re.DOTALL 

301 ) 

302 

303 key: str 

304 event_type: str 

305 database: int 

306 channel: str 

307 is_keyspace: bool 

308 data: str 

309 subkeys: list[str] = None # type: ignore[assignment] 

310 

311 def __post_init__(self): 

312 if self.subkeys is None: 

313 self.subkeys = [] 

314 

315 @classmethod 

316 def from_message( 

317 cls, 

318 message: dict[str, Any] | None, 

319 key_prefix: str | bytes | None = None, 

320 ) -> KeyNotification | None: 

321 """ 

322 Parse a pub/sub message into a KeyNotification. 

323 

324 Args: 

325 message: A pub/sub message dict with 'channel', 'data', and 'type' keys 

326 key_prefix: Optional prefix to filter and strip from keys. 

327 If provided, only notifications for keys starting with 

328 this prefix will be returned, and the prefix will be 

329 stripped from the key. 

330 

331 Returns: 

332 A KeyNotification if the message is a valid keyspace/keyevent 

333 notification, None otherwise. 

334 

335 Example: 

336 >>> message = { 

337 ... 'type': 'pmessage', 

338 ... 'pattern': '__keyspace@0__:user:*', 

339 ... 'channel': '__keyspace@0__:user:123', 

340 ... 'data': 'set' 

341 ... } 

342 >>> notification = KeyNotification.from_message(message) 

343 >>> notification.key 

344 'user:123' 

345 >>> notification.event_type 

346 'set' 

347 """ 

348 if message is None: 

349 return None 

350 

351 msg_type = message.get("type") 

352 if msg_type not in ("message", "pmessage"): 

353 return None 

354 

355 channel = message.get("channel") 

356 data = message.get("data") 

357 

358 if channel is None or data is None: 

359 return None 

360 

361 return cls.try_parse(channel, data, key_prefix) 

362 

363 @classmethod 

364 def try_parse( 

365 cls, 

366 channel: str | bytes, 

367 data: str | bytes, 

368 key_prefix: str | bytes | None = None, 

369 ) -> KeyNotification | None: 

370 """ 

371 Try to parse a channel and data into a KeyNotification. 

372 

373 This is a lower-level method that takes the channel and data directly, 

374 useful when working with callback-based subscription handlers. 

375 

376 Args: 

377 channel: The channel name (e.g., "__keyspace@0__:mykey") 

378 data: The message data (event type for keyspace, key for keyevent) 

379 key_prefix: Optional prefix to filter and strip from keys 

380 

381 Returns: 

382 A KeyNotification if valid, None otherwise. 

383 """ 

384 raw_data = bytes(data) if isinstance(data, (bytes, bytearray)) else None 

385 channel = safe_str(channel) 

386 data = safe_str(data) 

387 

388 try: 

389 return cls._parse(channel, data, key_prefix, raw_data=raw_data) 

390 except ValueError: 

391 return None 

392 

393 @classmethod 

394 def _parse( 

395 cls, 

396 channel: str, 

397 data: str, 

398 key_prefix: str | bytes | None = None, 

399 raw_data: bytes | None = None, 

400 ) -> KeyNotification | None: 

401 """Internal parsing logic.""" 

402 # Normalize key_prefix 

403 key_prefix = safe_str(key_prefix) if key_prefix else None 

404 # Byte-domain view of the payload: the server prefixes every element 

405 # with its size in bytes (sdslen), so length-prefixed fields must be 

406 # split before decoding. When the caller only has the decoded string 

407 # (decode_responses=True) the exact bytes are recovered by re-encoding. 

408 raw = raw_data if raw_data is not None else data.encode("utf-8") 

409 

410 # Try keyspace pattern first: __keyspace@<db>__:<key> 

411 match = cls._KEYSPACE_PATTERN.match(channel) 

412 if match: 

413 db_str, key = match.groups() 

414 database = int(db_str) if db_str != "*" else -1 

415 event_type = data # For keyspace, the data is the event type 

416 

417 # Apply key prefix filter 

418 if key_prefix: 

419 if not key.startswith(key_prefix): 

420 return None 

421 key = key[len(key_prefix) :] 

422 

423 return cls( 

424 key=key, 

425 event_type=event_type, 

426 database=database, 

427 channel=channel, 

428 is_keyspace=True, 

429 data=data, 

430 ) 

431 

432 # Try keyevent pattern: __keyevent@<db>__:<event> 

433 match = cls._KEYEVENT_PATTERN.match(channel) 

434 if match: 

435 db_str, event_type = match.groups() 

436 database = int(db_str) if db_str != "*" else -1 

437 key = data # For keyevent, the data is the key 

438 

439 # Apply key prefix filter 

440 if key_prefix: 

441 if not key.startswith(key_prefix): 

442 return None 

443 key = key[len(key_prefix) :] 

444 

445 return cls( 

446 key=key, 

447 event_type=event_type, 

448 database=database, 

449 channel=channel, 

450 is_keyspace=False, 

451 data=data, 

452 ) 

453 

454 # Try subkeyspace: channel=__subkeyspace@<db>__:<key> 

455 # data=<event>|<subkey_len>:<subkey>[,<subkey_len>:<subkey>...] 

456 match = cls._SUBKEYSPACE_PATTERN.match(channel) 

457 if match: 

458 db_str, key = match.groups() 

459 database = int(db_str) if db_str != "*" else -1 

460 pipe_idx = raw.index(b"|") 

461 event_type = raw[:pipe_idx].decode("utf-8", "replace") 

462 subkeys = _parse_length_prefixed_subkeys(raw[pipe_idx + 1 :]) 

463 

464 if key_prefix: 

465 if not key.startswith(key_prefix): 

466 return None 

467 key = key[len(key_prefix) :] 

468 

469 return cls( 

470 key=key, 

471 event_type=event_type, 

472 database=database, 

473 channel=channel, 

474 is_keyspace=True, 

475 data=data, 

476 subkeys=subkeys, 

477 ) 

478 

479 # Try subkeyevent: channel=__subkeyevent@<db>__:<event> 

480 # data=<key_len>:<key>|<subkey_len>:<subkey>[,...] 

481 match = cls._SUBKEYEVENT_PATTERN.match(channel) 

482 if match: 

483 db_str, event_type = match.groups() 

484 database = int(db_str) if db_str != "*" else -1 

485 # Parse key by length prefix 

486 colon_idx = raw.index(b":") 

487 key_len = int(raw[:colon_idx]) 

488 key_start = colon_idx + 1 

489 separator = key_start + key_len 

490 if key_len < 0 or separator >= len(raw) or raw[separator] != ord("|"): 

491 raise ValueError("Invalid subkeyevent key separator") 

492 key = raw[key_start : key_start + key_len].decode("utf-8", "replace") 

493 # After key, expect '|' then subkeys 

494 subkeys_start = separator + 1 

495 subkeys = _parse_length_prefixed_subkeys(raw[subkeys_start:]) 

496 

497 if key_prefix: 

498 if not key.startswith(key_prefix): 

499 return None 

500 key = key[len(key_prefix) :] 

501 

502 return cls( 

503 key=key, 

504 event_type=event_type, 

505 database=database, 

506 channel=channel, 

507 is_keyspace=False, 

508 data=data, 

509 subkeys=subkeys, 

510 ) 

511 

512 # Try subkeyspaceitem: channel=__subkeyspaceitem@<db>__:<key>\n<subkey> 

513 # data=<event> 

514 match = cls._SUBKEYSPACEITEM_PATTERN.match(channel) 

515 if match: 

516 db_str, key_and_subkey = match.groups() 

517 database = int(db_str) if db_str != "*" else -1 

518 newline_idx = key_and_subkey.index("\n") 

519 key = key_and_subkey[:newline_idx] 

520 subkey = key_and_subkey[newline_idx + 1 :] 

521 event_type = data 

522 

523 if key_prefix: 

524 if not key.startswith(key_prefix): 

525 return None 

526 key = key[len(key_prefix) :] 

527 

528 return cls( 

529 key=key, 

530 event_type=event_type, 

531 database=database, 

532 channel=channel, 

533 is_keyspace=True, 

534 data=data, 

535 subkeys=[subkey], 

536 ) 

537 

538 # Try subkeyspaceevent: channel=__subkeyspaceevent@<db>__:<event>|<key> 

539 # data=<subkey_len>:<subkey>[,...] 

540 match = cls._SUBKEYSPACEEVENT_PATTERN.match(channel) 

541 if match: 

542 db_str, event_and_key = match.groups() 

543 database = int(db_str) if db_str != "*" else -1 

544 pipe_idx = event_and_key.index("|") 

545 event_type = event_and_key[:pipe_idx] 

546 key = event_and_key[pipe_idx + 1 :] 

547 subkeys = _parse_length_prefixed_subkeys(raw) 

548 

549 if key_prefix: 

550 if not key.startswith(key_prefix): 

551 return None 

552 key = key[len(key_prefix) :] 

553 

554 return cls( 

555 key=key, 

556 event_type=event_type, 

557 database=database, 

558 channel=channel, 

559 is_keyspace=False, 

560 data=data, 

561 subkeys=subkeys, 

562 ) 

563 

564 return None 

565 

566 def key_starts_with(self, prefix: str | bytes) -> bool: 

567 """Check if the key starts with the given prefix.""" 

568 prefix = safe_str(prefix) 

569 return self.key.startswith(prefix) 

570 

571 

572# ============================================================================= 

573# Channel Classes 

574# ============================================================================= 

575 

576 

577class KeyspaceChannel: 

578 """ 

579 Represents a keyspace notification channel for subscribing to events on keys. 

580 

581 Keyspace notifications publish the event type (e.g., "set", "del") as the message 

582 when a key matching the pattern is modified. 

583 

584 This class can be used directly with subscribe()/psubscribe() as it implements 

585 __str__ to return the channel string. 

586 

587 Attributes: 

588 key_or_pattern: The key or pattern to monitor (use '*' for wildcards) 

589 db: The database number (defaults to 0, the only database in Redis Cluster) 

590 is_pattern: Whether this channel contains wildcards 

591 

592 Examples: 

593 >>> channel = KeyspaceChannel("user:123", db=0) 

594 >>> str(channel) 

595 '__keyspace@0__:user:123' 

596 

597 >>> # Pattern subscription (wildcards are auto-detected) 

598 >>> channel = KeyspaceChannel("user:*", db=0) 

599 >>> str(channel) 

600 '__keyspace@0__:user:*' 

601 

602 >>> # Use with KeyspaceNotifications 

603 >>> notifications = KeyspaceNotifications(redis_client) 

604 >>> notifications.subscribe(channel) 

605 """ 

606 

607 PREFIX: ClassVar[str] = "__keyspace@" 

608 

609 def __init__(self, key_or_pattern: str, db: int = 0): 

610 """ 

611 Create a keyspace notification channel. 

612 

613 Args: 

614 key_or_pattern: The key or pattern to monitor. Use '*' for wildcards. 

615 db: The database number. Defaults to 0 (the only database in Redis Cluster). 

616 """ 

617 self.key_or_pattern = key_or_pattern 

618 self.db = db 

619 self._channel_str = self._build_channel_string() 

620 

621 def _build_channel_string(self) -> str: 

622 return f"{self.PREFIX}{self.db}__:{self.key_or_pattern}" 

623 

624 @property 

625 def is_pattern(self) -> bool: 

626 """Check if this channel contains wildcards and should use psubscribe.""" 

627 return _is_pattern(self.key_or_pattern) 

628 

629 def __str__(self) -> str: 

630 return self._channel_str 

631 

632 def __repr__(self) -> str: 

633 return f"KeyspaceChannel({self.key_or_pattern!r}, db={self.db})" 

634 

635 def __eq__(self, other: object) -> bool: 

636 if isinstance(other, KeyspaceChannel): 

637 return self._channel_str == other._channel_str 

638 if isinstance(other, str): 

639 return self._channel_str == other 

640 return NotImplemented 

641 

642 def __hash__(self) -> int: 

643 return hash(self._channel_str) 

644 

645 

646class KeyeventChannel: 

647 """ 

648 Represents a keyevent notification channel for subscribing to event types. 

649 

650 Keyevent notifications publish the key name as the message when the specified 

651 event type occurs on any key. 

652 

653 This class can be used directly with subscribe()/psubscribe() as it implements 

654 __str__ to return the channel string. 

655 

656 Attributes: 

657 event: The event type to monitor 

658 db: The database number (defaults to 0, the only database in Redis Cluster) 

659 is_pattern: Whether this channel contains wildcards 

660 

661 Examples: 

662 >>> channel = KeyeventChannel(EventType.SET, db=0) 

663 >>> str(channel) 

664 '__keyevent@0__:set' 

665 

666 >>> channel = KeyeventChannel.all_events(db=0) 

667 >>> str(channel) 

668 '__keyevent@0__:*' 

669 

670 >>> # Use with KeyspaceNotifications 

671 >>> notifications = KeyspaceNotifications(redis_client) 

672 >>> notifications.subscribe(channel) 

673 """ 

674 

675 PREFIX: ClassVar[str] = "__keyevent@" 

676 

677 def __init__(self, event: str, db: int = 0): 

678 """ 

679 Create a keyevent notification channel. 

680 

681 Args: 

682 event: The event type to monitor (e.g., EventType.SET or "set") 

683 db: The database number. Defaults to 0 (the only database in Redis Cluster). 

684 """ 

685 self.event = event 

686 self.db = db 

687 self._channel_str = self._build_channel_string() 

688 

689 def _build_channel_string(self) -> str: 

690 return f"{self.PREFIX}{self.db}__:{self.event}" 

691 

692 @property 

693 def is_pattern(self) -> bool: 

694 """Check if this channel contains wildcards and should use psubscribe.""" 

695 return _is_pattern(self.event) 

696 

697 @classmethod 

698 def all_events(cls, db: int = 0) -> "KeyeventChannel": 

699 """ 

700 Create a keyevent pattern for subscribing to all event types. 

701 

702 This is equivalent to KeyeventChannel("*"). 

703 

704 Args: 

705 db: The database number. Defaults to 0 (the only database in Redis Cluster). 

706 

707 Returns: 

708 A KeyeventChannel configured to receive all events. 

709 

710 Examples: 

711 >>> channel = KeyeventChannel.all_events() 

712 >>> str(channel) 

713 '__keyevent@0__:*' 

714 """ 

715 return cls("*", db=db) 

716 

717 def __str__(self) -> str: 

718 return self._channel_str 

719 

720 def __repr__(self) -> str: 

721 return f"KeyeventChannel({self.event!r}, db={self.db})" 

722 

723 def __eq__(self, other: object) -> bool: 

724 if isinstance(other, KeyeventChannel): 

725 return self._channel_str == other._channel_str 

726 if isinstance(other, str): 

727 return self._channel_str == other 

728 return NotImplemented 

729 

730 def __hash__(self) -> int: 

731 return hash(self._channel_str) 

732 

733 

734class SubkeyspaceChannel: 

735 """ 

736 Represents a subkeyspace notification channel for subscribing to 

737 subkey-level events on keys (e.g., hash field changes). 

738 

739 The channel format is ``__subkeyspace@<db>__:<key>``. 

740 The message payload is ``<event>|<subkey_len>:<subkey>[,...]``. 

741 

742 Examples: 

743 >>> channel = SubkeyspaceChannel("myhash", db=0) 

744 >>> str(channel) 

745 '__subkeyspace@0__:myhash' 

746 """ 

747 

748 PREFIX: ClassVar[str] = "__subkeyspace@" 

749 

750 def __init__(self, key_or_pattern: str, db: int = 0): 

751 self.key_or_pattern = key_or_pattern 

752 self.db = db 

753 self._channel_str = self._build_channel_string() 

754 

755 def _build_channel_string(self) -> str: 

756 return f"{self.PREFIX}{self.db}__:{self.key_or_pattern}" 

757 

758 @property 

759 def is_pattern(self) -> bool: 

760 return _is_pattern(self.key_or_pattern) 

761 

762 def __str__(self) -> str: 

763 return self._channel_str 

764 

765 def __repr__(self) -> str: 

766 return f"SubkeyspaceChannel({self.key_or_pattern!r}, db={self.db})" 

767 

768 def __eq__(self, other: object) -> bool: 

769 if isinstance(other, SubkeyspaceChannel): 

770 return self._channel_str == other._channel_str 

771 if isinstance(other, str): 

772 return self._channel_str == other 

773 return NotImplemented 

774 

775 def __hash__(self) -> int: 

776 return hash(self._channel_str) 

777 

778 

779class SubkeyeventChannel: 

780 """ 

781 Represents a subkeyevent notification channel for subscribing to 

782 specific event types with subkey-level detail. 

783 

784 The channel format is ``__subkeyevent@<db>__:<event>``. 

785 The message payload is ``<key_len>:<key>|<subkey_len>:<subkey>[,...]``. 

786 

787 Examples: 

788 >>> channel = SubkeyeventChannel("hdel", db=0) 

789 >>> str(channel) 

790 '__subkeyevent@0__:hdel' 

791 """ 

792 

793 PREFIX: ClassVar[str] = "__subkeyevent@" 

794 

795 def __init__(self, event: str, db: int = 0): 

796 self.event = event 

797 self.db = db 

798 self._channel_str = self._build_channel_string() 

799 

800 def _build_channel_string(self) -> str: 

801 return f"{self.PREFIX}{self.db}__:{self.event}" 

802 

803 @property 

804 def is_pattern(self) -> bool: 

805 return _is_pattern(self.event) 

806 

807 @classmethod 

808 def all_events(cls, db: int = 0) -> SubkeyeventChannel: 

809 """Create a channel for all subkeyevent types.""" 

810 return cls("*", db=db) 

811 

812 def __str__(self) -> str: 

813 return self._channel_str 

814 

815 def __repr__(self) -> str: 

816 return f"SubkeyeventChannel({self.event!r}, db={self.db})" 

817 

818 def __eq__(self, other: object) -> bool: 

819 if isinstance(other, SubkeyeventChannel): 

820 return self._channel_str == other._channel_str 

821 if isinstance(other, str): 

822 return self._channel_str == other 

823 return NotImplemented 

824 

825 def __hash__(self) -> int: 

826 return hash(self._channel_str) 

827 

828 

829class SubkeyspaceitemChannel: 

830 """ 

831 Represents a subkeyspaceitem notification channel for subscribing to 

832 events on a specific subkey (field) of a specific key. 

833 

834 The channel format is ``__subkeyspaceitem@<db>__:<key>\\n<subkey>``. 

835 The message payload is the event type (e.g., ``"hset"``). 

836 

837 Note: 

838 The server only emits this notification when the key does not 

839 contain a newline character. 

840 

841 Examples: 

842 >>> channel = SubkeyspaceitemChannel("myhash", "myfield", db=0) 

843 >>> str(channel) 

844 '__subkeyspaceitem@0__:myhash\\nmyfield' 

845 """ 

846 

847 PREFIX: ClassVar[str] = "__subkeyspaceitem@" 

848 

849 def __init__(self, key_or_pattern: str, subkey_or_pattern: str, db: int = 0): 

850 self.key_or_pattern = key_or_pattern 

851 self.subkey_or_pattern = subkey_or_pattern 

852 self.db = db 

853 self._channel_str = self._build_channel_string() 

854 

855 def _build_channel_string(self) -> str: 

856 return ( 

857 f"{self.PREFIX}{self.db}__:{self.key_or_pattern}\n{self.subkey_or_pattern}" 

858 ) 

859 

860 @property 

861 def is_pattern(self) -> bool: 

862 return _is_pattern(self.key_or_pattern) or _is_pattern(self.subkey_or_pattern) 

863 

864 def __str__(self) -> str: 

865 return self._channel_str 

866 

867 def __repr__(self) -> str: 

868 return ( 

869 f"SubkeyspaceitemChannel({self.key_or_pattern!r}, " 

870 f"{self.subkey_or_pattern!r}, db={self.db})" 

871 ) 

872 

873 def __eq__(self, other: object) -> bool: 

874 if isinstance(other, SubkeyspaceitemChannel): 

875 return self._channel_str == other._channel_str 

876 if isinstance(other, str): 

877 return self._channel_str == other 

878 return NotImplemented 

879 

880 def __hash__(self) -> int: 

881 return hash(self._channel_str) 

882 

883 

884class SubkeyspaceeventChannel: 

885 """ 

886 Represents a subkeyspaceevent notification channel for subscribing to 

887 a specific event on a specific key, receiving affected subkeys. 

888 

889 The channel format is ``__subkeyspaceevent@<db>__:<event>|<key>``. 

890 The message payload is a length-prefixed subkey list. 

891 

892 Examples: 

893 >>> channel = SubkeyspaceeventChannel("hset", "myhash", db=0) 

894 >>> str(channel) 

895 '__subkeyspaceevent@0__:hset|myhash' 

896 """ 

897 

898 PREFIX: ClassVar[str] = "__subkeyspaceevent@" 

899 

900 def __init__(self, event: str, key_or_pattern: str, db: int = 0): 

901 self.event = event 

902 self.key_or_pattern = key_or_pattern 

903 self.db = db 

904 self._channel_str = self._build_channel_string() 

905 

906 def _build_channel_string(self) -> str: 

907 return f"{self.PREFIX}{self.db}__:{self.event}|{self.key_or_pattern}" 

908 

909 @property 

910 def is_pattern(self) -> bool: 

911 return _is_pattern(self.event) or _is_pattern(self.key_or_pattern) 

912 

913 def __str__(self) -> str: 

914 return self._channel_str 

915 

916 def __repr__(self) -> str: 

917 return ( 

918 f"SubkeyspaceeventChannel({self.event!r}, " 

919 f"{self.key_or_pattern!r}, db={self.db})" 

920 ) 

921 

922 def __eq__(self, other: object) -> bool: 

923 if isinstance(other, SubkeyspaceeventChannel): 

924 return self._channel_str == other._channel_str 

925 if isinstance(other, str): 

926 return self._channel_str == other 

927 return NotImplemented 

928 

929 def __hash__(self) -> int: 

930 return hash(self._channel_str) 

931 

932 

933class ChannelType(Enum): 

934 """ 

935 Enum representing the type of a Redis keyspace notification channel. 

936 

937 Redis provides two types of keyspace notifications and four subkey 

938 notification types: 

939 

940 - KEYSPACE: ``__keyspace@{db}__:{key}`` — data is the event type. 

941 - KEYEVENT: ``__keyevent@{db}__:{event}`` — data is the key name. 

942 - SUBKEYSPACE: ``__subkeyspace@{db}__:{key}`` — data is event + subkeys. 

943 - SUBKEYEVENT: ``__subkeyevent@{db}__:{event}`` — data is key + subkeys. 

944 - SUBKEYSPACEITEM: ``__subkeyspaceitem@{db}__:{key}\\n{subkey}`` — data 

945 is the event type. 

946 - SUBKEYSPACEEVENT: ``__subkeyspaceevent@{db}__:{event}|{key}`` — data 

947 is a subkey list. 

948 

949 Examples: 

950 >>> get_channel_type("__keyspace@0__:mykey") 

951 ChannelType.KEYSPACE 

952 >>> get_channel_type("__subkeyspace@0__:myhash") 

953 ChannelType.SUBKEYSPACE 

954 """ 

955 

956 KEYSPACE = "keyspace" 

957 KEYEVENT = "keyevent" 

958 SUBKEYSPACE = "subkeyspace" 

959 SUBKEYEVENT = "subkeyevent" 

960 SUBKEYSPACEITEM = "subkeyspaceitem" 

961 SUBKEYSPACEEVENT = "subkeyspaceevent" 

962 

963 

964def get_channel_type(channel: str | bytes) -> ChannelType | None: 

965 """ 

966 Determine the type of a Redis keyspace notification channel. 

967 

968 Args: 

969 channel: The channel name to check (string or bytes). 

970 

971 Returns: 

972 ChannelType.KEYSPACE if it's a keyspace notification channel, 

973 ChannelType.KEYEVENT if it's a keyevent notification channel, 

974 None if it's not a keyspace notification channel. 

975 

976 Examples: 

977 >>> get_channel_type("__keyspace@0__:mykey") 

978 ChannelType.KEYSPACE 

979 >>> get_channel_type("__keyevent@0__:set") 

980 ChannelType.KEYEVENT 

981 >>> get_channel_type("regular_channel") is None 

982 True 

983 >>> get_channel_type(b"__keyspace@0__:mykey") 

984 ChannelType.KEYSPACE 

985 """ 

986 channel_str = safe_str(channel) 

987 # Check subkey prefixes first (they are longer and more specific) 

988 if channel_str.startswith(SubkeyspaceitemChannel.PREFIX): 

989 return ChannelType.SUBKEYSPACEITEM 

990 if channel_str.startswith(SubkeyspaceeventChannel.PREFIX): 

991 return ChannelType.SUBKEYSPACEEVENT 

992 if channel_str.startswith(SubkeyspaceChannel.PREFIX): 

993 return ChannelType.SUBKEYSPACE 

994 if channel_str.startswith(SubkeyeventChannel.PREFIX): 

995 return ChannelType.SUBKEYEVENT 

996 if channel_str.startswith(KeyspaceChannel.PREFIX): 

997 return ChannelType.KEYSPACE 

998 if channel_str.startswith(KeyeventChannel.PREFIX): 

999 return ChannelType.KEYEVENT 

1000 return None 

1001 

1002 

1003def _is_pattern( 

1004 channel: str | bytes | KeyspaceChannel | KeyeventChannel, 

1005) -> bool: 

1006 """ 

1007 Check if a channel string contains glob-style pattern characters. 

1008 

1009 Redis uses glob-style patterns for psubscribe: 

1010 - * matches any sequence of characters 

1011 - ? matches any single character 

1012 - [...] matches any character in the brackets 

1013 

1014 Args: 

1015 channel: The channel string to check. Can be a string, bytes, 

1016 or a KeyspaceChannel/KeyeventChannel object. 

1017 

1018 Returns: 

1019 True if the channel contains pattern characters, False otherwise. 

1020 """ 

1021 # Handle Channel objects that have _channel_str attribute 

1022 # (KeyspaceChannel, KeyeventChannel) 

1023 if hasattr(channel, "_channel_str"): 

1024 channel = channel._channel_str 

1025 channel = safe_str(channel) 

1026 # Check for unescaped glob pattern characters. 

1027 # * and ? are always pattern characters. 

1028 # [ is only a pattern character when followed by a matching unescaped ], 

1029 # forming a bracket expression like [abc] or [a-z]. A lone [ (e.g. in 

1030 # a key named "my[key") is treated as a literal by Redis. 

1031 i = 0 

1032 while i < len(channel): 

1033 char = channel[i] 

1034 if char == "\\": 

1035 # Skip escaped character 

1036 i += 2 

1037 continue 

1038 if char in ("*", "?"): 

1039 return True 

1040 if char == "[": 

1041 # Look for a matching unescaped ] 

1042 j = i + 1 

1043 while j < len(channel): 

1044 if channel[j] == "\\": 

1045 j += 2 

1046 continue 

1047 if channel[j] == "]": 

1048 return True 

1049 j += 1 

1050 # No matching ] found — literal [ 

1051 i += 1 

1052 return False 

1053 

1054 

1055# ============================================================================= 

1056# Abstract Base Class for Keyspace Notifications 

1057# ============================================================================= 

1058 

1059 

1060class KeyspaceNotificationsInterface(ABC): 

1061 """ 

1062 Interface for keyspace notification managers. 

1063 

1064 This interface provides a consistent API for both standalone (KeyspaceNotifications) 

1065 and cluster (ClusterKeyspaceNotifications) implementations, allowing the same 

1066 code patterns to work with both standalone and cluster Redis deployments. 

1067 """ 

1068 

1069 @abstractmethod 

1070 def subscribe( 

1071 self, 

1072 *channels: ChannelT, 

1073 handler: SyncHandlerT | None = None, 

1074 ): 

1075 """Subscribe to keyspace notification channels.""" 

1076 pass 

1077 

1078 @abstractmethod 

1079 def unsubscribe(self, *channels: ChannelT): 

1080 """Unsubscribe from keyspace notification channels.""" 

1081 pass 

1082 

1083 @abstractmethod 

1084 def subscribe_keyspace( 

1085 self, 

1086 key_or_pattern: str, 

1087 db: int = 0, 

1088 handler: SyncHandlerT | None = None, 

1089 ): 

1090 """Subscribe to keyspace notifications for specific keys.""" 

1091 pass 

1092 

1093 @abstractmethod 

1094 def subscribe_keyevent( 

1095 self, 

1096 event: str, 

1097 db: int = 0, 

1098 handler: SyncHandlerT | None = None, 

1099 ): 

1100 """Subscribe to keyevent notifications for specific event types.""" 

1101 pass 

1102 

1103 @abstractmethod 

1104 def subscribe_subkeyspace( 

1105 self, 

1106 key_or_pattern: str, 

1107 db: int = 0, 

1108 handler: SyncHandlerT | None = None, 

1109 ): 

1110 """Subscribe to subkeyspace notifications for specific keys.""" 

1111 pass 

1112 

1113 @abstractmethod 

1114 def subscribe_subkeyevent( 

1115 self, 

1116 event: str, 

1117 db: int = 0, 

1118 handler: SyncHandlerT | None = None, 

1119 ): 

1120 """Subscribe to subkeyevent notifications for specific event types.""" 

1121 pass 

1122 

1123 @abstractmethod 

1124 def subscribe_subkeyspaceitem( 

1125 self, 

1126 key_or_pattern: str, 

1127 subkey_or_pattern: str, 

1128 db: int = 0, 

1129 handler: SyncHandlerT | None = None, 

1130 ): 

1131 """Subscribe to subkeyspaceitem notifications for a specific subkey.""" 

1132 pass 

1133 

1134 @abstractmethod 

1135 def subscribe_subkeyspaceevent( 

1136 self, 

1137 event: str, 

1138 key_or_pattern: str, 

1139 db: int = 0, 

1140 handler: SyncHandlerT | None = None, 

1141 ): 

1142 """Subscribe to subkeyspaceevent notifications for an event on a key.""" 

1143 pass 

1144 

1145 @abstractmethod 

1146 def get_message( 

1147 self, 

1148 ignore_subscribe_messages: bool | None = None, 

1149 timeout: float = 0.0, 

1150 ) -> KeyNotification | None: 

1151 """Get the next keyspace notification if one is available.""" 

1152 pass 

1153 

1154 @abstractmethod 

1155 def listen(self): 

1156 """Listen for keyspace notifications.""" 

1157 pass 

1158 

1159 @abstractmethod 

1160 def close(self): 

1161 """Close the notification manager and clean up resources.""" 

1162 pass 

1163 

1164 @abstractmethod 

1165 def __enter__(self): 

1166 pass 

1167 

1168 @abstractmethod 

1169 def __exit__(self, _exc_type, _exc_val, _exc_tb): 

1170 pass 

1171 

1172 @property 

1173 @abstractmethod 

1174 def subscribed(self) -> bool: 

1175 """Check if there are any active subscriptions and not closed.""" 

1176 pass 

1177 

1178 @abstractmethod 

1179 def run_in_thread( 

1180 self, 

1181 poll_timeout: float = 0.0, 

1182 daemon: bool = False, 

1183 exception_handler: Callable[ 

1184 [ 

1185 BaseException, 

1186 KeyspaceNotificationsInterface, 

1187 KeyspaceWorkerThread, 

1188 ], 

1189 None, 

1190 ] 

1191 | None = None, 

1192 ) -> KeyspaceWorkerThread: 

1193 """Start a background thread that polls for notifications.""" 

1194 pass 

1195 

1196 

1197class AbstractKeyspaceNotifications(KeyspaceNotificationsInterface): 

1198 """ 

1199 Abstract base class for keyspace notification managers. 

1200 

1201 Provides shared implementation for subscribe/unsubscribe logic. 

1202 Subclasses must implement: 

1203 - _execute_subscribe: Execute the subscribe operation 

1204 - _execute_unsubscribe: Execute the unsubscribe operation 

1205 - get_message: Get the next notification 

1206 - listen: Generator for notifications 

1207 - close: Clean up resources 

1208 """ 

1209 

1210 def __init__( 

1211 self, 

1212 key_prefix: str | bytes | None = None, 

1213 ignore_subscribe_messages: bool = True, 

1214 ): 

1215 """ 

1216 Initialize the base keyspace notification manager. 

1217 

1218 Args: 

1219 key_prefix: Optional prefix to filter and strip from keys in notifications 

1220 ignore_subscribe_messages: If True, subscribe/unsubscribe confirmations 

1221 are not returned by get_message/listen 

1222 """ 

1223 self.key_prefix = key_prefix 

1224 self.ignore_subscribe_messages = ignore_subscribe_messages 

1225 self._closed = False 

1226 

1227 def subscribe( 

1228 self, 

1229 *channels: ChannelT, 

1230 handler: SyncHandlerT | None = None, 

1231 ): 

1232 """ 

1233 Subscribe to keyspace notification channels. 

1234 

1235 Automatically detects whether each channel is a pattern (contains 

1236 wildcards like *, ?, [) or an exact channel name and uses the 

1237 appropriate Redis subscribe command internally. 

1238 

1239 Args: 

1240 *channels: Channels to subscribe to. Can be strings, KeyspaceChannel, 

1241 or KeyeventChannel objects. Patterns are auto-detected. 

1242 handler: Optional callback function that receives KeyNotification 

1243 objects. If provided, notifications are passed to the handler 

1244 instead of being returned by get_message()/listen(). 

1245 """ 

1246 # Wrap the handler to convert raw messages to KeyNotification objects 

1247 wrapped_handler: Callable | None = None 

1248 if handler is not None: 

1249 # Capture key_prefix in closure for consistent filtering/stripping 

1250 key_prefix = self.key_prefix 

1251 

1252 def _wrap_handler(message): 

1253 notification = KeyNotification.from_message( 

1254 message, key_prefix=key_prefix 

1255 ) 

1256 if notification is not None: 

1257 handler(notification) 

1258 

1259 wrapped_handler = _wrap_handler 

1260 

1261 patterns = {} 

1262 exact_channels = {} 

1263 

1264 for channel in channels: 

1265 if hasattr(channel, "_channel_str"): 

1266 channel_str = str(channel) 

1267 else: 

1268 channel_str = safe_str(channel) 

1269 if _is_pattern(channel): 

1270 patterns[channel_str] = wrapped_handler 

1271 else: 

1272 exact_channels[channel_str] = wrapped_handler 

1273 

1274 # Delegate to subclass implementation first. For standalone Redis 

1275 # this raises on failure, keeping tracking state clean. For cluster 

1276 # implementations the operation is best-effort (partial failures are 

1277 # logged, not raised) so tracking state is always updated afterwards. 

1278 self._execute_subscribe(patterns, exact_channels) 

1279 self._track_subscribe(patterns, exact_channels) 

1280 

1281 @abstractmethod 

1282 def _execute_subscribe( 

1283 self, patterns: dict[str, Any], exact_channels: dict[str, Any] 

1284 ) -> None: 

1285 """ 

1286 Execute the subscribe operation. 

1287 

1288 Args: 

1289 patterns: Dict mapping pattern strings to handlers (for psubscribe) 

1290 exact_channels: Dict mapping channel strings to handlers (for subscribe) 

1291 """ 

1292 pass 

1293 

1294 def unsubscribe(self, *channels: ChannelT): 

1295 """ 

1296 Unsubscribe from keyspace notification channels. 

1297 

1298 Automatically detects whether each channel is a pattern or exact 

1299 channel and uses the appropriate Redis unsubscribe command. 

1300 

1301 Args: 

1302 *channels: Channels to unsubscribe from. 

1303 """ 

1304 patterns = [] 

1305 exact_channels = [] 

1306 

1307 for channel in channels: 

1308 if hasattr(channel, "_channel_str"): 

1309 channel_str = str(channel) 

1310 else: 

1311 channel_str = safe_str(channel) 

1312 if _is_pattern(channel): 

1313 patterns.append(channel_str) 

1314 else: 

1315 exact_channels.append(channel_str) 

1316 

1317 # Delegate to subclass implementation first. For standalone Redis 

1318 # this raises on failure, keeping tracking state intact. For cluster 

1319 # implementations the operation is best-effort (partial failures are 

1320 # logged, not raised) so tracking state is always removed afterwards 

1321 # — this is intentional: the user asked to unsubscribe, so 

1322 # refresh_subscriptions should not re-subscribe these channels. 

1323 self._execute_unsubscribe(patterns, exact_channels) 

1324 self._untrack_subscribe(patterns, exact_channels) 

1325 

1326 @abstractmethod 

1327 def _execute_unsubscribe( 

1328 self, patterns: list[str], exact_channels: list[str] 

1329 ) -> None: 

1330 """ 

1331 Execute the unsubscribe operation. 

1332 

1333 Args: 

1334 patterns: List of pattern strings to punsubscribe from 

1335 exact_channels: List of channel strings to unsubscribe from 

1336 """ 

1337 pass 

1338 

1339 def _track_subscribe( 

1340 self, patterns: dict[str, Any], exact_channels: dict[str, Any] 

1341 ) -> None: 

1342 """Track newly subscribed patterns/channels. 

1343 

1344 Override in subclasses that need to maintain their own subscription 

1345 registry (e.g. cluster implementations that must re-subscribe 

1346 new/failed-over nodes). The default is a no-op because standalone 

1347 implementations delegate tracking to the underlying PubSub object. 

1348 """ 

1349 

1350 def _untrack_subscribe( 

1351 self, patterns: list[str], exact_channels: list[str] 

1352 ) -> None: 

1353 """Remove patterns/channels from the subscription registry. 

1354 

1355 Override in subclasses that maintain their own subscription registry. 

1356 The default is a no-op. 

1357 """ 

1358 

1359 def subscribe_keyspace( 

1360 self, 

1361 key_or_pattern: str, 

1362 db: int = 0, 

1363 handler: SyncHandlerT | None = None, 

1364 ): 

1365 """ 

1366 Subscribe to keyspace notifications for specific keys. 

1367 

1368 Args: 

1369 key_or_pattern: The key or pattern to monitor. Use '*' for wildcards. 

1370 db: The database number (default 0). 

1371 handler: Optional callback for notifications. 

1372 

1373 Example: 

1374 >>> ksn.subscribe_keyspace("user:123", db=0) 

1375 >>> ksn.subscribe_keyspace("user:*", db=0) 

1376 """ 

1377 channel = KeyspaceChannel(key_or_pattern, db=db) 

1378 self.subscribe(channel, handler=handler) 

1379 

1380 def subscribe_keyevent( 

1381 self, 

1382 event: str, 

1383 db: int = 0, 

1384 handler: SyncHandlerT | None = None, 

1385 ): 

1386 """ 

1387 Subscribe to keyevent notifications for specific event types. 

1388 

1389 Args: 

1390 event: The event type to monitor (e.g., EventType.SET or "set") 

1391 db: The database number (default 0). 

1392 handler: Optional callback for notifications. 

1393 

1394 Example: 

1395 >>> ksn.subscribe_keyevent(EventType.SET) 

1396 >>> ksn.subscribe_keyevent(EventType.EXPIRED, handler=my_handler) 

1397 """ 

1398 channel = KeyeventChannel(event, db=db) 

1399 self.subscribe(channel, handler=handler) 

1400 

1401 def subscribe_subkeyspace( 

1402 self, 

1403 key_or_pattern: str, 

1404 db: int = 0, 

1405 handler: SyncHandlerT | None = None, 

1406 ): 

1407 """ 

1408 Subscribe to subkeyspace notifications for specific keys. 

1409 

1410 Receives events with affected subkeys (fields) for the given key. 

1411 

1412 Args: 

1413 key_or_pattern: The key or pattern to monitor. 

1414 db: The database number (default 0). 

1415 handler: Optional callback for notifications. 

1416 """ 

1417 channel = SubkeyspaceChannel(key_or_pattern, db=db) 

1418 self.subscribe(channel, handler=handler) 

1419 

1420 def subscribe_subkeyevent( 

1421 self, 

1422 event: str, 

1423 db: int = 0, 

1424 handler: SyncHandlerT | None = None, 

1425 ): 

1426 """ 

1427 Subscribe to subkeyevent notifications for specific event types. 

1428 

1429 Receives the affected key and subkeys when the given event occurs. 

1430 

1431 Args: 

1432 event: The event type to monitor (e.g., "hset", "hdel"). 

1433 db: The database number (default 0). 

1434 handler: Optional callback for notifications. 

1435 """ 

1436 channel = SubkeyeventChannel(event, db=db) 

1437 self.subscribe(channel, handler=handler) 

1438 

1439 def subscribe_subkeyspaceitem( 

1440 self, 

1441 key_or_pattern: str, 

1442 subkey_or_pattern: str, 

1443 db: int = 0, 

1444 handler: SyncHandlerT | None = None, 

1445 ): 

1446 """ 

1447 Subscribe to subkeyspaceitem notifications for a specific subkey. 

1448 

1449 Receives the event type when the given subkey of the given key is 

1450 modified. 

1451 

1452 Args: 

1453 key_or_pattern: The key or pattern to monitor. 

1454 subkey_or_pattern: The subkey (field) or pattern to monitor. 

1455 db: The database number (default 0). 

1456 handler: Optional callback for notifications. 

1457 """ 

1458 channel = SubkeyspaceitemChannel(key_or_pattern, subkey_or_pattern, db=db) 

1459 self.subscribe(channel, handler=handler) 

1460 

1461 def subscribe_subkeyspaceevent( 

1462 self, 

1463 event: str, 

1464 key_or_pattern: str, 

1465 db: int = 0, 

1466 handler: SyncHandlerT | None = None, 

1467 ): 

1468 """ 

1469 Subscribe to subkeyspaceevent notifications for an event on a key. 

1470 

1471 Receives the affected subkeys when the given event occurs on the 

1472 given key. 

1473 

1474 Args: 

1475 event: The event type to monitor. 

1476 key_or_pattern: The key or pattern to monitor. 

1477 db: The database number (default 0). 

1478 handler: Optional callback for notifications. 

1479 """ 

1480 channel = SubkeyspaceeventChannel(event, key_or_pattern, db=db) 

1481 self.subscribe(channel, handler=handler) 

1482 

1483 def __enter__(self): 

1484 return self 

1485 

1486 def __exit__(self, _exc_type, _exc_val, _exc_tb): 

1487 self.close() 

1488 return False 

1489 

1490 def run_in_thread( 

1491 self, 

1492 poll_timeout: float = 0.0, 

1493 daemon: bool = False, 

1494 exception_handler: Callable[ 

1495 [ 

1496 BaseException, 

1497 KeyspaceNotificationsInterface, 

1498 KeyspaceWorkerThread, 

1499 ], 

1500 None, 

1501 ] 

1502 | None = None, 

1503 ) -> KeyspaceWorkerThread: 

1504 """ 

1505 Start a background thread that polls for notifications and triggers handlers. 

1506 

1507 This method spawns a thread that continuously calls get_message() to 

1508 process incoming notifications. When a notification arrives, any 

1509 registered handler for that channel/pattern is invoked automatically. 

1510 

1511 All subscriptions must have handlers registered before calling this method. 

1512 

1513 Args: 

1514 poll_timeout: Timeout in seconds for get_message() calls. When no message 

1515 is available, the thread waits up to this long before checking 

1516 again. Default 0.0 (non-blocking). WARNING: the default 

1517 causes a CPU spin-loop. It is preferred to pass a positive 

1518 value (e.g. 0.1 or 1.0). 

1519 daemon: If True, the thread will be a daemon thread and will be 

1520 terminated when the main program exits. Default False. 

1521 exception_handler: Optional callback invoked when an exception occurs 

1522 in the worker thread. Receives (exception, notifications, 

1523 thread) as arguments. If None, exceptions are raised. 

1524 

1525 Returns: 

1526 KeyspaceWorkerThread: The started worker thread. Call stop() on it 

1527 to stop the thread and close the notifications. 

1528 

1529 Raises: 

1530 RedisError: If any subscription doesn't have a handler registered. 

1531 

1532 Example: 

1533 >>> def my_handler(notification): 

1534 ... print(f"Got: {notification.key} - {notification.event_type}") 

1535 >>> 

1536 >>> notifications.subscribe(KeyspaceChannel("user:*"), handler=my_handler) 

1537 >>> thread = notifications.run_in_thread(poll_timeout=0.1, daemon=True) 

1538 >>> # ... handlers are called automatically ... 

1539 >>> thread.stop() 

1540 """ 

1541 self._validate_all_handlers() 

1542 

1543 thread = KeyspaceWorkerThread( 

1544 self, 

1545 poll_timeout, 

1546 daemon=daemon, 

1547 exception_handler=exception_handler, 

1548 ) 

1549 thread.start() 

1550 return thread 

1551 

1552 @abstractmethod 

1553 def _validate_all_handlers(self) -> None: 

1554 """Raise :class:`~redis.RedisError` if any subscription lacks a handler. 

1555 

1556 Subclasses inspect their own subscription state to perform 

1557 the validation. 

1558 """ 

1559 pass 

1560 

1561 

1562class KeyspaceWorkerThread(threading.Thread): 

1563 """ 

1564 Background thread for processing keyspace notifications. 

1565 

1566 This thread continuously polls for notifications and invokes registered 

1567 handlers. It works with both KeyspaceNotifications (standalone) and 

1568 ClusterKeyspaceNotifications. 

1569 

1570 Example: 

1571 >>> thread = notifications.run_in_thread(poll_timeout=0.1) 

1572 >>> # ... handlers are called automatically ... 

1573 >>> thread.stop() 

1574 """ 

1575 

1576 def __init__( 

1577 self, 

1578 notifications: KeyspaceNotificationsInterface, 

1579 poll_timeout: float, 

1580 daemon: bool = False, 

1581 exception_handler: Callable[ 

1582 [ 

1583 BaseException, 

1584 KeyspaceNotificationsInterface, 

1585 KeyspaceWorkerThread, 

1586 ], 

1587 None, 

1588 ] 

1589 | None = None, 

1590 ): 

1591 super().__init__() 

1592 self.daemon = daemon 

1593 self.notifications = notifications 

1594 self.poll_timeout = poll_timeout 

1595 self.exception_handler = exception_handler 

1596 self._running = threading.Event() 

1597 

1598 def run(self) -> None: 

1599 """Main loop that polls for notifications and triggers handlers.""" 

1600 if self._running.is_set(): 

1601 return 

1602 self._running.set() 

1603 notifications = self.notifications 

1604 poll_timeout = self.poll_timeout 

1605 while self._running.is_set(): 

1606 try: 

1607 notifications.get_message( 

1608 ignore_subscribe_messages=True, timeout=poll_timeout 

1609 ) 

1610 except BaseException as e: 

1611 if self.exception_handler is None: 

1612 raise 

1613 self.exception_handler(e, notifications, self) 

1614 notifications.close() 

1615 

1616 def stop(self) -> None: 

1617 """ 

1618 Stop the worker thread. 

1619 

1620 This signals the thread to exit its run loop. The thread will close 

1621 the notifications object before terminating. 

1622 """ 

1623 self._running.clear() 

1624 

1625 

1626# ============================================================================= 

1627# Standalone Keyspace Notification Manager 

1628# ============================================================================= 

1629 

1630 

1631class KeyspaceNotifications(AbstractKeyspaceNotifications): 

1632 """ 

1633 Manages keyspace notification subscriptions for standalone Redis. 

1634 

1635 For standalone Redis, keyspace notifications work with a single PubSub 

1636 connection. This class wraps that connection and provides: 

1637 - Automatic pattern vs exact channel detection 

1638 - KeyNotification parsing with optional key_prefix filtering 

1639 - Convenience methods for keyspace and keyevent subscriptions 

1640 - Context manager and run_in_thread support 

1641 """ 

1642 

1643 def __init__( 

1644 self, 

1645 redis_client: Redis, 

1646 key_prefix: str | bytes | None = None, 

1647 ignore_subscribe_messages: bool = True, 

1648 ): 

1649 """ 

1650 Initialize the standalone keyspace notification manager. 

1651 

1652 Note: Keyspace notifications must be enabled on the Redis server via 

1653 the ``notify-keyspace-events`` configuration option. This is a server-side 

1654 configuration that should be done by your infrastructure/operations team. 

1655 

1656 Args: 

1657 redis_client: A Redis client instance 

1658 key_prefix: Optional prefix to filter and strip from keys in notifications 

1659 ignore_subscribe_messages: If True, subscribe/unsubscribe confirmations 

1660 are not returned by get_message/listen 

1661 """ 

1662 super().__init__(key_prefix, ignore_subscribe_messages) 

1663 self.redis = redis_client 

1664 

1665 # Create the PubSub instance with ignore_subscribe_messages=False 

1666 # so that the per-call argument in get_message() can control behavior 

1667 self._pubsub = redis_client.pubsub(ignore_subscribe_messages=False) 

1668 

1669 def _execute_subscribe( 

1670 self, patterns: dict[str, Any], exact_channels: dict[str, Any] 

1671 ) -> None: 

1672 """Execute subscribe on the single pubsub connection.""" 

1673 if patterns: 

1674 self._pubsub.psubscribe(**patterns) 

1675 if exact_channels: 

1676 self._pubsub.subscribe(**exact_channels) 

1677 

1678 def _execute_unsubscribe( 

1679 self, patterns: list[str], exact_channels: list[str] 

1680 ) -> None: 

1681 """Execute unsubscribe on the single pubsub connection.""" 

1682 if patterns: 

1683 self._pubsub.punsubscribe(*patterns) 

1684 if exact_channels: 

1685 self._pubsub.unsubscribe(*exact_channels) 

1686 

1687 def get_message( 

1688 self, 

1689 ignore_subscribe_messages: bool | None = None, 

1690 timeout: float = 0.0, 

1691 ) -> KeyNotification | None: 

1692 """ 

1693 Get the next keyspace notification if one is available. 

1694 

1695 Note: If a handler was registered for the channel, pubsub will call 

1696 the handler directly and this method returns None for that message. 

1697 

1698 Args: 

1699 ignore_subscribe_messages: If True, skip subscribe/unsubscribe messages. 

1700 Defaults to the value set in __init__ (True). 

1701 timeout: Time to wait for a message. 

1702 

1703 Returns: 

1704 A KeyNotification if a notification is available and no handler 

1705 was registered for the channel, None otherwise. 

1706 """ 

1707 if ignore_subscribe_messages is None: 

1708 ignore_subscribe_messages = self.ignore_subscribe_messages 

1709 

1710 if self._closed: 

1711 return None 

1712 

1713 # Pubsub's get_message will call wrapped handlers directly for channels 

1714 # with registered handlers and return None. For channels without handlers, 

1715 # it returns the raw message which we parse to KeyNotification. 

1716 message = self._pubsub.get_message( 

1717 ignore_subscribe_messages=ignore_subscribe_messages, 

1718 timeout=timeout, 

1719 ) 

1720 

1721 if message is not None: 

1722 return KeyNotification.from_message(message, key_prefix=self.key_prefix) 

1723 

1724 return None 

1725 

1726 def listen(self): 

1727 """ 

1728 Listen for keyspace notifications. 

1729 

1730 This is a generator that yields KeyNotification objects as they arrive. 

1731 It blocks until a notification is received. 

1732 

1733 Yields: 

1734 KeyNotification objects for each keyspace/keyevent notification. 

1735 

1736 Example: 

1737 >>> for notification in ksn.listen(): 

1738 ... print(f"{notification.key}: {notification.event_type}") 

1739 """ 

1740 while self.subscribed: 

1741 notification = self.get_message(timeout=1.0) 

1742 if notification is not None: 

1743 yield notification 

1744 

1745 @property 

1746 def subscribed(self) -> bool: 

1747 """Check if there are any active subscriptions and not closed.""" 

1748 return not self._closed and self._pubsub.subscribed 

1749 

1750 def _validate_all_handlers(self) -> None: 

1751 """Raise if any subscription in the underlying PubSub lacks a handler.""" 

1752 for channel, handler in self._pubsub.channels.items(): 

1753 if handler is None: 

1754 raise RedisError(f"Channel '{channel}' has no handler registered") 

1755 for pattern, handler in self._pubsub.patterns.items(): 

1756 if handler is None: 

1757 raise RedisError(f"Pattern '{pattern}' has no handler registered") 

1758 

1759 def close(self): 

1760 """Close the pubsub connection and clean up resources.""" 

1761 self._closed = True 

1762 try: 

1763 self._pubsub.close() 

1764 except Exception: 

1765 pass 

1766 

1767 

1768# ============================================================================= 

1769# Cluster-Aware Keyspace Notification Manager 

1770# ============================================================================= 

1771 

1772 

1773class ClusterKeyspaceNotifications(AbstractKeyspaceNotifications): 

1774 """ 

1775 Manages keyspace notification subscriptions across all nodes in a Redis Cluster. 

1776 

1777 In Redis Cluster, keyspace notifications are NOT broadcast between nodes. 

1778 Each node only emits notifications for keys it owns. This class automatically 

1779 subscribes to all primary nodes in the cluster and handles topology changes. 

1780 """ 

1781 

1782 def __init__( 

1783 self, 

1784 redis_cluster: RedisCluster, 

1785 key_prefix: str | bytes | None = None, 

1786 ignore_subscribe_messages: bool = True, 

1787 ): 

1788 """ 

1789 Initialize the cluster keyspace notification manager. 

1790 

1791 Note: Keyspace notifications must be enabled on all Redis cluster nodes via 

1792 the ``notify-keyspace-events`` configuration option. This is a server-side 

1793 configuration that should be done by your infrastructure/operations team. 

1794 

1795 Args: 

1796 redis_cluster: A RedisCluster instance 

1797 key_prefix: Optional prefix to filter and strip from keys in notifications 

1798 ignore_subscribe_messages: If True, subscribe/unsubscribe confirmations 

1799 are not returned by get_message/listen 

1800 """ 

1801 super().__init__(key_prefix, ignore_subscribe_messages) 

1802 self.cluster = redis_cluster 

1803 

1804 # Canonical subscription registry: pattern/channel -> wrapped handler. 

1805 # In cluster mode there are multiple PubSub objects (one per node), so 

1806 # this is the single source of truth used to (re-)subscribe new or 

1807 # failed-over nodes. 

1808 self._subscribed_patterns: dict[str, Any] = {} 

1809 self._subscribed_channels: dict[str, Any] = {} 

1810 

1811 # Track subscriptions per node 

1812 self._node_pubsubs: dict[str, Any] = {} 

1813 

1814 # Lock for topology refresh operations 

1815 self._refresh_lock = threading.Lock() 

1816 

1817 # Current pubsub index for round-robin polling 

1818 self._poll_index = 0 

1819 

1820 @property 

1821 def subscribed(self) -> bool: 

1822 """Check if there are any active subscriptions and not closed.""" 

1823 return not self._closed and bool( 

1824 self._subscribed_patterns or self._subscribed_channels 

1825 ) 

1826 

1827 def _track_subscribe( 

1828 self, patterns: dict[str, Any], exact_channels: dict[str, Any] 

1829 ) -> None: 

1830 """Track newly subscribed patterns/channels in the cluster registry.""" 

1831 if patterns: 

1832 self._subscribed_patterns.update(patterns) 

1833 if exact_channels: 

1834 self._subscribed_channels.update(exact_channels) 

1835 

1836 def _untrack_subscribe( 

1837 self, patterns: list[str], exact_channels: list[str] 

1838 ) -> None: 

1839 """Remove patterns/channels from the cluster registry.""" 

1840 for p in patterns: 

1841 self._subscribed_patterns.pop(p, None) 

1842 for c in exact_channels: 

1843 self._subscribed_channels.pop(c, None) 

1844 

1845 def _validate_all_handlers(self) -> None: 

1846 """Raise if any subscription in the cluster registry lacks a handler.""" 

1847 for channel, handler in self._subscribed_channels.items(): 

1848 if handler is None: 

1849 raise RedisError(f"Channel '{channel}' has no handler registered") 

1850 for pattern, handler in self._subscribed_patterns.items(): 

1851 if handler is None: 

1852 raise RedisError(f"Pattern '{pattern}' has no handler registered") 

1853 

1854 def _get_all_primary_nodes(self): 

1855 """Get all primary nodes in the cluster.""" 

1856 return self.cluster.get_primaries() 

1857 

1858 def _cleanup_node(self, node_name: str) -> None: 

1859 """Remove and close a node's PubSub. 

1860 

1861 Closing the ``PubSub`` disconnects its connection so it is not 

1862 left in a subscribed state inside the connection pool. 

1863 """ 

1864 pubsub = self._node_pubsubs.pop(node_name, None) 

1865 if pubsub: 

1866 try: 

1867 pubsub.close() 

1868 except Exception: 

1869 pass 

1870 

1871 def _ensure_node_pubsub(self, node) -> Any: 

1872 """Get or create a PubSub instance for a node.""" 

1873 if node.name not in self._node_pubsubs: 

1874 redis_conn = self.cluster.get_redis_connection(node) 

1875 # Always create PubSub with ignore_subscribe_messages=False 

1876 # so that the per-call argument in get_message() can control 

1877 # the behavior reliably 

1878 pubsub = redis_conn.pubsub(ignore_subscribe_messages=False) 

1879 self._node_pubsubs[node.name] = pubsub 

1880 return self._node_pubsubs[node.name] 

1881 

1882 def _execute_subscribe( 

1883 self, patterns: dict[str, Any], exact_channels: dict[str, Any] 

1884 ) -> None: 

1885 """Execute subscribe on all cluster nodes. 

1886 

1887 Patterns and exact channels are subscribed in a single pass over 

1888 nodes so that a mid-batch node failure cannot create a 

1889 partially-caught-up replacement. If a node fails during this 

1890 call it is removed from ``_node_pubsubs`` and will be fully 

1891 re-subscribed on the next ``refresh_subscriptions`` cycle. 

1892 

1893 If a newly discovered node is encountered (not yet in 

1894 ``_node_pubsubs``), it is also subscribed to all *previously* 

1895 tracked patterns/channels so it doesn't miss notifications for 

1896 subscriptions that were established before this node joined. 

1897 """ 

1898 if not patterns and not exact_channels: 

1899 return 

1900 

1901 failed_nodes: list[str] = [] 

1902 for node in self._get_all_primary_nodes(): 

1903 is_new_node = node.name not in self._node_pubsubs 

1904 pubsub = self._ensure_node_pubsub(node) 

1905 try: 

1906 # If this is a brand-new node, catch it up on existing 

1907 # subscriptions before adding the new channels. 

1908 if is_new_node: 

1909 if self._subscribed_patterns: 

1910 pubsub.psubscribe(**self._subscribed_patterns) 

1911 if self._subscribed_channels: 

1912 pubsub.subscribe(**self._subscribed_channels) 

1913 

1914 if patterns: 

1915 pubsub.psubscribe(**patterns) 

1916 if exact_channels: 

1917 pubsub.subscribe(**exact_channels) 

1918 except Exception: 

1919 # Remove the broken pubsub so refresh_subscriptions can 

1920 # re-create it later. 

1921 self._cleanup_node(node.name) 

1922 failed_nodes.append(node.name) 

1923 

1924 if failed_nodes: 

1925 logger.warning( 

1926 "Failed to subscribe on cluster nodes: %s. " 

1927 "These nodes will be retried on the next refresh cycle.", 

1928 ", ".join(failed_nodes), 

1929 ) 

1930 

1931 def _execute_unsubscribe( 

1932 self, patterns: list[str], exact_channels: list[str] 

1933 ) -> None: 

1934 """Execute unsubscribe on all cluster nodes.""" 

1935 if patterns: 

1936 self._unsubscribe_from_all_nodes(patterns, use_punsubscribe=True) 

1937 if exact_channels: 

1938 self._unsubscribe_from_all_nodes(exact_channels, use_punsubscribe=False) 

1939 

1940 def _unsubscribe_from_all_nodes(self, channels: list[str], use_punsubscribe: bool): 

1941 """Unsubscribe from patterns/channels on all nodes. 

1942 

1943 Best-effort: tries every node so that a single broken connection 

1944 does not prevent the remaining nodes from being unsubscribed. 

1945 Broken pubsubs are cleaned up; the tracking state is still removed 

1946 by the caller, so ``refresh_subscriptions`` will *not* re-subscribe 

1947 these channels on replacement nodes. 

1948 """ 

1949 failed_nodes: list[str] = [] 

1950 for node_name, pubsub in list(self._node_pubsubs.items()): 

1951 try: 

1952 if use_punsubscribe: 

1953 pubsub.punsubscribe(*channels) 

1954 else: 

1955 pubsub.unsubscribe(*channels) 

1956 except Exception: 

1957 self._cleanup_node(node_name) 

1958 failed_nodes.append(node_name) 

1959 

1960 if failed_nodes: 

1961 logger.warning( 

1962 "Failed to unsubscribe on cluster nodes: %s. " 

1963 "These nodes will be re-created on the next refresh cycle.", 

1964 ", ".join(failed_nodes), 

1965 ) 

1966 

1967 def get_message( 

1968 self, 

1969 ignore_subscribe_messages: bool | None = None, 

1970 timeout: float = 0.0, 

1971 ) -> KeyNotification | None: 

1972 """ 

1973 Get the next keyspace notification if one is available. 

1974 

1975 This method polls all node pubsubs in round-robin fashion until 

1976 a message is received or the timeout expires. 

1977 If a connection error occurs, subscriptions are automatically refreshed. 

1978 

1979 Args: 

1980 ignore_subscribe_messages: If True, skip subscribe/unsubscribe messages. 

1981 Defaults to the value set in __init__ (True). 

1982 timeout: Total time to wait for a message (distributed across all nodes) 

1983 

1984 Returns: 

1985 A KeyNotification if a notification is available, None otherwise. 

1986 """ 

1987 if self._closed: 

1988 return None 

1989 

1990 total_nodes = len(self._node_pubsubs) 

1991 if total_nodes == 0: 

1992 # Sleep for the requested timeout so callers that loop 

1993 # (run_in_thread, listen) don't spin the CPU when all node 

1994 # connections have been cleaned up. 

1995 if timeout > 0: 

1996 time.sleep(timeout) 

1997 return None 

1998 

1999 # Use instance default if not specified 

2000 if ignore_subscribe_messages is None: 

2001 ignore_subscribe_messages = self.ignore_subscribe_messages 

2002 

2003 # Handle timeout=0 as a single non-blocking poll over all pubsubs 

2004 # This matches the expected semantics of PubSub.get_message(timeout=0) 

2005 if timeout == 0.0: 

2006 return self._poll_all_nodes_once(ignore_subscribe_messages) 

2007 

2008 # Calculate per-node timeout for each poll 

2009 # Use a small timeout per node to allow round-robin polling 

2010 per_node_timeout = min(0.1, timeout / max(total_nodes, 1)) 

2011 

2012 start_time = time.monotonic() 

2013 end_time = start_time + timeout 

2014 

2015 while True: 

2016 # Check if we've exceeded the total timeout 

2017 if time.monotonic() >= end_time: 

2018 return None 

2019 

2020 pubsubs = list(self._node_pubsubs.values()) 

2021 if not pubsubs: 

2022 return None 

2023 

2024 # Round-robin polling 

2025 self._poll_index = self._poll_index % len(pubsubs) 

2026 pubsub = pubsubs[self._poll_index] 

2027 self._poll_index += 1 

2028 

2029 try: 

2030 message = pubsub.get_message( 

2031 ignore_subscribe_messages=ignore_subscribe_messages, 

2032 timeout=per_node_timeout, 

2033 ) 

2034 except (ConnectionError, TimeoutError, RedisError): 

2035 # Connection error - refresh subscriptions and continue 

2036 self._refresh_subscriptions_on_error() 

2037 continue 

2038 

2039 if message is not None: 

2040 # Note: If a handler was registered, PubSub already invoked it 

2041 # and returned None, so we only reach here for handler-less subscriptions 

2042 notification = KeyNotification.from_message( 

2043 message, key_prefix=self.key_prefix 

2044 ) 

2045 if notification is not None: 

2046 return notification 

2047 # If not a keyspace notification, continue checking other nodes 

2048 

2049 def _poll_all_nodes_once( 

2050 self, ignore_subscribe_messages: bool 

2051 ) -> KeyNotification | None: 

2052 """ 

2053 Perform a single non-blocking poll over all node pubsubs. 

2054 

2055 This is used when timeout=0 to match the expected semantics of 

2056 PubSub.get_message(timeout=0) - a non-blocking check for messages. 

2057 

2058 Returns: 

2059 A KeyNotification if one is available, None otherwise. 

2060 """ 

2061 had_error = False 

2062 for pubsub in list(self._node_pubsubs.values()): 

2063 try: 

2064 message = pubsub.get_message( 

2065 ignore_subscribe_messages=ignore_subscribe_messages, 

2066 timeout=0.0, 

2067 ) 

2068 except (ConnectionError, TimeoutError, RedisError): 

2069 # Record the error but continue polling remaining healthy 

2070 # nodes so that already-buffered notifications are not lost. 

2071 had_error = True 

2072 continue 

2073 

2074 if message is not None: 

2075 # Note: If a handler was registered, PubSub already invoked it 

2076 # and returned None, so we only reach here for handler-less subscriptions 

2077 notification = KeyNotification.from_message( 

2078 message, key_prefix=self.key_prefix 

2079 ) 

2080 if notification is not None: 

2081 # Refresh before returning if any node had an error, 

2082 # so the next poll cycle has fresh state. 

2083 if had_error: 

2084 self._refresh_subscriptions_on_error() 

2085 return notification 

2086 

2087 # Refresh after polling all nodes if any had errors 

2088 if had_error: 

2089 self._refresh_subscriptions_on_error() 

2090 return None 

2091 

2092 def listen(self): 

2093 """ 

2094 Listen for keyspace notifications from all cluster nodes. 

2095 

2096 This is a generator that yields KeyNotification objects as they arrive. 

2097 It blocks until a notification is received. 

2098 

2099 Yields: 

2100 KeyNotification objects for each keyspace/keyevent notification. 

2101 

2102 Example: 

2103 >>> for notification in ksn.listen(): 

2104 ... print(f"{notification.key}: {notification.event_type}") 

2105 """ 

2106 while self.subscribed: 

2107 notification = self.get_message(timeout=1.0) 

2108 if notification is not None: 

2109 yield notification 

2110 

2111 def _refresh_subscriptions_on_error(self): 

2112 """ 

2113 Refresh subscriptions after a connection error. 

2114 

2115 This is called automatically when a connection error occurs during 

2116 get_message(). It checks if nodes changed before refreshing. 

2117 """ 

2118 self._poll_index = 0 # Reset round-robin index 

2119 

2120 try: 

2121 self.refresh_subscriptions() 

2122 except Exception: 

2123 logger.warning( 

2124 "Failed to refresh cluster subscriptions, will retry on next error", 

2125 exc_info=True, 

2126 ) 

2127 

2128 def _is_pubsub_connected(self, pubsub) -> bool: 

2129 """Check if a pubsub connection is still alive.""" 

2130 try: 

2131 conn = pubsub.connection 

2132 if conn is None: 

2133 return False 

2134 return conn.is_connected 

2135 except Exception: 

2136 return False 

2137 

2138 def refresh_subscriptions(self): 

2139 """ 

2140 Refresh subscriptions after a topology change. 

2141 

2142 This method is called automatically when topology changes are detected 

2143 or when connection errors occur. You can also call it manually if needed. 

2144 

2145 This method: 

2146 1. Discovers any new primary nodes and subscribes them 

2147 2. Removes pubsubs for nodes that are no longer primaries 

2148 3. Re-creates broken pubsub connections for existing nodes 

2149 """ 

2150 with self._refresh_lock: 

2151 current_primaries = { 

2152 node.name: node for node in self._get_all_primary_nodes() 

2153 } 

2154 

2155 # Remove pubsubs for nodes that are no longer primaries 

2156 removed_nodes = set(self._node_pubsubs.keys()) - set( 

2157 current_primaries.keys() 

2158 ) 

2159 for node_name in removed_nodes: 

2160 self._cleanup_node(node_name) 

2161 

2162 # Detect broken connections for existing nodes and remove them 

2163 # so they get re-created below 

2164 existing_nodes = set(self._node_pubsubs.keys()) & set( 

2165 current_primaries.keys() 

2166 ) 

2167 for node_name in existing_nodes: 

2168 pubsub = self._node_pubsubs.get(node_name) 

2169 if pubsub and not self._is_pubsub_connected(pubsub): 

2170 # Connection is broken, remove it so it gets re-created 

2171 self._cleanup_node(node_name) 

2172 

2173 # Subscribe new nodes (and nodes with broken connections) to existing 

2174 # patterns/channels 

2175 new_nodes = set(current_primaries.keys()) - set(self._node_pubsubs.keys()) 

2176 failed_nodes: list[str] = [] 

2177 for node_name in new_nodes: 

2178 node = current_primaries[node_name] 

2179 pubsub = self._ensure_node_pubsub(node) 

2180 

2181 try: 

2182 if self._subscribed_patterns: 

2183 pubsub.psubscribe(**self._subscribed_patterns) 

2184 if self._subscribed_channels: 

2185 pubsub.subscribe(**self._subscribed_channels) 

2186 except Exception: 

2187 # Subscription failed - remove from dict so retry is possible 

2188 self._cleanup_node(node_name) 

2189 failed_nodes.append(node_name) 

2190 

2191 # Raise after attempting all nodes so we don't skip any 

2192 if failed_nodes: 

2193 raise ConnectionError( 

2194 f"Failed to subscribe to cluster nodes: {', '.join(failed_nodes)}" 

2195 ) 

2196 

2197 def close(self): 

2198 """Close all pubsub connections and clean up resources.""" 

2199 self._closed = True 

2200 for node_name in list(self._node_pubsubs.keys()): 

2201 self._cleanup_node(node_name) 

2202 self._subscribed_patterns.clear() 

2203 self._subscribed_channels.clear()