1from __future__ import annotations
2
3import asyncio
4import warnings
5from typing import (
6 TYPE_CHECKING,
7 Any,
8 AsyncIterator,
9 Awaitable,
10 Dict,
11 Iterable,
12 Iterator,
13 List,
14 Literal,
15 Mapping,
16 NoReturn,
17 Sequence,
18 overload,
19)
20
21from redis.crc import key_slot
22from redis.exceptions import RedisClusterException, RedisError
23from redis.typing import (
24 AnyKeyT,
25 AsyncClientProtocol,
26 ClusterCommandsProtocol,
27 ClusterLinksResponse,
28 ClusterNodeDetail,
29 ClusterShardsResponse,
30 EncodableT,
31 KeysT,
32 KeyT,
33 PatternT,
34 ResponseT,
35 StralgoResponse,
36 SyncClientProtocol,
37)
38from redis.utils import deprecated_function
39
40from .core import (
41 ACLCommands,
42 AsyncACLCommands,
43 AsyncBlessCommands,
44 AsyncDataAccessCommands,
45 AsyncFunctionCommands,
46 AsyncManagementCommands,
47 AsyncModuleCommands,
48 AsyncScriptCommands,
49 BlessCommands,
50 BlessFlag,
51 DataAccessCommands,
52 FunctionCommands,
53 HotkeysMetricsTypes,
54 ManagementCommands,
55 ModuleCommands,
56 PubSubCommands,
57 ScriptCommands,
58)
59from .helpers import list_or_args
60from .redismodules import AsyncRedisModuleCommands, RedisModuleCommands
61
62if TYPE_CHECKING:
63 from redis.asyncio.cluster import TargetNodesT
64 from redis.cluster import LoadBalancingStrategy
65
66# DEPRECATED - no longer consulted by the default metadata routing, and it will be removed in a future release.
67#
68# Replica safety is now decided from command metadata by the metadata resolver,
69# so this set no longer describes what commands are safe to execute on replicas.
70# It is kept as a public attribute only so an external caller reading it keeps working;
71# editing it changes nothing.
72#
73# To change replica safety, edit ``redis.commands.metadata._STATIC_COMMAND_METADATA`` or pass
74# a ``metadata_resolver`` to the client. Nothing here.
75READ_COMMANDS = frozenset(
76 [
77 # Bit Operations
78 "BITCOUNT",
79 "BITFIELD_RO",
80 "BITPOS",
81 # Scripting
82 "EVAL_RO",
83 "EVALSHA_RO",
84 "FCALL_RO",
85 # Key Operations
86 "DBSIZE",
87 "DIGEST",
88 "DUMP",
89 "EXISTS",
90 "EXPIRETIME",
91 "PEXPIRETIME",
92 "KEYS",
93 "SCAN",
94 "PTTL",
95 "RANDOMKEY",
96 "TTL",
97 "TYPE",
98 # String Operations
99 "GET",
100 "GETBIT",
101 "GETRANGE",
102 "MGET",
103 "STRLEN",
104 "LCS",
105 # Geo Operations
106 "GEODIST",
107 "GEOHASH",
108 "GEOPOS",
109 "GEOSEARCH",
110 # Hash Operations
111 "HEXISTS",
112 "HGET",
113 "HGETALL",
114 "HKEYS",
115 "HLEN",
116 "HMGET",
117 "HSTRLEN",
118 "HVALS",
119 "HRANDFIELD",
120 "HEXPIRETIME",
121 "HPEXPIRETIME",
122 "HTTL",
123 "HPTTL",
124 "HSCAN",
125 # List Operations
126 "LINDEX",
127 "LPOS",
128 "LLEN",
129 "LRANGE",
130 # Set Operations
131 "SCARD",
132 "SDIFF",
133 "SDIFFCARD",
134 "SINTER",
135 "SINTERCARD",
136 "SISMEMBER",
137 "SMISMEMBER",
138 "SMEMBERS",
139 "SRANDMEMBER",
140 "SUNION",
141 "SUNIONCARD",
142 "SSCAN",
143 # Sorted Set Operations
144 "ZCARD",
145 "ZCOUNT",
146 "ZDIFF",
147 "ZINTER",
148 "ZINTERCARD",
149 "ZLEXCOUNT",
150 "ZMSCORE",
151 "ZRANDMEMBER",
152 "ZRANGE",
153 "ZRANGEBYLEX",
154 "ZRANGEBYSCORE",
155 "ZRANK",
156 "ZREVRANGE",
157 "ZREVRANGEBYLEX",
158 "ZREVRANGEBYSCORE",
159 "ZREVRANK",
160 "ZSCAN",
161 "ZSCORE",
162 "ZUNION",
163 # Stream Operations
164 "XLEN",
165 "XPENDING",
166 "XRANGE",
167 "XREAD",
168 "XREVRANGE",
169 # JSON Module
170 "JSON.ARRINDEX",
171 "JSON.ARRLEN",
172 "JSON.GET",
173 "JSON.MGET",
174 "JSON.OBJKEYS",
175 "JSON.OBJLEN",
176 "JSON.RESP",
177 "JSON.STRLEN",
178 "JSON.TYPE",
179 # RediSearch Module
180 "FT.ALIASLIST",
181 "FT.EXPLAIN",
182 "FT.INFO",
183 "FT.PROFILE",
184 "FT.SEARCH",
185 ]
186)
187
188
189class ClusterMultiKeyCommands(ClusterCommandsProtocol):
190 """
191 A class containing commands that handle more than one key
192 """
193
194 # Read-routing configuration, which the cluster clients all set on the instance. The
195 # defaults are here for a host class that mixes these commands in without one - see
196 # ``_is_replica_safe`` below, which is the same fallback for the same audience - so
197 # that ``_execute_pipeline_by_slot`` reads a value rather than raising
198 # ``AttributeError``. Typed under TYPE_CHECKING because ``redis.cluster`` imports this
199 # module.
200 read_from_replicas: bool = False
201 load_balancing_strategy: LoadBalancingStrategy | None = None
202
203 def _partition_keys_by_slot(self, keys: Iterable[KeyT]) -> Dict[int, List[KeyT]]:
204 """Split keys into a dictionary that maps a slot to a list of keys."""
205
206 slots_to_keys = {}
207 for key in keys:
208 slot = key_slot(self.encoder.encode(key))
209 slots_to_keys.setdefault(slot, []).append(key)
210
211 return slots_to_keys
212
213 def _partition_pairs_by_slot(
214 self, mapping: Mapping[AnyKeyT, EncodableT]
215 ) -> Dict[int, List[EncodableT]]:
216 """Split pairs into a dictionary that maps a slot to a list of pairs."""
217
218 slots_to_pairs = {}
219 for pair in mapping.items():
220 slot = key_slot(self.encoder.encode(pair[0]))
221 slots_to_pairs.setdefault(slot, []).extend(pair)
222
223 return slots_to_pairs
224
225 def _is_replica_safe(self, command_name: str) -> bool:
226 warnings.warn(
227 "Using READ_COMMANDS for replica-safe checks is deprecated and will be removed in a future release. "
228 "Use a MetadataResolver instead.",
229 DeprecationWarning,
230 stacklevel=2,
231 )
232 return isinstance(command_name, str) and command_name.upper() in READ_COMMANDS
233
234 def _execute_pipeline_by_slot(
235 self, command: str, slots_to_args: Mapping[int, Iterable[EncodableT]]
236 ) -> List[Any]:
237 replica_safe = (
238 self.read_from_replicas or self.load_balancing_strategy is not None
239 ) and self._is_replica_safe(command)
240 pipe = self.pipeline()
241 [
242 pipe.execute_command(
243 command,
244 *slot_args,
245 target_nodes=[
246 self.nodes_manager.get_node_from_slot(
247 slot,
248 replica_safe,
249 self.load_balancing_strategy if replica_safe else None,
250 )
251 ],
252 )
253 for slot, slot_args in slots_to_args.items()
254 ]
255 return pipe.execute()
256
257 def _reorder_keys_by_command(
258 self,
259 keys: Iterable[KeyT],
260 slots_to_args: Mapping[int, Iterable[EncodableT]],
261 responses: Iterable[Any],
262 ) -> List[Any]:
263 results = {
264 k: v
265 for slot_values, response in zip(slots_to_args.values(), responses)
266 for k, v in zip(slot_values, response)
267 }
268 return [results[key] for key in keys]
269
270 def mget_nonatomic(self, keys: KeysT, *args: KeyT) -> List[Any | None]:
271 """
272 Splits the keys into different slots and then calls MGET
273 for the keys of every slot. This operation will not be atomic
274 if keys belong to more than one slot.
275
276 Returns a list of values ordered identically to ``keys``
277
278 For more information see https://redis.io/commands/mget
279 """
280
281 # Concatenate all keys into a list
282 keys = list_or_args(keys, args)
283
284 # Split keys into slots
285 slots_to_keys = self._partition_keys_by_slot(keys)
286
287 # Execute commands using a pipeline
288 res = self._execute_pipeline_by_slot("MGET", slots_to_keys)
289
290 # Reorder keys in the order the user provided & return
291 return self._reorder_keys_by_command(keys, slots_to_keys, res)
292
293 def mset_nonatomic(self, mapping: Mapping[AnyKeyT, EncodableT]) -> List[bool]:
294 """
295 Sets key/values based on a mapping. Mapping is a dictionary of
296 key/value pairs. Both keys and values should be strings or types that
297 can be cast to a string via str().
298
299 Splits the keys into different slots and then calls MSET
300 for the keys of every slot. This operation will not be atomic
301 if keys belong to more than one slot.
302
303 For more information see https://redis.io/commands/mset
304 """
305
306 # Partition the keys by slot
307 slots_to_pairs = self._partition_pairs_by_slot(mapping)
308
309 # Execute commands using a pipeline & return list of replies
310 return self._execute_pipeline_by_slot("MSET", slots_to_pairs)
311
312 def _split_command_across_slots(self, command: str, *keys: KeyT) -> int:
313 """
314 Runs the given command once for the keys
315 of each slot. Returns the sum of the return values.
316 """
317
318 # Partition the keys by slot
319 slots_to_keys = self._partition_keys_by_slot(keys)
320
321 # Sum up the reply from each command
322 return sum(self._execute_pipeline_by_slot(command, slots_to_keys))
323
324 @overload
325 def exists(self: SyncClientProtocol, *keys: KeyT) -> int: ...
326
327 @overload
328 def exists(self: AsyncClientProtocol, *keys: KeyT) -> Awaitable[int]: ...
329
330 def exists(self, *keys: KeyT) -> int | Awaitable[int]:
331 """
332 Returns the number of ``names`` that exist in the
333 whole cluster. The keys are first split up into slots
334 and then an EXISTS command is sent for every slot
335
336 For more information see https://redis.io/commands/exists
337 """
338 return self._split_command_across_slots("EXISTS", *keys)
339
340 @overload
341 def delete(self: SyncClientProtocol, *keys: KeyT) -> int: ...
342
343 @overload
344 def delete(self: AsyncClientProtocol, *keys: KeyT) -> Awaitable[int]: ...
345
346 def delete(self, *keys: KeyT) -> int | Awaitable[int]:
347 """
348 Deletes the given keys in the cluster.
349 The keys are first split up into slots
350 and then an DEL command is sent for every slot
351
352 Non-existent keys are ignored.
353 Returns the number of keys that were deleted.
354
355 For more information see https://redis.io/commands/del
356 """
357 return self._split_command_across_slots("DEL", *keys)
358
359 @overload
360 def touch(self: SyncClientProtocol, *keys: KeyT) -> int: ...
361
362 @overload
363 def touch(self: AsyncClientProtocol, *keys: KeyT) -> Awaitable[int]: ...
364
365 def touch(self, *keys: KeyT) -> int | Awaitable[int]:
366 """
367 Updates the last access time of given keys across the
368 cluster.
369
370 The keys are first split up into slots
371 and then an TOUCH command is sent for every slot
372
373 Non-existent keys are ignored.
374 Returns the number of keys that were touched.
375
376 For more information see https://redis.io/commands/touch
377 """
378 return self._split_command_across_slots("TOUCH", *keys)
379
380 @overload
381 def unlink(self: SyncClientProtocol, *keys: KeyT) -> int: ...
382
383 @overload
384 def unlink(self: AsyncClientProtocol, *keys: KeyT) -> Awaitable[int]: ...
385
386 def unlink(self, *keys: KeyT) -> int | Awaitable[int]:
387 """
388 Remove the specified keys in a different thread.
389
390 The keys are first split up into slots
391 and then an TOUCH command is sent for every slot
392
393 Non-existent keys are ignored.
394 Returns the number of keys that were unlinked.
395
396 For more information see https://redis.io/commands/unlink
397 """
398 return self._split_command_across_slots("UNLINK", *keys)
399
400
401class AsyncClusterMultiKeyCommands(ClusterMultiKeyCommands):
402 """
403 A class containing commands that handle more than one key
404 """
405
406 async def mget_nonatomic(self, keys: KeysT, *args: KeyT) -> List[Any | None]:
407 """
408 Splits the keys into different slots and then calls MGET
409 for the keys of every slot. This operation will not be atomic
410 if keys belong to more than one slot.
411
412 Returns a list of values ordered identically to ``keys``
413
414 For more information see https://redis.io/commands/mget
415 """
416
417 # Concatenate all keys into a list
418 keys = list_or_args(keys, args)
419
420 # Split keys into slots
421 slots_to_keys = self._partition_keys_by_slot(keys)
422
423 # Execute commands using a pipeline
424 res = await self._execute_pipeline_by_slot("MGET", slots_to_keys)
425
426 # Reorder keys in the order the user provided & return
427 return self._reorder_keys_by_command(keys, slots_to_keys, res)
428
429 async def mset_nonatomic(self, mapping: Mapping[AnyKeyT, EncodableT]) -> List[bool]:
430 """
431 Sets key/values based on a mapping. Mapping is a dictionary of
432 key/value pairs. Both keys and values should be strings or types that
433 can be cast to a string via str().
434
435 Splits the keys into different slots and then calls MSET
436 for the keys of every slot. This operation will not be atomic
437 if keys belong to more than one slot.
438
439 For more information see https://redis.io/commands/mset
440 """
441
442 # Partition the keys by slot
443 slots_to_pairs = self._partition_pairs_by_slot(mapping)
444
445 # Execute commands using a pipeline & return list of replies
446 return await self._execute_pipeline_by_slot("MSET", slots_to_pairs)
447
448 async def _split_command_across_slots(self, command: str, *keys: KeyT) -> int:
449 """
450 Runs the given command once for the keys
451 of each slot. Returns the sum of the return values.
452 """
453
454 # Partition the keys by slot
455 slots_to_keys = self._partition_keys_by_slot(keys)
456
457 # Sum up the reply from each command
458 return sum(await self._execute_pipeline_by_slot(command, slots_to_keys))
459
460 async def _is_replica_safe(self, command_name: str) -> bool:
461 warnings.warn(
462 "Using READ_COMMANDS for replica-safe checks is deprecated and will be removed in a future release. "
463 "Use an AsyncMetadataResolver instead.",
464 DeprecationWarning,
465 stacklevel=2,
466 )
467 return isinstance(command_name, str) and command_name.upper() in READ_COMMANDS
468
469 async def _execute_pipeline_by_slot(
470 self, command: str, slots_to_args: Mapping[int, Iterable[EncodableT]]
471 ) -> List[Any]:
472 # Only _initialize and initialize() are asked of the host class (other
473 # clients may use this mixin), and initialize() returns at once while
474 # a requested refresh is not due
475 if self._initialize:
476 await self.initialize()
477 replica_safe = (
478 self.read_from_replicas or self.load_balancing_strategy is not None
479 ) and await self._is_replica_safe(command)
480 pipe = self.pipeline()
481 [
482 pipe.execute_command(
483 command,
484 *slot_args,
485 target_nodes=[
486 self.nodes_manager.get_node_from_slot(
487 slot,
488 replica_safe,
489 self.load_balancing_strategy if replica_safe else None,
490 )
491 ],
492 )
493 for slot, slot_args in slots_to_args.items()
494 ]
495 return await pipe.execute()
496
497
498class ClusterManagementCommands(ManagementCommands):
499 """
500 A class for Redis Cluster management commands
501
502 The class inherits from Redis's core ManagementCommands class and do the
503 required adjustments to work with cluster mode
504 """
505
506 def slaveof(self, *args, **kwargs) -> NoReturn:
507 """
508 Make the server a replica of another instance, or promote it as master.
509
510 For more information see https://redis.io/commands/slaveof
511 """
512 raise RedisClusterException("SLAVEOF is not supported in cluster mode")
513
514 def replicaof(self, *args, **kwargs) -> NoReturn:
515 """
516 Make the server a replica of another instance, or promote it as master.
517
518 For more information see https://redis.io/commands/replicaof
519 """
520 raise RedisClusterException("REPLICAOF is not supported in cluster mode")
521
522 def swapdb(self, *args, **kwargs) -> NoReturn:
523 """
524 Swaps two Redis databases.
525
526 For more information see https://redis.io/commands/swapdb
527 """
528 raise RedisClusterException("SWAPDB is not supported in cluster mode")
529
530 @overload
531 def cluster_myid(
532 self: SyncClientProtocol, target_node: "TargetNodesT"
533 ) -> bytes | str: ...
534
535 @overload
536 def cluster_myid(
537 self: AsyncClientProtocol, target_node: "TargetNodesT"
538 ) -> Awaitable[bytes | str]: ...
539
540 def cluster_myid(self, target_node: "TargetNodesT") -> (bytes | str) | Awaitable[
541 bytes | str
542 ]:
543 """
544 Returns the node's id.
545
546 :target_node: 'ClusterNode'
547 The node to execute the command on
548
549 For more information check https://redis.io/commands/cluster-myid/
550 """
551 return self.execute_command("CLUSTER MYID", target_nodes=target_node)
552
553 @overload
554 def cluster_addslots(
555 self: SyncClientProtocol, target_node: "TargetNodesT", *slots: EncodableT
556 ) -> bool: ...
557
558 @overload
559 def cluster_addslots(
560 self: AsyncClientProtocol, target_node: "TargetNodesT", *slots: EncodableT
561 ) -> Awaitable[bool]: ...
562
563 def cluster_addslots(
564 self, target_node: "TargetNodesT", *slots: EncodableT
565 ) -> bool | Awaitable[bool]:
566 """
567 Assign new hash slots to receiving node. Sends to specified node.
568
569 :target_node: 'ClusterNode'
570 The node to execute the command on
571
572 For more information see https://redis.io/commands/cluster-addslots
573 """
574 return self.execute_command(
575 "CLUSTER ADDSLOTS", *slots, target_nodes=target_node
576 )
577
578 @overload
579 def cluster_addslotsrange(
580 self: SyncClientProtocol, target_node: "TargetNodesT", *slots: EncodableT
581 ) -> bool: ...
582
583 @overload
584 def cluster_addslotsrange(
585 self: AsyncClientProtocol, target_node: "TargetNodesT", *slots: EncodableT
586 ) -> Awaitable[bool]: ...
587
588 def cluster_addslotsrange(
589 self, target_node: "TargetNodesT", *slots: EncodableT
590 ) -> bool | Awaitable[bool]:
591 """
592 Similar to the CLUSTER ADDSLOTS command.
593 The difference between the two commands is that ADDSLOTS takes a list of slots
594 to assign to the node, while ADDSLOTSRANGE takes a list of slot ranges
595 (specified by start and end slots) to assign to the node.
596
597 :target_node: 'ClusterNode'
598 The node to execute the command on
599
600 For more information see https://redis.io/commands/cluster-addslotsrange
601 """
602 return self.execute_command(
603 "CLUSTER ADDSLOTSRANGE", *slots, target_nodes=target_node
604 )
605
606 @overload
607 def cluster_countkeysinslot(self: SyncClientProtocol, slot_id: int) -> int: ...
608
609 @overload
610 def cluster_countkeysinslot(
611 self: AsyncClientProtocol, slot_id: int
612 ) -> Awaitable[int]: ...
613
614 def cluster_countkeysinslot(self, slot_id: int) -> int | Awaitable[int]:
615 """
616 Return the number of local keys in the specified hash slot
617 Send to node based on specified slot_id
618
619 For more information see https://redis.io/commands/cluster-countkeysinslot
620 """
621 return self.execute_command("CLUSTER COUNTKEYSINSLOT", slot_id)
622
623 @overload
624 def cluster_count_failure_report(self: SyncClientProtocol, node_id: str) -> int: ...
625
626 @overload
627 def cluster_count_failure_report(
628 self: AsyncClientProtocol, node_id: str
629 ) -> Awaitable[int]: ...
630
631 def cluster_count_failure_report(self, node_id: str) -> int | Awaitable[int]:
632 """
633 Return the number of failure reports active for a given node
634 Sends to a random node
635
636 For more information see https://redis.io/commands/cluster-count-failure-reports
637 """
638 return self.execute_command("CLUSTER COUNT-FAILURE-REPORTS", node_id)
639
640 def cluster_delslots(self, *slots: EncodableT) -> List[bool]:
641 """
642 Set hash slots as unbound in the cluster.
643 It determines by it self what node the slot is in and sends it there
644
645 Returns a list of the results for each processed slot.
646
647 For more information see https://redis.io/commands/cluster-delslots
648 """
649 return [self.execute_command("CLUSTER DELSLOTS", slot) for slot in slots]
650
651 @overload
652 def cluster_delslotsrange(self: SyncClientProtocol, *slots: EncodableT) -> bool: ...
653
654 @overload
655 def cluster_delslotsrange(
656 self: AsyncClientProtocol, *slots: EncodableT
657 ) -> Awaitable[bool]: ...
658
659 def cluster_delslotsrange(self, *slots: EncodableT) -> bool | Awaitable[bool]:
660 """
661 Similar to the CLUSTER DELSLOTS command.
662 The difference is that CLUSTER DELSLOTS takes a list of hash slots to remove
663 from the node, while CLUSTER DELSLOTSRANGE takes a list of slot ranges to remove
664 from the node.
665
666 For more information see https://redis.io/commands/cluster-delslotsrange
667 """
668 return self.execute_command("CLUSTER DELSLOTSRANGE", *slots)
669
670 @overload
671 def cluster_failover(
672 self: SyncClientProtocol,
673 target_node: "TargetNodesT",
674 option: str | None = None,
675 ) -> bool: ...
676
677 @overload
678 def cluster_failover(
679 self: AsyncClientProtocol,
680 target_node: "TargetNodesT",
681 option: str | None = None,
682 ) -> Awaitable[bool]: ...
683
684 def cluster_failover(
685 self, target_node: "TargetNodesT", option: str | None = None
686 ) -> bool | Awaitable[bool]:
687 """
688 Forces a slave to perform a manual failover of its master
689 Sends to specified node
690
691 :target_node: 'ClusterNode'
692 The node to execute the command on
693
694 For more information see https://redis.io/commands/cluster-failover
695 """
696 if option:
697 if option.upper() not in ["FORCE", "TAKEOVER"]:
698 raise RedisError(
699 f"Invalid option for CLUSTER FAILOVER command: {option}"
700 )
701 else:
702 return self.execute_command(
703 "CLUSTER FAILOVER", option, target_nodes=target_node
704 )
705 else:
706 return self.execute_command("CLUSTER FAILOVER", target_nodes=target_node)
707
708 @overload
709 def cluster_info(
710 self: SyncClientProtocol, target_nodes: "TargetNodesT" | None = None
711 ) -> dict[str, str]: ...
712
713 @overload
714 def cluster_info(
715 self: AsyncClientProtocol, target_nodes: "TargetNodesT" | None = None
716 ) -> Awaitable[dict[str, str]]: ...
717
718 def cluster_info(
719 self, target_nodes: "TargetNodesT" | None = None
720 ) -> dict[str, str] | Awaitable[dict[str, str]]:
721 """
722 Provides info about Redis Cluster node state.
723 The command will be sent to a random node in the cluster if no target
724 node is specified.
725
726 For more information see https://redis.io/commands/cluster-info
727 """
728 return self.execute_command("CLUSTER INFO", target_nodes=target_nodes)
729
730 @overload
731 def cluster_keyslot(self: SyncClientProtocol, key: str) -> int: ...
732
733 @overload
734 def cluster_keyslot(self: AsyncClientProtocol, key: str) -> Awaitable[int]: ...
735
736 def cluster_keyslot(self, key: str) -> int | Awaitable[int]:
737 """
738 Returns the hash slot of the specified key
739 Sends to random node in the cluster
740
741 For more information see https://redis.io/commands/cluster-keyslot
742 """
743 return self.execute_command("CLUSTER KEYSLOT", key)
744
745 @overload
746 def cluster_meet(
747 self: SyncClientProtocol,
748 host: str,
749 port: int,
750 target_nodes: "TargetNodesT" | None = None,
751 ) -> bool: ...
752
753 @overload
754 def cluster_meet(
755 self: AsyncClientProtocol,
756 host: str,
757 port: int,
758 target_nodes: "TargetNodesT" | None = None,
759 ) -> Awaitable[bool]: ...
760
761 def cluster_meet(
762 self, host: str, port: int, target_nodes: "TargetNodesT" | None = None
763 ) -> bool | Awaitable[bool]:
764 """
765 Force a node cluster to handshake with another node.
766 Sends to specified node.
767
768 For more information see https://redis.io/commands/cluster-meet
769 """
770 return self.execute_command(
771 "CLUSTER MEET", host, port, target_nodes=target_nodes
772 )
773
774 @overload
775 def cluster_nodes(self: SyncClientProtocol) -> dict[str, ClusterNodeDetail]: ...
776
777 @overload
778 def cluster_nodes(
779 self: AsyncClientProtocol,
780 ) -> Awaitable[dict[str, ClusterNodeDetail]]: ...
781
782 def cluster_nodes(
783 self,
784 ) -> dict[str, ClusterNodeDetail] | Awaitable[dict[str, ClusterNodeDetail]]:
785 """
786 Get Cluster config for the node.
787 Sends to random node in the cluster
788
789 For more information see https://redis.io/commands/cluster-nodes
790 """
791 return self.execute_command("CLUSTER NODES")
792
793 @overload
794 def cluster_replicate(
795 self: SyncClientProtocol, target_nodes: "TargetNodesT", node_id: str
796 ) -> bool: ...
797
798 @overload
799 def cluster_replicate(
800 self: AsyncClientProtocol, target_nodes: "TargetNodesT", node_id: str
801 ) -> Awaitable[bool]: ...
802
803 def cluster_replicate(
804 self, target_nodes: "TargetNodesT", node_id: str
805 ) -> bool | Awaitable[bool]:
806 """
807 Reconfigure a node as a slave of the specified master node
808
809 For more information see https://redis.io/commands/cluster-replicate
810 """
811 return self.execute_command(
812 "CLUSTER REPLICATE", node_id, target_nodes=target_nodes
813 )
814
815 @overload
816 def cluster_reset(
817 self: SyncClientProtocol,
818 soft: bool = True,
819 target_nodes: "TargetNodesT" | None = None,
820 ) -> bool: ...
821
822 @overload
823 def cluster_reset(
824 self: AsyncClientProtocol,
825 soft: bool = True,
826 target_nodes: "TargetNodesT" | None = None,
827 ) -> Awaitable[bool]: ...
828
829 def cluster_reset(
830 self, soft: bool = True, target_nodes: "TargetNodesT" | None = None
831 ) -> bool | Awaitable[bool]:
832 """
833 Reset a Redis Cluster node
834
835 If 'soft' is True then it will send 'SOFT' argument
836 If 'soft' is False then it will send 'HARD' argument
837
838 For more information see https://redis.io/commands/cluster-reset
839 """
840 return self.execute_command(
841 "CLUSTER RESET", b"SOFT" if soft else b"HARD", target_nodes=target_nodes
842 )
843
844 @overload
845 def cluster_save_config(
846 self: SyncClientProtocol, target_nodes: "TargetNodesT" | None = None
847 ) -> bool: ...
848
849 @overload
850 def cluster_save_config(
851 self: AsyncClientProtocol, target_nodes: "TargetNodesT" | None = None
852 ) -> Awaitable[bool]: ...
853
854 def cluster_save_config(
855 self, target_nodes: "TargetNodesT" | None = None
856 ) -> bool | Awaitable[bool]:
857 """
858 Forces the node to save cluster state on disk
859
860 For more information see https://redis.io/commands/cluster-saveconfig
861 """
862 return self.execute_command("CLUSTER SAVECONFIG", target_nodes=target_nodes)
863
864 @overload
865 def cluster_get_keys_in_slot(
866 self: SyncClientProtocol, slot: int, num_keys: int
867 ) -> list[bytes | str]: ...
868
869 @overload
870 def cluster_get_keys_in_slot(
871 self: AsyncClientProtocol, slot: int, num_keys: int
872 ) -> Awaitable[list[bytes | str]]: ...
873
874 def cluster_get_keys_in_slot(
875 self, slot: int, num_keys: int
876 ) -> list[bytes | str] | Awaitable[list[bytes | str]]:
877 """
878 Returns the number of keys in the specified cluster slot
879
880 For more information see https://redis.io/commands/cluster-getkeysinslot
881 """
882 return self.execute_command("CLUSTER GETKEYSINSLOT", slot, num_keys)
883
884 @overload
885 def cluster_set_config_epoch(
886 self: SyncClientProtocol, epoch: int, target_nodes: "TargetNodesT" | None = None
887 ) -> bool: ...
888
889 @overload
890 def cluster_set_config_epoch(
891 self: AsyncClientProtocol,
892 epoch: int,
893 target_nodes: "TargetNodesT" | None = None,
894 ) -> Awaitable[bool]: ...
895
896 def cluster_set_config_epoch(
897 self, epoch: int, target_nodes: "TargetNodesT" | None = None
898 ) -> bool | Awaitable[bool]:
899 """
900 Set the configuration epoch in a new node
901
902 For more information see https://redis.io/commands/cluster-set-config-epoch
903 """
904 return self.execute_command(
905 "CLUSTER SET-CONFIG-EPOCH", epoch, target_nodes=target_nodes
906 )
907
908 @overload
909 def cluster_setslot(
910 self: SyncClientProtocol,
911 target_node: "TargetNodesT",
912 node_id: str,
913 slot_id: int,
914 state: str,
915 ) -> bool: ...
916
917 @overload
918 def cluster_setslot(
919 self: AsyncClientProtocol,
920 target_node: "TargetNodesT",
921 node_id: str,
922 slot_id: int,
923 state: str,
924 ) -> Awaitable[bool]: ...
925
926 def cluster_setslot(
927 self, target_node: "TargetNodesT", node_id: str, slot_id: int, state: str
928 ) -> bool | Awaitable[bool]:
929 """
930 Bind an hash slot to a specific node
931
932 :target_node: 'ClusterNode'
933 The node to execute the command on
934
935 For more information see https://redis.io/commands/cluster-setslot
936 """
937 if state.upper() in ("IMPORTING", "NODE", "MIGRATING"):
938 return self.execute_command(
939 "CLUSTER SETSLOT", slot_id, state, node_id, target_nodes=target_node
940 )
941 elif state.upper() == "STABLE":
942 raise RedisError('For "stable" state please use cluster_setslot_stable')
943 else:
944 raise RedisError(f"Invalid slot state: {state}")
945
946 @overload
947 def cluster_setslot_stable(self: SyncClientProtocol, slot_id: int) -> bool: ...
948
949 @overload
950 def cluster_setslot_stable(
951 self: AsyncClientProtocol, slot_id: int
952 ) -> Awaitable[bool]: ...
953
954 def cluster_setslot_stable(self, slot_id: int) -> bool | Awaitable[bool]:
955 """
956 Clears migrating / importing state from the slot.
957 It determines by it self what node the slot is in and sends it there.
958
959 For more information see https://redis.io/commands/cluster-setslot
960 """
961 return self.execute_command("CLUSTER SETSLOT", slot_id, "STABLE")
962
963 @overload
964 def cluster_replicas(
965 self: SyncClientProtocol,
966 node_id: str,
967 target_nodes: "TargetNodesT" | None = None,
968 ) -> dict[str, ClusterNodeDetail]: ...
969
970 @overload
971 def cluster_replicas(
972 self: AsyncClientProtocol,
973 node_id: str,
974 target_nodes: "TargetNodesT" | None = None,
975 ) -> Awaitable[dict[str, ClusterNodeDetail]]: ...
976
977 def cluster_replicas(
978 self, node_id: str, target_nodes: "TargetNodesT" | None = None
979 ) -> dict[str, ClusterNodeDetail] | Awaitable[dict[str, ClusterNodeDetail]]:
980 """
981 Provides a list of replica nodes replicating from the specified primary
982 target node.
983
984 For more information see https://redis.io/commands/cluster-replicas
985 """
986 return self.execute_command(
987 "CLUSTER REPLICAS", node_id, target_nodes=target_nodes
988 )
989
990 @overload
991 def cluster_slots(
992 self: SyncClientProtocol, target_nodes: "TargetNodesT" | None = None
993 ) -> list[Any]: ...
994
995 @overload
996 def cluster_slots(
997 self: AsyncClientProtocol, target_nodes: "TargetNodesT" | None = None
998 ) -> Awaitable[list[Any]]: ...
999
1000 def cluster_slots(
1001 self, target_nodes: "TargetNodesT" | None = None
1002 ) -> list[Any] | Awaitable[list[Any]]:
1003 """
1004 Get array of Cluster slot to node mappings
1005
1006 For more information see https://redis.io/commands/cluster-slots
1007 """
1008 return self.execute_command("CLUSTER SLOTS", target_nodes=target_nodes)
1009
1010 @overload
1011 def cluster_shards(
1012 self: SyncClientProtocol, target_nodes: "TargetNodesT" | None = None
1013 ) -> ClusterShardsResponse: ...
1014
1015 @overload
1016 def cluster_shards(
1017 self: AsyncClientProtocol, target_nodes: "TargetNodesT" | None = None
1018 ) -> Awaitable[ClusterShardsResponse]: ...
1019
1020 def cluster_shards(
1021 self, target_nodes: "TargetNodesT" | None = None
1022 ) -> ClusterShardsResponse | Awaitable[ClusterShardsResponse]:
1023 """
1024 Returns details about the shards of the cluster.
1025
1026 For more information see https://redis.io/commands/cluster-shards
1027 """
1028 return self.execute_command("CLUSTER SHARDS", target_nodes=target_nodes)
1029
1030 @overload
1031 def cluster_myshardid(
1032 self: SyncClientProtocol, target_nodes: "TargetNodesT" | None = None
1033 ) -> bytes | str: ...
1034
1035 @overload
1036 def cluster_myshardid(
1037 self: AsyncClientProtocol, target_nodes: "TargetNodesT" | None = None
1038 ) -> Awaitable[bytes | str]: ...
1039
1040 def cluster_myshardid(self, target_nodes: "TargetNodesT" | None = None) -> (
1041 bytes | str
1042 ) | Awaitable[bytes | str]:
1043 """
1044 Returns the shard ID of the node.
1045
1046 For more information see https://redis.io/commands/cluster-myshardid/
1047 """
1048 return self.execute_command("CLUSTER MYSHARDID", target_nodes=target_nodes)
1049
1050 @overload
1051 def cluster_links(
1052 self: SyncClientProtocol, target_node: "TargetNodesT"
1053 ) -> ClusterLinksResponse: ...
1054
1055 @overload
1056 def cluster_links(
1057 self: AsyncClientProtocol, target_node: "TargetNodesT"
1058 ) -> Awaitable[ClusterLinksResponse]: ...
1059
1060 def cluster_links(
1061 self, target_node: "TargetNodesT"
1062 ) -> ClusterLinksResponse | Awaitable[ClusterLinksResponse]:
1063 """
1064 Each node in a Redis Cluster maintains a pair of long-lived TCP link with each
1065 peer in the cluster: One for sending outbound messages towards the peer and one
1066 for receiving inbound messages from the peer.
1067
1068 This command outputs information of all such peer links as an array.
1069
1070 For more information see https://redis.io/commands/cluster-links
1071 """
1072 return self.execute_command("CLUSTER LINKS", target_nodes=target_node)
1073
1074 def cluster_flushslots(self, target_nodes: "TargetNodesT" | None = None) -> None:
1075 raise NotImplementedError(
1076 "CLUSTER FLUSHSLOTS is intentionally not implemented in the client."
1077 )
1078
1079 def cluster_bumpepoch(self, target_nodes: "TargetNodesT" | None = None) -> None:
1080 raise NotImplementedError(
1081 "CLUSTER BUMPEPOCH is intentionally not implemented in the client."
1082 )
1083
1084 def readonly(self, target_nodes: "TargetNodesT" | None = None) -> ResponseT:
1085 """
1086 Enables read queries.
1087 The command will be sent to the default cluster node if target_nodes is
1088 not specified.
1089
1090 For more information see https://redis.io/commands/readonly
1091 """
1092 if target_nodes == "replicas" or target_nodes == "all":
1093 # read_from_replicas will only be enabled if the READONLY command
1094 # is sent to all replicas
1095 self.read_from_replicas = True
1096 return self.execute_command("READONLY", target_nodes=target_nodes)
1097
1098 def readwrite(self, target_nodes: "TargetNodesT" | None = None) -> ResponseT:
1099 """
1100 Disables read queries.
1101 The command will be sent to the default cluster node if target_nodes is
1102 not specified.
1103
1104 For more information see https://redis.io/commands/readwrite
1105 """
1106 # Reset read from replicas flag
1107 self.read_from_replicas = False
1108 return self.execute_command("READWRITE", target_nodes=target_nodes)
1109
1110 @deprecated_function(
1111 version="7.2.0",
1112 reason="Use client-side caching feature instead.",
1113 )
1114 def client_tracking_on(
1115 self,
1116 clientid: int | None = None,
1117 prefix: Sequence[KeyT] = [],
1118 bcast: bool = False,
1119 optin: bool = False,
1120 optout: bool = False,
1121 noloop: bool = False,
1122 target_nodes: "TargetNodesT" | None = "all",
1123 ) -> ResponseT:
1124 """
1125 Enables the tracking feature of the Redis server, that is used
1126 for server assisted client side caching.
1127
1128 When clientid is provided - in target_nodes only the node that owns the
1129 connection with this id should be provided.
1130 When clientid is not provided - target_nodes can be any node.
1131
1132 On a client with client-side caching enabled this raises ``RedisError``:
1133 the cache enables tracking itself.
1134
1135 For more information see https://redis.io/commands/client-tracking
1136 """
1137 return self.client_tracking(
1138 True,
1139 clientid,
1140 prefix,
1141 bcast,
1142 optin,
1143 optout,
1144 noloop,
1145 target_nodes=target_nodes,
1146 )
1147
1148 @deprecated_function(
1149 version="7.2.0",
1150 reason="Use client-side caching feature instead.",
1151 )
1152 def client_tracking_off(
1153 self,
1154 clientid: int | None = None,
1155 prefix: Sequence[KeyT] = [],
1156 bcast: bool = False,
1157 optin: bool = False,
1158 optout: bool = False,
1159 noloop: bool = False,
1160 target_nodes: "TargetNodesT" | None = "all",
1161 ) -> ResponseT:
1162 """
1163 Disables the tracking feature of the Redis server, that is used
1164 for server assisted client side caching.
1165
1166 When clientid is provided - in target_nodes only the node that owns the
1167 connection with this id should be provided.
1168 When clientid is not provided - target_nodes can be any node.
1169
1170 On a client with client-side caching enabled this raises ``RedisError``:
1171 turning tracking off would stop invalidations for cached replies.
1172
1173 For more information see https://redis.io/commands/client-tracking
1174 """
1175 return self.client_tracking(
1176 False,
1177 clientid,
1178 prefix,
1179 bcast,
1180 optin,
1181 optout,
1182 noloop,
1183 target_nodes=target_nodes,
1184 )
1185
1186 def hotkeys_start(
1187 self,
1188 metrics: List[HotkeysMetricsTypes],
1189 count: int | None = None,
1190 duration: int | None = None,
1191 sample_ratio: int | None = None,
1192 slots: List[int] | None = None,
1193 **kwargs,
1194 ) -> str | bytes:
1195 """
1196 Cluster client does not support hotkeys command. Please use the non-cluster client.
1197
1198 For more information see https://redis.io/commands/hotkeys-start
1199 """
1200 raise NotImplementedError(
1201 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1202 )
1203
1204 def hotkeys_stop(self, **kwargs) -> str | bytes:
1205 """
1206 Cluster client does not support hotkeys command. Please use the non-cluster client.
1207
1208 For more information see https://redis.io/commands/hotkeys-stop
1209 """
1210 raise NotImplementedError(
1211 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1212 )
1213
1214 def hotkeys_reset(self, **kwargs) -> str | bytes:
1215 """
1216 Cluster client does not support hotkeys command. Please use the non-cluster client.
1217
1218 For more information see https://redis.io/commands/hotkeys-reset
1219 """
1220 raise NotImplementedError(
1221 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1222 )
1223
1224 def hotkeys_get(self, **kwargs) -> list[dict[str | bytes, Any]]:
1225 """
1226 Cluster client does not support hotkeys command. Please use the non-cluster client.
1227
1228 For more information see https://redis.io/commands/hotkeys-get
1229 """
1230 raise NotImplementedError(
1231 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1232 )
1233
1234
1235class AsyncClusterManagementCommands(
1236 ClusterManagementCommands, AsyncManagementCommands
1237):
1238 """
1239 A class for Redis Cluster management commands
1240
1241 The class inherits from Redis's core ManagementCommands class and do the
1242 required adjustments to work with cluster mode
1243 """
1244
1245 async def cluster_delslots(self, *slots: EncodableT) -> List[bool]:
1246 """
1247 Set hash slots as unbound in the cluster.
1248 It determines by it self what node the slot is in and sends it there
1249
1250 Returns a list of the results for each processed slot.
1251
1252 For more information see https://redis.io/commands/cluster-delslots
1253 """
1254 return await asyncio.gather(
1255 *(
1256 asyncio.create_task(self.execute_command("CLUSTER DELSLOTS", slot))
1257 for slot in slots
1258 )
1259 )
1260
1261 @deprecated_function(
1262 version="7.2.0",
1263 reason="Use client-side caching feature instead.",
1264 )
1265 async def client_tracking_on(
1266 self,
1267 clientid: int | None = None,
1268 prefix: Sequence[KeyT] = [],
1269 bcast: bool = False,
1270 optin: bool = False,
1271 optout: bool = False,
1272 noloop: bool = False,
1273 target_nodes: "TargetNodesT" | None = "all",
1274 ) -> ResponseT:
1275 """
1276 Enables the tracking feature of the Redis server, that is used
1277 for server assisted client side caching.
1278
1279 When clientid is provided - in target_nodes only the node that owns the
1280 connection with this id should be provided.
1281 When clientid is not provided - target_nodes can be any node.
1282
1283 For more information see https://redis.io/commands/client-tracking
1284 """
1285 return await self.client_tracking(
1286 True,
1287 clientid,
1288 prefix,
1289 bcast,
1290 optin,
1291 optout,
1292 noloop,
1293 target_nodes=target_nodes,
1294 )
1295
1296 @deprecated_function(
1297 version="7.2.0",
1298 reason="Use client-side caching feature instead.",
1299 )
1300 async def client_tracking_off(
1301 self,
1302 clientid: int | None = None,
1303 prefix: Sequence[KeyT] = [],
1304 bcast: bool = False,
1305 optin: bool = False,
1306 optout: bool = False,
1307 noloop: bool = False,
1308 target_nodes: "TargetNodesT" | None = "all",
1309 ) -> ResponseT:
1310 """
1311 Disables the tracking feature of the Redis server, that is used
1312 for server assisted client side caching.
1313
1314 When clientid is provided - in target_nodes only the node that owns the
1315 connection with this id should be provided.
1316 When clientid is not provided - target_nodes can be any node.
1317
1318 For more information see https://redis.io/commands/client-tracking
1319 """
1320 return await self.client_tracking(
1321 False,
1322 clientid,
1323 prefix,
1324 bcast,
1325 optin,
1326 optout,
1327 noloop,
1328 target_nodes=target_nodes,
1329 )
1330
1331 async def hotkeys_start(
1332 self,
1333 metrics: List[HotkeysMetricsTypes],
1334 count: int | None = None,
1335 duration: int | None = None,
1336 sample_ratio: int | None = None,
1337 slots: List[int] | None = None,
1338 **kwargs,
1339 ) -> Awaitable[str | bytes]:
1340 """
1341 Cluster client does not support hotkeys command. Please use the non-cluster client.
1342
1343 For more information see https://redis.io/commands/hotkeys-start
1344 """
1345 raise NotImplementedError(
1346 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1347 )
1348
1349 async def hotkeys_stop(self, **kwargs) -> Awaitable[str | bytes]:
1350 """
1351 Cluster client does not support hotkeys command. Please use the non-cluster client.
1352
1353 For more information see https://redis.io/commands/hotkeys-stop
1354 """
1355 raise NotImplementedError(
1356 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1357 )
1358
1359 async def hotkeys_reset(self, **kwargs) -> Awaitable[str | bytes]:
1360 """
1361 Cluster client does not support hotkeys command. Please use the non-cluster client.
1362
1363 For more information see https://redis.io/commands/hotkeys-reset
1364 """
1365 raise NotImplementedError(
1366 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1367 )
1368
1369 async def hotkeys_get(self, **kwargs) -> Awaitable[list[dict[str | bytes, Any]]]:
1370 """
1371 Cluster client does not support hotkeys command. Please use the non-cluster client.
1372
1373 For more information see https://redis.io/commands/hotkeys-get
1374 """
1375 raise NotImplementedError(
1376 "HOTKEYS commands are not supported in cluster mode. Please use the non-cluster client."
1377 )
1378
1379
1380class ClusterDataAccessCommands(DataAccessCommands):
1381 """
1382 A class for Redis Cluster Data Access Commands
1383
1384 The class inherits from Redis's core DataAccessCommand class and do the
1385 required adjustments to work with cluster mode
1386 """
1387
1388 @overload
1389 def stralgo(
1390 self: SyncClientProtocol,
1391 algo: Literal["LCS"],
1392 value1: KeyT,
1393 value2: KeyT,
1394 specific_argument: Literal["strings"] | Literal["keys"] = "strings",
1395 len: bool = False,
1396 idx: bool = False,
1397 minmatchlen: int | None = None,
1398 withmatchlen: bool = False,
1399 **kwargs,
1400 ) -> StralgoResponse: ...
1401
1402 @overload
1403 def stralgo(
1404 self: AsyncClientProtocol,
1405 algo: Literal["LCS"],
1406 value1: KeyT,
1407 value2: KeyT,
1408 specific_argument: Literal["strings"] | Literal["keys"] = "strings",
1409 len: bool = False,
1410 idx: bool = False,
1411 minmatchlen: int | None = None,
1412 withmatchlen: bool = False,
1413 **kwargs,
1414 ) -> Awaitable[StralgoResponse]: ...
1415
1416 def stralgo(
1417 self,
1418 algo: Literal["LCS"],
1419 value1: KeyT,
1420 value2: KeyT,
1421 specific_argument: Literal["strings"] | Literal["keys"] = "strings",
1422 len: bool = False,
1423 idx: bool = False,
1424 minmatchlen: int | None = None,
1425 withmatchlen: bool = False,
1426 **kwargs,
1427 ) -> StralgoResponse | Awaitable[StralgoResponse]:
1428 """
1429 Implements complex algorithms that operate on strings.
1430 Right now the only algorithm implemented is the LCS algorithm
1431 (longest common substring). However new algorithms could be
1432 implemented in the future.
1433
1434 ``algo`` Right now must be LCS
1435 ``value1`` and ``value2`` Can be two strings or two keys
1436 ``specific_argument`` Specifying if the arguments to the algorithm
1437 will be keys or strings. strings is the default.
1438 ``len`` Returns just the len of the match.
1439 ``idx`` Returns the match positions in each string.
1440 ``minmatchlen`` Restrict the list of matches to the ones of a given
1441 minimal length. Can be provided only when ``idx`` set to True.
1442 ``withmatchlen`` Returns the matches with the len of the match.
1443 Can be provided only when ``idx`` set to True.
1444
1445 For more information see https://redis.io/commands/stralgo
1446 """
1447 target_nodes = kwargs.pop("target_nodes", None)
1448 if specific_argument == "strings" and target_nodes is None:
1449 target_nodes = "default-node"
1450 kwargs.update({"target_nodes": target_nodes})
1451 return super().stralgo(
1452 algo,
1453 value1,
1454 value2,
1455 specific_argument,
1456 len,
1457 idx,
1458 minmatchlen,
1459 withmatchlen,
1460 **kwargs,
1461 )
1462
1463 def scan_iter(
1464 self,
1465 match: PatternT | None = None,
1466 count: int | None = None,
1467 _type: str | None = None,
1468 **kwargs,
1469 ) -> Iterator:
1470 # Do the first query with cursor=0 for all nodes
1471 cursors, data = self.scan(match=match, count=count, _type=_type, **kwargs)
1472 yield from data
1473
1474 cursors = {name: cursor for name, cursor in cursors.items() if cursor != 0}
1475 if cursors:
1476 # Get nodes by name
1477 nodes = {name: self.get_node(node_name=name) for name in cursors.keys()}
1478
1479 # Iterate over each node till its cursor is 0
1480 kwargs.pop("target_nodes", None)
1481 while cursors:
1482 for name, cursor in cursors.items():
1483 cur, data = self.scan(
1484 cursor=cursor,
1485 match=match,
1486 count=count,
1487 _type=_type,
1488 target_nodes=nodes[name],
1489 **kwargs,
1490 )
1491 yield from data
1492 cursors[name] = cur[name]
1493
1494 cursors = {
1495 name: cursor for name, cursor in cursors.items() if cursor != 0
1496 }
1497
1498
1499class AsyncClusterDataAccessCommands(
1500 ClusterDataAccessCommands, AsyncDataAccessCommands
1501):
1502 """
1503 A class for Redis Cluster Data Access Commands
1504
1505 The class inherits from Redis's core DataAccessCommand class and do the
1506 required adjustments to work with cluster mode
1507 """
1508
1509 async def scan_iter(
1510 self,
1511 match: PatternT | None = None,
1512 count: int | None = None,
1513 _type: str | None = None,
1514 **kwargs,
1515 ) -> AsyncIterator:
1516 # Do the first query with cursor=0 for all nodes
1517 cursors, data = await self.scan(match=match, count=count, _type=_type, **kwargs)
1518 for value in data:
1519 yield value
1520
1521 cursors = {name: cursor for name, cursor in cursors.items() if cursor != 0}
1522 if cursors:
1523 # Get nodes by name
1524 nodes = {name: self.get_node(node_name=name) for name in cursors.keys()}
1525
1526 # Iterate over each node till its cursor is 0
1527 kwargs.pop("target_nodes", None)
1528 while cursors:
1529 for name, cursor in cursors.items():
1530 cur, data = await self.scan(
1531 cursor=cursor,
1532 match=match,
1533 count=count,
1534 _type=_type,
1535 target_nodes=nodes[name],
1536 **kwargs,
1537 )
1538 for value in data:
1539 yield value
1540 cursors[name] = cur[name]
1541
1542 cursors = {
1543 name: cursor for name, cursor in cursors.items() if cursor != 0
1544 }
1545
1546
1547class ClusterBlessCommands(BlessCommands):
1548 """
1549 A class for Redis Cluster BLESS commands
1550
1551 The class inherits from Redis's core BlessCommands class and does the
1552 required adjustments to work with cluster mode
1553 """
1554
1555 def bless_scan_iter(
1556 self,
1557 flag: BlessFlag,
1558 count: int | None = None,
1559 **kwargs,
1560 ) -> Iterator[bytes | str]:
1561 # Do the first query with cursor=0 for all nodes
1562 cursors, data = self.bless_scan(cursor=0, flag=flag, count=count, **kwargs)
1563 yield from data
1564
1565 cursors = {name: cursor for name, cursor in cursors.items() if cursor != 0}
1566 if cursors:
1567 # Get nodes by name
1568 nodes = {name: self.get_node(node_name=name) for name in cursors.keys()}
1569
1570 # Iterate over each node till its cursor is 0
1571 kwargs.pop("target_nodes", None)
1572 while cursors:
1573 for name, cursor in cursors.items():
1574 cur, data = self.bless_scan(
1575 cursor=cursor,
1576 flag=flag,
1577 count=count,
1578 target_nodes=nodes[name],
1579 **kwargs,
1580 )
1581 yield from data
1582 cursors[name] = cur[name]
1583
1584 cursors = {
1585 name: cursor for name, cursor in cursors.items() if cursor != 0
1586 }
1587
1588
1589class AsyncClusterBlessCommands(ClusterBlessCommands, AsyncBlessCommands):
1590 """
1591 A class for Redis Cluster BLESS commands
1592
1593 The class inherits from Redis's core BlessCommands class and does the
1594 required adjustments to work with cluster mode
1595 """
1596
1597 async def bless_scan_iter(
1598 self,
1599 flag: BlessFlag,
1600 count: int | None = None,
1601 **kwargs,
1602 ) -> AsyncIterator[bytes | str]:
1603 # Do the first query with cursor=0 for all nodes
1604 cursors, data = await self.bless_scan(
1605 cursor=0, flag=flag, count=count, **kwargs
1606 )
1607 for value in data:
1608 yield value
1609
1610 cursors = {name: cursor for name, cursor in cursors.items() if cursor != 0}
1611 if cursors:
1612 # Get nodes by name
1613 nodes = {name: self.get_node(node_name=name) for name in cursors.keys()}
1614
1615 # Iterate over each node till its cursor is 0
1616 kwargs.pop("target_nodes", None)
1617 while cursors:
1618 for name, cursor in cursors.items():
1619 cur, data = await self.bless_scan(
1620 cursor=cursor,
1621 flag=flag,
1622 count=count,
1623 target_nodes=nodes[name],
1624 **kwargs,
1625 )
1626 for value in data:
1627 yield value
1628 cursors[name] = cur[name]
1629
1630 cursors = {
1631 name: cursor for name, cursor in cursors.items() if cursor != 0
1632 }
1633
1634
1635class RedisClusterCommands(
1636 ClusterMultiKeyCommands,
1637 ClusterManagementCommands,
1638 ACLCommands,
1639 PubSubCommands,
1640 ClusterDataAccessCommands,
1641 ScriptCommands,
1642 FunctionCommands,
1643 ClusterBlessCommands,
1644 ModuleCommands,
1645 RedisModuleCommands,
1646):
1647 """
1648 A class for all Redis Cluster commands
1649
1650 For key-based commands, the target node(s) will be internally determined
1651 by the keys' hash slot.
1652 Non-key-based commands can be executed with the 'target_nodes' argument to
1653 target specific nodes. By default, if target_nodes is not specified, the
1654 command will be executed on the default cluster node.
1655
1656 :param target_nodes: type can be one of the following:
1657 - nodes flag: ALL_NODES, PRIMARIES, REPLICAS, RANDOM
1658 - 'ClusterNode'
1659 - 'list(ClusterNodes)'
1660 - 'dict(any:clusterNodes)'
1661
1662 for example:
1663 r.cluster_info(target_nodes=RedisCluster.ALL_NODES)
1664 """
1665
1666
1667class AsyncRedisClusterCommands(
1668 AsyncClusterMultiKeyCommands,
1669 AsyncClusterManagementCommands,
1670 AsyncACLCommands,
1671 PubSubCommands,
1672 AsyncClusterDataAccessCommands,
1673 AsyncScriptCommands,
1674 AsyncFunctionCommands,
1675 AsyncClusterBlessCommands,
1676 AsyncModuleCommands,
1677 AsyncRedisModuleCommands,
1678):
1679 """
1680 A class for all Redis Cluster commands
1681
1682 For key-based commands, the target node(s) will be internally determined
1683 by the keys' hash slot.
1684 Non-key-based commands can be executed with the 'target_nodes' argument to
1685 target specific nodes. By default, if target_nodes is not specified, the
1686 command will be executed on the default cluster node.
1687
1688 :param target_nodes: type can be one of the following:
1689 - nodes flag: ALL_NODES, PRIMARIES, REPLICAS, RANDOM
1690 - 'ClusterNode'
1691 - 'list(ClusterNodes)'
1692 - 'dict(any:clusterNodes)'
1693
1694 for example:
1695 r.cluster_info(target_nodes=RedisCluster.ALL_NODES)
1696 """