redis 6.0.0b2__py3-none-any.whl → 6.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
redis/cluster.py CHANGED
@@ -3,18 +3,25 @@ import socket
3
3
  import sys
4
4
  import threading
5
5
  import time
6
+ from abc import ABC, abstractmethod
6
7
  from collections import OrderedDict
8
+ from copy import copy
7
9
  from enum import Enum
8
- from typing import Any, Callable, Dict, List, Optional, Tuple, Union
10
+ from itertools import chain
11
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
9
12
 
10
13
  from redis._parsers import CommandsParser, Encoder
11
14
  from redis._parsers.helpers import parse_scan
12
- from redis.backoff import default_backoff
15
+ from redis.backoff import ExponentialWithJitterBackoff, NoBackoff
13
16
  from redis.cache import CacheConfig, CacheFactory, CacheFactoryInterface, CacheInterface
14
- from redis.client import CaseInsensitiveDict, PubSub, Redis
17
+ from redis.client import EMPTY_RESPONSE, CaseInsensitiveDict, PubSub, Redis
15
18
  from redis.commands import READ_COMMANDS, RedisClusterCommands
16
19
  from redis.commands.helpers import list_or_args
17
- from redis.connection import ConnectionPool, parse_url
20
+ from redis.connection import (
21
+ Connection,
22
+ ConnectionPool,
23
+ parse_url,
24
+ )
18
25
  from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot
19
26
  from redis.event import (
20
27
  AfterPooledConnectionsInstantiationEvent,
@@ -28,7 +35,10 @@ from redis.exceptions import (
28
35
  ClusterDownError,
29
36
  ClusterError,
30
37
  ConnectionError,
38
+ CrossSlotTransactionError,
31
39
  DataError,
40
+ ExecAbortError,
41
+ InvalidPipelineStack,
32
42
  MovedError,
33
43
  RedisClusterException,
34
44
  RedisError,
@@ -36,6 +46,7 @@ from redis.exceptions import (
36
46
  SlotNotCoveredError,
37
47
  TimeoutError,
38
48
  TryAgainError,
49
+ WatchError,
39
50
  )
40
51
  from redis.lock import Lock
41
52
  from redis.retry import Retry
@@ -58,9 +69,9 @@ def get_node_name(host: str, port: Union[str, int]) -> str:
58
69
  @deprecated_args(
59
70
  allowed_args=["redis_node"],
60
71
  reason="Use get_connection(redis_node) instead",
61
- version="5.0.3",
72
+ version="5.3.0",
62
73
  )
63
- def get_connection(redis_node, *args, **options):
74
+ def get_connection(redis_node: Redis, *args, **options) -> Connection:
64
75
  return redis_node.connection or redis_node.connection_pool.get_connection()
65
76
 
66
77
 
@@ -142,7 +153,6 @@ REPLICA = "replica"
142
153
  SLOT_ID = "slot-id"
143
154
 
144
155
  REDIS_ALLOWED_KEYS = (
145
- "charset",
146
156
  "connection_class",
147
157
  "connection_pool",
148
158
  "connection_pool_class",
@@ -152,7 +162,6 @@ REDIS_ALLOWED_KEYS = (
152
162
  "decode_responses",
153
163
  "encoding",
154
164
  "encoding_errors",
155
- "errors",
156
165
  "host",
157
166
  "lib_name",
158
167
  "lib_version",
@@ -176,12 +185,13 @@ REDIS_ALLOWED_KEYS = (
176
185
  "ssl_cert_reqs",
177
186
  "ssl_keyfile",
178
187
  "ssl_password",
188
+ "ssl_check_hostname",
179
189
  "unix_socket_path",
180
190
  "username",
181
191
  "cache",
182
192
  "cache_config",
183
193
  )
184
- KWARGS_DISABLED_KEYS = ("host", "port")
194
+ KWARGS_DISABLED_KEYS = ("host", "port", "retry")
185
195
 
186
196
 
187
197
  def cleanup_kwargs(**kwargs):
@@ -412,7 +422,12 @@ class AbstractRedisCluster:
412
422
  list_keys_to_dict(["SCRIPT FLUSH"], lambda command, res: all(res.values())),
413
423
  )
414
424
 
415
- ERRORS_ALLOW_RETRY = (ConnectionError, TimeoutError, ClusterDownError)
425
+ ERRORS_ALLOW_RETRY = (
426
+ ConnectionError,
427
+ TimeoutError,
428
+ ClusterDownError,
429
+ SlotNotCoveredError,
430
+ )
416
431
 
417
432
  def replace_default_node(self, target_node: "ClusterNode" = None) -> None:
418
433
  """Replace the default cluster node.
@@ -433,7 +448,7 @@ class AbstractRedisCluster:
433
448
  # Choose a primary if the cluster contains different primaries
434
449
  self.nodes_manager.default_node = random.choice(primaries)
435
450
  else:
436
- # Otherwise, hoose a primary if the cluster contains different primaries
451
+ # Otherwise, choose a primary if the cluster contains different primaries
437
452
  replicas = [node for node in self.get_replicas() if node != curr_node]
438
453
  if replicas:
439
454
  self.nodes_manager.default_node = random.choice(replicas)
@@ -487,7 +502,14 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
487
502
  @deprecated_args(
488
503
  args_to_warn=["read_from_replicas"],
489
504
  reason="Please configure the 'load_balancing_strategy' instead",
490
- version="5.0.3",
505
+ version="5.3.0",
506
+ )
507
+ @deprecated_args(
508
+ args_to_warn=[
509
+ "cluster_error_retry_attempts",
510
+ ],
511
+ reason="Please configure the 'retry' object instead",
512
+ version="6.0.0",
491
513
  )
492
514
  def __init__(
493
515
  self,
@@ -496,7 +518,7 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
496
518
  startup_nodes: Optional[List["ClusterNode"]] = None,
497
519
  cluster_error_retry_attempts: int = 3,
498
520
  retry: Optional["Retry"] = None,
499
- require_full_coverage: bool = False,
521
+ require_full_coverage: bool = True,
500
522
  reinitialize_steps: int = 5,
501
523
  read_from_replicas: bool = False,
502
524
  load_balancing_strategy: Optional["LoadBalancingStrategy"] = None,
@@ -546,9 +568,19 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
546
568
  If you use dynamic DNS endpoints for startup nodes but CLUSTER SLOTS lists
547
569
  specific IP addresses, it is best to set it to false.
548
570
  :param cluster_error_retry_attempts:
571
+ @deprecated - Please configure the 'retry' object instead
572
+ In case 'retry' object is set - this argument is ignored!
573
+
549
574
  Number of times to retry before raising an error when
550
- :class:`~.TimeoutError` or :class:`~.ConnectionError` or
575
+ :class:`~.TimeoutError` or :class:`~.ConnectionError`, :class:`~.SlotNotCoveredError` or
551
576
  :class:`~.ClusterDownError` are encountered
577
+ :param retry:
578
+ A retry object that defines the retry strategy and the number of
579
+ retries for the cluster client.
580
+ In current implementation for the cluster client (starting form redis-py version 6.0.0)
581
+ the retry object is not yet fully utilized, instead it is used just to determine
582
+ the number of retries for the cluster client.
583
+ In the future releases the retry object will be used to handle the cluster client retries!
552
584
  :param reinitialize_steps:
553
585
  Specifies the number of MOVED errors that need to occur before
554
586
  reinitializing the whole cluster topology. If a MOVED error occurs
@@ -568,7 +600,8 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
568
600
 
569
601
  :**kwargs:
570
602
  Extra arguments that will be sent into Redis instance when created
571
- (See Official redis-py doc for supported kwargs
603
+ (See Official redis-py doc for supported kwargs - the only limitation
604
+ is that you can't provide 'retry' object as part of kwargs.
572
605
  [https://github.com/andymccurdy/redis-py/blob/master/redis/client.py])
573
606
  Some kwargs are not supported and will raise a
574
607
  RedisClusterException:
@@ -583,6 +616,15 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
583
616
  "Argument 'db' is not possible to use in cluster mode"
584
617
  )
585
618
 
619
+ if "retry" in kwargs:
620
+ # Argument 'retry' is not possible to be used in kwargs when in cluster mode
621
+ # the kwargs are set to the lower level connections to the cluster nodes
622
+ # and there we provide retry configuration without retries allowed.
623
+ # The retries should be handled on cluster client level.
624
+ raise RedisClusterException(
625
+ "The 'retry' argument cannot be used in kwargs when running in cluster mode."
626
+ )
627
+
586
628
  # Get the startup node/s
587
629
  from_url = False
588
630
  if url is not None:
@@ -625,9 +667,11 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
625
667
  kwargs = cleanup_kwargs(**kwargs)
626
668
  if retry:
627
669
  self.retry = retry
628
- kwargs.update({"retry": self.retry})
629
670
  else:
630
- kwargs.update({"retry": Retry(default_backoff(), 0)})
671
+ self.retry = Retry(
672
+ backoff=ExponentialWithJitterBackoff(base=1, cap=10),
673
+ retries=cluster_error_retry_attempts,
674
+ )
631
675
 
632
676
  self.encoder = Encoder(
633
677
  kwargs.get("encoding", "utf-8"),
@@ -638,7 +682,6 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
638
682
  if (cache_config or cache) and protocol not in [3, "3"]:
639
683
  raise RedisError("Client caching is only supported with RESP version 3")
640
684
 
641
- self.cluster_error_retry_attempts = cluster_error_retry_attempts
642
685
  self.command_flags = self.__class__.COMMAND_FLAGS.copy()
643
686
  self.node_flags = self.__class__.NODE_FLAGS.copy()
644
687
  self.read_from_replicas = read_from_replicas
@@ -710,7 +753,7 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
710
753
  if self.user_on_connect_func is not None:
711
754
  self.user_on_connect_func(connection)
712
755
 
713
- def get_redis_connection(self, node):
756
+ def get_redis_connection(self, node: "ClusterNode") -> Redis:
714
757
  if not node.redis_connection:
715
758
  with self._lock:
716
759
  if not node.redis_connection:
@@ -769,13 +812,8 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
769
812
  self.nodes_manager.default_node = node
770
813
  return True
771
814
 
772
- def get_retry(self) -> Optional["Retry"]:
773
- return self.retry
774
-
775
- def set_retry(self, retry: "Retry") -> None:
815
+ def set_retry(self, retry: Retry) -> None:
776
816
  self.retry = retry
777
- for node in self.get_nodes():
778
- node.redis_connection.set_retry(retry)
779
817
 
780
818
  def monitor(self, target_node=None):
781
819
  """
@@ -813,20 +851,19 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
813
851
  if shard_hint:
814
852
  raise RedisClusterException("shard_hint is deprecated in cluster mode")
815
853
 
816
- if transaction:
817
- raise RedisClusterException("transaction is deprecated in cluster mode")
818
-
819
854
  return ClusterPipeline(
820
855
  nodes_manager=self.nodes_manager,
821
856
  commands_parser=self.commands_parser,
822
857
  startup_nodes=self.nodes_manager.startup_nodes,
823
858
  result_callbacks=self.result_callbacks,
824
859
  cluster_response_callbacks=self.cluster_response_callbacks,
825
- cluster_error_retry_attempts=self.cluster_error_retry_attempts,
860
+ cluster_error_retry_attempts=self.retry.get_retries(),
826
861
  read_from_replicas=self.read_from_replicas,
827
862
  load_balancing_strategy=self.load_balancing_strategy,
828
863
  reinitialize_steps=self.reinitialize_steps,
864
+ retry=self.retry,
829
865
  lock=self._lock,
866
+ transaction=transaction,
830
867
  )
831
868
 
832
869
  def lock(
@@ -988,7 +1025,7 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
988
1025
  redis_conn = self.get_default_node().redis_connection
989
1026
  return self.commands_parser.get_keys(redis_conn, *args)
990
1027
 
991
- def determine_slot(self, *args):
1028
+ def determine_slot(self, *args) -> int:
992
1029
  """
993
1030
  Figure out what slot to use based on args.
994
1031
 
@@ -1087,8 +1124,8 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
1087
1124
  """
1088
1125
  Wrapper for ERRORS_ALLOW_RETRY error handling.
1089
1126
 
1090
- It will try the number of times specified by the config option
1091
- "self.cluster_error_retry_attempts" which defaults to 3 unless manually
1127
+ It will try the number of times specified by the retries property from
1128
+ config option "self.retry" which defaults to 3 unless manually
1092
1129
  configured.
1093
1130
 
1094
1131
  If it reaches the number of times, the command will raise the exception
@@ -1114,9 +1151,7 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
1114
1151
  # execution since the nodes may not be valid anymore after the tables
1115
1152
  # were reinitialized. So in case of passed target nodes,
1116
1153
  # retry_attempts will be set to 0.
1117
- retry_attempts = (
1118
- 0 if target_nodes_specified else self.cluster_error_retry_attempts
1119
- )
1154
+ retry_attempts = 0 if target_nodes_specified else self.retry.get_retries()
1120
1155
  # Add one for the first execution
1121
1156
  execute_attempts = 1 + retry_attempts
1122
1157
  for _ in range(execute_attempts):
@@ -1203,8 +1238,6 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
1203
1238
  except AuthenticationError:
1204
1239
  raise
1205
1240
  except (ConnectionError, TimeoutError) as e:
1206
- # Connection retries are being handled in the node's
1207
- # Retry object.
1208
1241
  # ConnectionError can also be raised if we couldn't get a
1209
1242
  # connection from the pool before timing out, so check that
1210
1243
  # this is an actual connection before attempting to disconnect.
@@ -1241,13 +1274,19 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
1241
1274
  except AskError as e:
1242
1275
  redirect_addr = get_node_name(host=e.host, port=e.port)
1243
1276
  asking = True
1244
- except ClusterDownError as e:
1277
+ except (ClusterDownError, SlotNotCoveredError):
1245
1278
  # ClusterDownError can occur during a failover and to get
1246
1279
  # self-healed, we will try to reinitialize the cluster layout
1247
1280
  # and retry executing the command
1281
+
1282
+ # SlotNotCoveredError can occur when the cluster is not fully
1283
+ # initialized or can be temporary issue.
1284
+ # We will try to reinitialize the cluster topology
1285
+ # and retry executing the command
1286
+
1248
1287
  time.sleep(0.25)
1249
1288
  self.nodes_manager.initialize()
1250
- raise e
1289
+ raise
1251
1290
  except ResponseError:
1252
1291
  raise
1253
1292
  except Exception as e:
@@ -1299,6 +1338,28 @@ class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
1299
1338
  """
1300
1339
  setattr(self, funcname, func)
1301
1340
 
1341
+ def transaction(self, func, *watches, **kwargs):
1342
+ """
1343
+ Convenience method for executing the callable `func` as a transaction
1344
+ while watching all keys specified in `watches`. The 'func' callable
1345
+ should expect a single argument which is a Pipeline object.
1346
+ """
1347
+ shard_hint = kwargs.pop("shard_hint", None)
1348
+ value_from_callable = kwargs.pop("value_from_callable", False)
1349
+ watch_delay = kwargs.pop("watch_delay", None)
1350
+ with self.pipeline(True, shard_hint) as pipe:
1351
+ while True:
1352
+ try:
1353
+ if watches:
1354
+ pipe.watch(*watches)
1355
+ func_value = func(pipe)
1356
+ exec_value = pipe.execute()
1357
+ return func_value if value_from_callable else exec_value
1358
+ except WatchError:
1359
+ if watch_delay is not None and watch_delay > 0:
1360
+ time.sleep(watch_delay)
1361
+ continue
1362
+
1302
1363
 
1303
1364
  class ClusterNode:
1304
1365
  def __init__(self, host, port, server_type=None, redis_connection=None):
@@ -1324,8 +1385,12 @@ class ClusterNode:
1324
1385
  return isinstance(obj, ClusterNode) and obj.name == self.name
1325
1386
 
1326
1387
  def __del__(self):
1327
- if self.redis_connection is not None:
1328
- self.redis_connection.close()
1388
+ try:
1389
+ if self.redis_connection is not None:
1390
+ self.redis_connection.close()
1391
+ except Exception:
1392
+ # Ignore errors when closing the connection
1393
+ pass
1329
1394
 
1330
1395
 
1331
1396
  class LoadBalancingStrategy(Enum):
@@ -1392,7 +1457,7 @@ class NodesManager:
1392
1457
  event_dispatcher: Optional[EventDispatcher] = None,
1393
1458
  **kwargs,
1394
1459
  ):
1395
- self.nodes_cache = {}
1460
+ self.nodes_cache: Dict[str, Redis] = {}
1396
1461
  self.slots_cache = {}
1397
1462
  self.startup_nodes = {}
1398
1463
  self.default_node = None
@@ -1484,7 +1549,7 @@ class NodesManager:
1484
1549
  "In case you need select some load balancing strategy "
1485
1550
  "that will use replicas, please set it through 'load_balancing_strategy'"
1486
1551
  ),
1487
- version="5.0.3",
1552
+ version="5.3.0",
1488
1553
  )
1489
1554
  def get_node_from_slot(
1490
1555
  self,
@@ -1492,7 +1557,7 @@ class NodesManager:
1492
1557
  read_from_replicas=False,
1493
1558
  load_balancing_strategy=None,
1494
1559
  server_type=None,
1495
- ):
1560
+ ) -> ClusterNode:
1496
1561
  """
1497
1562
  Gets a node that servers this hash slot
1498
1563
  """
@@ -1576,17 +1641,32 @@ class NodesManager:
1576
1641
  )
1577
1642
 
1578
1643
  def create_redis_node(self, host, port, **kwargs):
1644
+ # We are configuring the connection pool not to retry
1645
+ # connections on lower level clients to avoid retrying
1646
+ # connections to nodes that are not reachable
1647
+ # and to avoid blocking the connection pool.
1648
+ # The only error that will have some handling in the lower
1649
+ # level clients is ConnectionError which will trigger disconnection
1650
+ # of the socket.
1651
+ # The retries will be handled on cluster client level
1652
+ # where we will have proper handling of the cluster topology
1653
+ node_retry_config = Retry(
1654
+ backoff=NoBackoff(), retries=0, supported_errors=(ConnectionError,)
1655
+ )
1656
+
1579
1657
  if self.from_url:
1580
1658
  # Create a redis node with a costumed connection pool
1581
1659
  kwargs.update({"host": host})
1582
1660
  kwargs.update({"port": port})
1583
1661
  kwargs.update({"cache": self._cache})
1662
+ kwargs.update({"retry": node_retry_config})
1584
1663
  r = Redis(connection_pool=self.connection_pool_class(**kwargs))
1585
1664
  else:
1586
1665
  r = Redis(
1587
1666
  host=host,
1588
1667
  port=port,
1589
1668
  cache=self._cache,
1669
+ retry=node_retry_config,
1590
1670
  **kwargs,
1591
1671
  )
1592
1672
  return r
@@ -1624,7 +1704,9 @@ class NodesManager:
1624
1704
  fully_covered = False
1625
1705
  kwargs = self.connection_kwargs
1626
1706
  exception = None
1627
- for startup_node in self.startup_nodes.values():
1707
+ # Convert to tuple to prevent RuntimeError if self.startup_nodes
1708
+ # is modified during iteration
1709
+ for startup_node in tuple(self.startup_nodes.values()):
1628
1710
  try:
1629
1711
  if startup_node.redis_connection:
1630
1712
  r = startup_node.redis_connection
@@ -1771,6 +1853,16 @@ class NodesManager:
1771
1853
  return self.address_remap((host, port))
1772
1854
  return host, port
1773
1855
 
1856
+ def find_connection_owner(self, connection: Connection) -> Optional[Redis]:
1857
+ node_name = get_node_name(connection.host, connection.port)
1858
+ for node in tuple(self.nodes_cache.values()):
1859
+ if node.redis_connection:
1860
+ conn_args = node.redis_connection.connection_pool.connection_kwargs
1861
+ if node_name == get_node_name(
1862
+ conn_args.get("host"), conn_args.get("port")
1863
+ ):
1864
+ return node
1865
+
1774
1866
 
1775
1867
  class ClusterPubSub(PubSub):
1776
1868
  """
@@ -2030,6 +2122,17 @@ class ClusterPipeline(RedisCluster):
2030
2122
  TryAgainError,
2031
2123
  )
2032
2124
 
2125
+ NO_SLOTS_COMMANDS = {"UNWATCH"}
2126
+ IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
2127
+ UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
2128
+
2129
+ @deprecated_args(
2130
+ args_to_warn=[
2131
+ "cluster_error_retry_attempts",
2132
+ ],
2133
+ reason="Please configure the 'retry' object instead",
2134
+ version="6.0.0",
2135
+ )
2033
2136
  def __init__(
2034
2137
  self,
2035
2138
  nodes_manager: "NodesManager",
@@ -2041,7 +2144,9 @@ class ClusterPipeline(RedisCluster):
2041
2144
  load_balancing_strategy: Optional[LoadBalancingStrategy] = None,
2042
2145
  cluster_error_retry_attempts: int = 3,
2043
2146
  reinitialize_steps: int = 5,
2147
+ retry: Optional[Retry] = None,
2044
2148
  lock=None,
2149
+ transaction=False,
2045
2150
  **kwargs,
2046
2151
  ):
2047
2152
  """ """
@@ -2057,9 +2162,16 @@ class ClusterPipeline(RedisCluster):
2057
2162
  self.load_balancing_strategy = load_balancing_strategy
2058
2163
  self.command_flags = self.__class__.COMMAND_FLAGS.copy()
2059
2164
  self.cluster_response_callbacks = cluster_response_callbacks
2060
- self.cluster_error_retry_attempts = cluster_error_retry_attempts
2061
2165
  self.reinitialize_counter = 0
2062
2166
  self.reinitialize_steps = reinitialize_steps
2167
+ if retry is not None:
2168
+ self.retry = retry
2169
+ else:
2170
+ self.retry = Retry(
2171
+ backoff=ExponentialWithJitterBackoff(base=1, cap=10),
2172
+ retries=cluster_error_retry_attempts,
2173
+ )
2174
+
2063
2175
  self.encoder = Encoder(
2064
2176
  kwargs.get("encoding", "utf-8"),
2065
2177
  kwargs.get("encoding_errors", "strict"),
@@ -2068,6 +2180,10 @@ class ClusterPipeline(RedisCluster):
2068
2180
  if lock is None:
2069
2181
  lock = threading.Lock()
2070
2182
  self._lock = lock
2183
+ self.parent_execute_command = super().execute_command
2184
+ self._execution_strategy: ExecutionStrategy = (
2185
+ PipelineStrategy(self) if not transaction else TransactionStrategy(self)
2186
+ )
2071
2187
 
2072
2188
  def __repr__(self):
2073
2189
  """ """
@@ -2089,7 +2205,7 @@ class ClusterPipeline(RedisCluster):
2089
2205
 
2090
2206
  def __len__(self):
2091
2207
  """ """
2092
- return len(self.command_stack)
2208
+ return len(self._execution_strategy.command_queue)
2093
2209
 
2094
2210
  def __bool__(self):
2095
2211
  "Pipeline instances should always evaluate to True on Python 3+"
@@ -2099,45 +2215,35 @@ class ClusterPipeline(RedisCluster):
2099
2215
  """
2100
2216
  Wrapper function for pipeline_execute_command
2101
2217
  """
2102
- return self.pipeline_execute_command(*args, **kwargs)
2218
+ return self._execution_strategy.execute_command(*args, **kwargs)
2103
2219
 
2104
2220
  def pipeline_execute_command(self, *args, **options):
2105
2221
  """
2106
- Appends the executed command to the pipeline's command stack
2107
- """
2108
- self.command_stack.append(
2109
- PipelineCommand(args, options, len(self.command_stack))
2110
- )
2111
- return self
2222
+ Stage a command to be executed when execute() is next called
2112
2223
 
2113
- def raise_first_error(self, stack):
2114
- """
2115
- Raise the first exception on the stack
2224
+ Returns the current Pipeline object back so commands can be
2225
+ chained together, such as:
2226
+
2227
+ pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
2228
+
2229
+ At some other point, you can then run: pipe.execute(),
2230
+ which will execute all commands queued in the pipe.
2116
2231
  """
2117
- for c in stack:
2118
- r = c.result
2119
- if isinstance(r, Exception):
2120
- self.annotate_exception(r, c.position + 1, c.args)
2121
- raise r
2232
+ return self._execution_strategy.execute_command(*args, **options)
2122
2233
 
2123
2234
  def annotate_exception(self, exception, number, command):
2124
2235
  """
2125
2236
  Provides extra context to the exception prior to it being handled
2126
2237
  """
2127
- cmd = " ".join(map(safe_str, command))
2128
- msg = (
2129
- f"Command # {number} ({truncate_text(cmd)}) of pipeline "
2130
- f"caused error: {exception.args[0]}"
2131
- )
2132
- exception.args = (msg,) + exception.args[1:]
2238
+ self._execution_strategy.annotate_exception(exception, number, command)
2133
2239
 
2134
2240
  def execute(self, raise_on_error: bool = True) -> List[Any]:
2135
2241
  """
2136
2242
  Execute all the commands in the current pipeline
2137
2243
  """
2138
- stack = self.command_stack
2244
+
2139
2245
  try:
2140
- return self.send_cluster_commands(stack, raise_on_error)
2246
+ return self._execution_strategy.execute(raise_on_error)
2141
2247
  finally:
2142
2248
  self.reset()
2143
2249
 
@@ -2145,312 +2251,53 @@ class ClusterPipeline(RedisCluster):
2145
2251
  """
2146
2252
  Reset back to empty pipeline.
2147
2253
  """
2148
- self.command_stack = []
2149
-
2150
- self.scripts = set()
2151
-
2152
- # TODO: Implement
2153
- # make sure to reset the connection state in the event that we were
2154
- # watching something
2155
- # if self.watching and self.connection:
2156
- # try:
2157
- # # call this manually since our unwatch or
2158
- # # immediate_execute_command methods can call reset()
2159
- # self.connection.send_command('UNWATCH')
2160
- # self.connection.read_response()
2161
- # except ConnectionError:
2162
- # # disconnect will also remove any previous WATCHes
2163
- # self.connection.disconnect()
2164
-
2165
- # clean up the other instance attributes
2166
- self.watching = False
2167
- self.explicit_transaction = False
2168
-
2169
- # TODO: Implement
2170
- # we can safely return the connection to the pool here since we're
2171
- # sure we're no longer WATCHing anything
2172
- # if self.connection:
2173
- # self.connection_pool.release(self.connection)
2174
- # self.connection = None
2254
+ self._execution_strategy.reset()
2175
2255
 
2176
2256
  def send_cluster_commands(
2177
2257
  self, stack, raise_on_error=True, allow_redirections=True
2178
2258
  ):
2179
- """
2180
- Wrapper for CLUSTERDOWN error handling.
2259
+ return self._execution_strategy.send_cluster_commands(
2260
+ stack, raise_on_error=raise_on_error, allow_redirections=allow_redirections
2261
+ )
2181
2262
 
2182
- If the cluster reports it is down it is assumed that:
2183
- - connection_pool was disconnected
2184
- - connection_pool was reseted
2185
- - refereh_table_asap set to True
2263
+ def exists(self, *keys):
2264
+ return self._execution_strategy.exists(*keys)
2186
2265
 
2187
- It will try the number of times specified by
2188
- the config option "self.cluster_error_retry_attempts"
2189
- which defaults to 3 unless manually configured.
2266
+ def eval(self):
2267
+ """ """
2268
+ return self._execution_strategy.eval()
2190
2269
 
2191
- If it reaches the number of times, the command will
2192
- raises ClusterDownException.
2270
+ def multi(self):
2193
2271
  """
2194
- if not stack:
2195
- return []
2196
- retry_attempts = self.cluster_error_retry_attempts
2197
- while True:
2198
- try:
2199
- return self._send_cluster_commands(
2200
- stack,
2201
- raise_on_error=raise_on_error,
2202
- allow_redirections=allow_redirections,
2203
- )
2204
- except RedisCluster.ERRORS_ALLOW_RETRY as e:
2205
- if retry_attempts > 0:
2206
- # Try again with the new cluster setup. All other errors
2207
- # should be raised.
2208
- retry_attempts -= 1
2209
- pass
2210
- else:
2211
- raise e
2212
-
2213
- def _send_cluster_commands(
2214
- self, stack, raise_on_error=True, allow_redirections=True
2215
- ):
2272
+ Start a transactional block of the pipeline after WATCH commands
2273
+ are issued. End the transactional block with `execute`.
2216
2274
  """
2217
- Send a bunch of cluster commands to the redis cluster.
2275
+ self._execution_strategy.multi()
2218
2276
 
2219
- `allow_redirections` If the pipeline should follow
2220
- `ASK` & `MOVED` responses automatically. If set
2221
- to false it will raise RedisClusterException.
2222
- """
2223
- # the first time sending the commands we send all of
2224
- # the commands that were queued up.
2225
- # if we have to run through it again, we only retry
2226
- # the commands that failed.
2227
- attempt = sorted(stack, key=lambda x: x.position)
2228
- is_default_node = False
2229
- # build a list of node objects based on node names we need to
2230
- nodes = {}
2277
+ def load_scripts(self):
2278
+ """ """
2279
+ self._execution_strategy.load_scripts()
2231
2280
 
2232
- # as we move through each command that still needs to be processed,
2233
- # we figure out the slot number that command maps to, then from
2234
- # the slot determine the node.
2235
- for c in attempt:
2236
- while True:
2237
- # refer to our internal node -> slot table that
2238
- # tells us where a given command should route to.
2239
- # (it might be possible we have a cached node that no longer
2240
- # exists in the cluster, which is why we do this in a loop)
2241
- passed_targets = c.options.pop("target_nodes", None)
2242
- if passed_targets and not self._is_nodes_flag(passed_targets):
2243
- target_nodes = self._parse_target_nodes(passed_targets)
2244
- else:
2245
- target_nodes = self._determine_nodes(
2246
- *c.args, node_flag=passed_targets
2247
- )
2248
- if not target_nodes:
2249
- raise RedisClusterException(
2250
- f"No targets were found to execute {c.args} command on"
2251
- )
2252
- if len(target_nodes) > 1:
2253
- raise RedisClusterException(
2254
- f"Too many targets for command {c.args}"
2255
- )
2281
+ def discard(self):
2282
+ """ """
2283
+ self._execution_strategy.discard()
2256
2284
 
2257
- node = target_nodes[0]
2258
- if node == self.get_default_node():
2259
- is_default_node = True
2285
+ def watch(self, *names):
2286
+ """Watches the values at keys ``names``"""
2287
+ self._execution_strategy.watch(*names)
2260
2288
 
2261
- # now that we know the name of the node
2262
- # ( it's just a string in the form of host:port )
2263
- # we can build a list of commands for each node.
2264
- node_name = node.name
2265
- if node_name not in nodes:
2266
- redis_node = self.get_redis_connection(node)
2267
- try:
2268
- connection = get_connection(redis_node)
2269
- except (ConnectionError, TimeoutError):
2270
- for n in nodes.values():
2271
- n.connection_pool.release(n.connection)
2272
- # Connection retries are being handled in the node's
2273
- # Retry object. Reinitialize the node -> slot table.
2274
- self.nodes_manager.initialize()
2275
- if is_default_node:
2276
- self.replace_default_node()
2277
- raise
2278
- nodes[node_name] = NodeCommands(
2279
- redis_node.parse_response,
2280
- redis_node.connection_pool,
2281
- connection,
2282
- )
2283
- nodes[node_name].append(c)
2284
- break
2289
+ def unwatch(self):
2290
+ """Unwatches all previously specified keys"""
2291
+ self._execution_strategy.unwatch()
2285
2292
 
2286
- # send the commands in sequence.
2287
- # we write to all the open sockets for each node first,
2288
- # before reading anything
2289
- # this allows us to flush all the requests out across the
2290
- # network essentially in parallel
2291
- # so that we can read them all in parallel as they come back.
2292
- # we dont' multiplex on the sockets as they come available,
2293
- # but that shouldn't make too much difference.
2294
- node_commands = nodes.values()
2295
- try:
2296
- node_commands = nodes.values()
2297
- for n in node_commands:
2298
- n.write()
2293
+ def script_load_for_pipeline(self, *args, **kwargs):
2294
+ self._execution_strategy.script_load_for_pipeline(*args, **kwargs)
2299
2295
 
2300
- for n in node_commands:
2301
- n.read()
2302
- finally:
2303
- # release all of the redis connections we allocated earlier
2304
- # back into the connection pool.
2305
- # we used to do this step as part of a try/finally block,
2306
- # but it is really dangerous to
2307
- # release connections back into the pool if for some
2308
- # reason the socket has data still left in it
2309
- # from a previous operation. The write and
2310
- # read operations already have try/catch around them for
2311
- # all known types of errors including connection
2312
- # and socket level errors.
2313
- # So if we hit an exception, something really bad
2314
- # happened and putting any oF
2315
- # these connections back into the pool is a very bad idea.
2316
- # the socket might have unread buffer still sitting in it,
2317
- # and then the next time we read from it we pass the
2318
- # buffered result back from a previous command and
2319
- # every single request after to that connection will always get
2320
- # a mismatched result.
2321
- for n in nodes.values():
2322
- n.connection_pool.release(n.connection)
2296
+ def delete(self, *names):
2297
+ self._execution_strategy.delete(*names)
2323
2298
 
2324
- # if the response isn't an exception it is a
2325
- # valid response from the node
2326
- # we're all done with that command, YAY!
2327
- # if we have more commands to attempt, we've run into problems.
2328
- # collect all the commands we are allowed to retry.
2329
- # (MOVED, ASK, or connection errors or timeout errors)
2330
- attempt = sorted(
2331
- (
2332
- c
2333
- for c in attempt
2334
- if isinstance(c.result, ClusterPipeline.ERRORS_ALLOW_RETRY)
2335
- ),
2336
- key=lambda x: x.position,
2337
- )
2338
- if attempt and allow_redirections:
2339
- # RETRY MAGIC HAPPENS HERE!
2340
- # send these remaining commands one at a time using `execute_command`
2341
- # in the main client. This keeps our retry logic
2342
- # in one place mostly,
2343
- # and allows us to be more confident in correctness of behavior.
2344
- # at this point any speed gains from pipelining have been lost
2345
- # anyway, so we might as well make the best
2346
- # attempt to get the correct behavior.
2347
- #
2348
- # The client command will handle retries for each
2349
- # individual command sequentially as we pass each
2350
- # one into `execute_command`. Any exceptions
2351
- # that bubble out should only appear once all
2352
- # retries have been exhausted.
2353
- #
2354
- # If a lot of commands have failed, we'll be setting the
2355
- # flag to rebuild the slots table from scratch.
2356
- # So MOVED errors should correct themselves fairly quickly.
2357
- self.reinitialize_counter += 1
2358
- if self._should_reinitialized():
2359
- self.nodes_manager.initialize()
2360
- if is_default_node:
2361
- self.replace_default_node()
2362
- for c in attempt:
2363
- try:
2364
- # send each command individually like we
2365
- # do in the main client.
2366
- c.result = super().execute_command(*c.args, **c.options)
2367
- except RedisError as e:
2368
- c.result = e
2369
-
2370
- # turn the response back into a simple flat array that corresponds
2371
- # to the sequence of commands issued in the stack in pipeline.execute()
2372
- response = []
2373
- for c in sorted(stack, key=lambda x: x.position):
2374
- if c.args[0] in self.cluster_response_callbacks:
2375
- # Remove keys entry, it needs only for cache.
2376
- c.options.pop("keys", None)
2377
- c.result = self.cluster_response_callbacks[c.args[0]](
2378
- c.result, **c.options
2379
- )
2380
- response.append(c.result)
2381
-
2382
- if raise_on_error:
2383
- self.raise_first_error(stack)
2384
-
2385
- return response
2386
-
2387
- def _fail_on_redirect(self, allow_redirections):
2388
- """ """
2389
- if not allow_redirections:
2390
- raise RedisClusterException(
2391
- "ASK & MOVED redirection not allowed in this pipeline"
2392
- )
2393
-
2394
- def exists(self, *keys):
2395
- return self.execute_command("EXISTS", *keys)
2396
-
2397
- def eval(self):
2398
- """ """
2399
- raise RedisClusterException("method eval() is not implemented")
2400
-
2401
- def multi(self):
2402
- """ """
2403
- raise RedisClusterException("method multi() is not implemented")
2404
-
2405
- def immediate_execute_command(self, *args, **options):
2406
- """ """
2407
- raise RedisClusterException(
2408
- "method immediate_execute_command() is not implemented"
2409
- )
2410
-
2411
- def _execute_transaction(self, *args, **kwargs):
2412
- """ """
2413
- raise RedisClusterException("method _execute_transaction() is not implemented")
2414
-
2415
- def load_scripts(self):
2416
- """ """
2417
- raise RedisClusterException("method load_scripts() is not implemented")
2418
-
2419
- def watch(self, *names):
2420
- """ """
2421
- raise RedisClusterException("method watch() is not implemented")
2422
-
2423
- def unwatch(self):
2424
- """ """
2425
- raise RedisClusterException("method unwatch() is not implemented")
2426
-
2427
- def script_load_for_pipeline(self, *args, **kwargs):
2428
- """ """
2429
- raise RedisClusterException(
2430
- "method script_load_for_pipeline() is not implemented"
2431
- )
2432
-
2433
- def delete(self, *names):
2434
- """
2435
- "Delete a key specified by ``names``"
2436
- """
2437
- if len(names) != 1:
2438
- raise RedisClusterException(
2439
- "deleting multiple keys is not implemented in pipeline command"
2440
- )
2441
-
2442
- return self.execute_command("DEL", names[0])
2443
-
2444
- def unlink(self, *names):
2445
- """
2446
- "Unlink a key specified by ``names``"
2447
- """
2448
- if len(names) != 1:
2449
- raise RedisClusterException(
2450
- "unlinking multiple keys is not implemented in pipeline command"
2451
- )
2452
-
2453
- return self.execute_command("UNLINK", names[0])
2299
+ def unlink(self, *names):
2300
+ self._execution_strategy.unlink(*names)
2454
2301
 
2455
2302
 
2456
2303
  def block_pipeline_command(name: str) -> Callable[..., Any]:
@@ -2627,3 +2474,880 @@ class NodeCommands:
2627
2474
  return
2628
2475
  except RedisError:
2629
2476
  c.result = sys.exc_info()[1]
2477
+
2478
+
2479
+ class ExecutionStrategy(ABC):
2480
+ @property
2481
+ @abstractmethod
2482
+ def command_queue(self):
2483
+ pass
2484
+
2485
+ @abstractmethod
2486
+ def execute_command(self, *args, **kwargs):
2487
+ """
2488
+ Execution flow for current execution strategy.
2489
+
2490
+ See: ClusterPipeline.execute_command()
2491
+ """
2492
+ pass
2493
+
2494
+ @abstractmethod
2495
+ def annotate_exception(self, exception, number, command):
2496
+ """
2497
+ Annotate exception according to current execution strategy.
2498
+
2499
+ See: ClusterPipeline.annotate_exception()
2500
+ """
2501
+ pass
2502
+
2503
+ @abstractmethod
2504
+ def pipeline_execute_command(self, *args, **options):
2505
+ """
2506
+ Pipeline execution flow for current execution strategy.
2507
+
2508
+ See: ClusterPipeline.pipeline_execute_command()
2509
+ """
2510
+ pass
2511
+
2512
+ @abstractmethod
2513
+ def execute(self, raise_on_error: bool = True) -> List[Any]:
2514
+ """
2515
+ Executes current execution strategy.
2516
+
2517
+ See: ClusterPipeline.execute()
2518
+ """
2519
+ pass
2520
+
2521
+ @abstractmethod
2522
+ def send_cluster_commands(
2523
+ self, stack, raise_on_error=True, allow_redirections=True
2524
+ ):
2525
+ """
2526
+ Sends commands according to current execution strategy.
2527
+
2528
+ See: ClusterPipeline.send_cluster_commands()
2529
+ """
2530
+ pass
2531
+
2532
+ @abstractmethod
2533
+ def reset(self):
2534
+ """
2535
+ Resets current execution strategy.
2536
+
2537
+ See: ClusterPipeline.reset()
2538
+ """
2539
+ pass
2540
+
2541
+ @abstractmethod
2542
+ def exists(self, *keys):
2543
+ pass
2544
+
2545
+ @abstractmethod
2546
+ def eval(self):
2547
+ pass
2548
+
2549
+ @abstractmethod
2550
+ def multi(self):
2551
+ """
2552
+ Starts transactional context.
2553
+
2554
+ See: ClusterPipeline.multi()
2555
+ """
2556
+ pass
2557
+
2558
+ @abstractmethod
2559
+ def load_scripts(self):
2560
+ pass
2561
+
2562
+ @abstractmethod
2563
+ def watch(self, *names):
2564
+ pass
2565
+
2566
+ @abstractmethod
2567
+ def unwatch(self):
2568
+ """
2569
+ Unwatches all previously specified keys
2570
+
2571
+ See: ClusterPipeline.unwatch()
2572
+ """
2573
+ pass
2574
+
2575
+ @abstractmethod
2576
+ def script_load_for_pipeline(self, *args, **kwargs):
2577
+ pass
2578
+
2579
+ @abstractmethod
2580
+ def delete(self, *names):
2581
+ """
2582
+ "Delete a key specified by ``names``"
2583
+
2584
+ See: ClusterPipeline.delete()
2585
+ """
2586
+ pass
2587
+
2588
+ @abstractmethod
2589
+ def unlink(self, *names):
2590
+ """
2591
+ "Unlink a key specified by ``names``"
2592
+
2593
+ See: ClusterPipeline.unlink()
2594
+ """
2595
+ pass
2596
+
2597
+ @abstractmethod
2598
+ def discard(self):
2599
+ pass
2600
+
2601
+
2602
+ class AbstractStrategy(ExecutionStrategy):
2603
+ def __init__(
2604
+ self,
2605
+ pipe: ClusterPipeline,
2606
+ ):
2607
+ self._command_queue: List[PipelineCommand] = []
2608
+ self._pipe = pipe
2609
+ self._nodes_manager = self._pipe.nodes_manager
2610
+
2611
+ @property
2612
+ def command_queue(self):
2613
+ return self._command_queue
2614
+
2615
+ @command_queue.setter
2616
+ def command_queue(self, queue: List[PipelineCommand]):
2617
+ self._command_queue = queue
2618
+
2619
+ @abstractmethod
2620
+ def execute_command(self, *args, **kwargs):
2621
+ pass
2622
+
2623
+ def pipeline_execute_command(self, *args, **options):
2624
+ self._command_queue.append(
2625
+ PipelineCommand(args, options, len(self._command_queue))
2626
+ )
2627
+ return self._pipe
2628
+
2629
+ @abstractmethod
2630
+ def execute(self, raise_on_error: bool = True) -> List[Any]:
2631
+ pass
2632
+
2633
+ @abstractmethod
2634
+ def send_cluster_commands(
2635
+ self, stack, raise_on_error=True, allow_redirections=True
2636
+ ):
2637
+ pass
2638
+
2639
+ @abstractmethod
2640
+ def reset(self):
2641
+ pass
2642
+
2643
+ def exists(self, *keys):
2644
+ return self.execute_command("EXISTS", *keys)
2645
+
2646
+ def eval(self):
2647
+ """ """
2648
+ raise RedisClusterException("method eval() is not implemented")
2649
+
2650
+ def load_scripts(self):
2651
+ """ """
2652
+ raise RedisClusterException("method load_scripts() is not implemented")
2653
+
2654
+ def script_load_for_pipeline(self, *args, **kwargs):
2655
+ """ """
2656
+ raise RedisClusterException(
2657
+ "method script_load_for_pipeline() is not implemented"
2658
+ )
2659
+
2660
+ def annotate_exception(self, exception, number, command):
2661
+ """
2662
+ Provides extra context to the exception prior to it being handled
2663
+ """
2664
+ cmd = " ".join(map(safe_str, command))
2665
+ msg = (
2666
+ f"Command # {number} ({truncate_text(cmd)}) of pipeline "
2667
+ f"caused error: {exception.args[0]}"
2668
+ )
2669
+ exception.args = (msg,) + exception.args[1:]
2670
+
2671
+
2672
+ class PipelineStrategy(AbstractStrategy):
2673
+ def __init__(self, pipe: ClusterPipeline):
2674
+ super().__init__(pipe)
2675
+ self.command_flags = pipe.command_flags
2676
+
2677
+ def execute_command(self, *args, **kwargs):
2678
+ return self.pipeline_execute_command(*args, **kwargs)
2679
+
2680
+ def _raise_first_error(self, stack):
2681
+ """
2682
+ Raise the first exception on the stack
2683
+ """
2684
+ for c in stack:
2685
+ r = c.result
2686
+ if isinstance(r, Exception):
2687
+ self.annotate_exception(r, c.position + 1, c.args)
2688
+ raise r
2689
+
2690
+ def execute(self, raise_on_error: bool = True) -> List[Any]:
2691
+ stack = self._command_queue
2692
+ if not stack:
2693
+ return []
2694
+
2695
+ try:
2696
+ return self.send_cluster_commands(stack, raise_on_error)
2697
+ finally:
2698
+ self.reset()
2699
+
2700
+ def reset(self):
2701
+ """
2702
+ Reset back to empty pipeline.
2703
+ """
2704
+ self._command_queue = []
2705
+
2706
+ def send_cluster_commands(
2707
+ self, stack, raise_on_error=True, allow_redirections=True
2708
+ ):
2709
+ """
2710
+ Wrapper for RedisCluster.ERRORS_ALLOW_RETRY errors handling.
2711
+
2712
+ If one of the retryable exceptions has been thrown we assume that:
2713
+ - connection_pool was disconnected
2714
+ - connection_pool was reseted
2715
+ - refereh_table_asap set to True
2716
+
2717
+ It will try the number of times specified by
2718
+ the retries in config option "self.retry"
2719
+ which defaults to 3 unless manually configured.
2720
+
2721
+ If it reaches the number of times, the command will
2722
+ raises ClusterDownException.
2723
+ """
2724
+ if not stack:
2725
+ return []
2726
+ retry_attempts = self._pipe.retry.get_retries()
2727
+ while True:
2728
+ try:
2729
+ return self._send_cluster_commands(
2730
+ stack,
2731
+ raise_on_error=raise_on_error,
2732
+ allow_redirections=allow_redirections,
2733
+ )
2734
+ except RedisCluster.ERRORS_ALLOW_RETRY as e:
2735
+ if retry_attempts > 0:
2736
+ # Try again with the new cluster setup. All other errors
2737
+ # should be raised.
2738
+ retry_attempts -= 1
2739
+ pass
2740
+ else:
2741
+ raise e
2742
+
2743
+ def _send_cluster_commands(
2744
+ self, stack, raise_on_error=True, allow_redirections=True
2745
+ ):
2746
+ """
2747
+ Send a bunch of cluster commands to the redis cluster.
2748
+
2749
+ `allow_redirections` If the pipeline should follow
2750
+ `ASK` & `MOVED` responses automatically. If set
2751
+ to false it will raise RedisClusterException.
2752
+ """
2753
+ # the first time sending the commands we send all of
2754
+ # the commands that were queued up.
2755
+ # if we have to run through it again, we only retry
2756
+ # the commands that failed.
2757
+ attempt = sorted(stack, key=lambda x: x.position)
2758
+ is_default_node = False
2759
+ # build a list of node objects based on node names we need to
2760
+ nodes = {}
2761
+
2762
+ # as we move through each command that still needs to be processed,
2763
+ # we figure out the slot number that command maps to, then from
2764
+ # the slot determine the node.
2765
+ for c in attempt:
2766
+ while True:
2767
+ # refer to our internal node -> slot table that
2768
+ # tells us where a given command should route to.
2769
+ # (it might be possible we have a cached node that no longer
2770
+ # exists in the cluster, which is why we do this in a loop)
2771
+ passed_targets = c.options.pop("target_nodes", None)
2772
+ if passed_targets and not self._is_nodes_flag(passed_targets):
2773
+ target_nodes = self._parse_target_nodes(passed_targets)
2774
+ else:
2775
+ target_nodes = self._determine_nodes(
2776
+ *c.args, node_flag=passed_targets
2777
+ )
2778
+ if not target_nodes:
2779
+ raise RedisClusterException(
2780
+ f"No targets were found to execute {c.args} command on"
2781
+ )
2782
+ if len(target_nodes) > 1:
2783
+ raise RedisClusterException(
2784
+ f"Too many targets for command {c.args}"
2785
+ )
2786
+
2787
+ node = target_nodes[0]
2788
+ if node == self._pipe.get_default_node():
2789
+ is_default_node = True
2790
+
2791
+ # now that we know the name of the node
2792
+ # ( it's just a string in the form of host:port )
2793
+ # we can build a list of commands for each node.
2794
+ node_name = node.name
2795
+ if node_name not in nodes:
2796
+ redis_node = self._pipe.get_redis_connection(node)
2797
+ try:
2798
+ connection = get_connection(redis_node)
2799
+ except (ConnectionError, TimeoutError):
2800
+ for n in nodes.values():
2801
+ n.connection_pool.release(n.connection)
2802
+ # Connection retries are being handled in the node's
2803
+ # Retry object. Reinitialize the node -> slot table.
2804
+ self._nodes_manager.initialize()
2805
+ if is_default_node:
2806
+ self._pipe.replace_default_node()
2807
+ raise
2808
+ nodes[node_name] = NodeCommands(
2809
+ redis_node.parse_response,
2810
+ redis_node.connection_pool,
2811
+ connection,
2812
+ )
2813
+ nodes[node_name].append(c)
2814
+ break
2815
+
2816
+ # send the commands in sequence.
2817
+ # we write to all the open sockets for each node first,
2818
+ # before reading anything
2819
+ # this allows us to flush all the requests out across the
2820
+ # network
2821
+ # so that we can read them from different sockets as they come back.
2822
+ # we dont' multiplex on the sockets as they come available,
2823
+ # but that shouldn't make too much difference.
2824
+ try:
2825
+ node_commands = nodes.values()
2826
+ for n in node_commands:
2827
+ n.write()
2828
+
2829
+ for n in node_commands:
2830
+ n.read()
2831
+ finally:
2832
+ # release all of the redis connections we allocated earlier
2833
+ # back into the connection pool.
2834
+ # we used to do this step as part of a try/finally block,
2835
+ # but it is really dangerous to
2836
+ # release connections back into the pool if for some
2837
+ # reason the socket has data still left in it
2838
+ # from a previous operation. The write and
2839
+ # read operations already have try/catch around them for
2840
+ # all known types of errors including connection
2841
+ # and socket level errors.
2842
+ # So if we hit an exception, something really bad
2843
+ # happened and putting any oF
2844
+ # these connections back into the pool is a very bad idea.
2845
+ # the socket might have unread buffer still sitting in it,
2846
+ # and then the next time we read from it we pass the
2847
+ # buffered result back from a previous command and
2848
+ # every single request after to that connection will always get
2849
+ # a mismatched result.
2850
+ for n in nodes.values():
2851
+ n.connection_pool.release(n.connection)
2852
+
2853
+ # if the response isn't an exception it is a
2854
+ # valid response from the node
2855
+ # we're all done with that command, YAY!
2856
+ # if we have more commands to attempt, we've run into problems.
2857
+ # collect all the commands we are allowed to retry.
2858
+ # (MOVED, ASK, or connection errors or timeout errors)
2859
+ attempt = sorted(
2860
+ (
2861
+ c
2862
+ for c in attempt
2863
+ if isinstance(c.result, ClusterPipeline.ERRORS_ALLOW_RETRY)
2864
+ ),
2865
+ key=lambda x: x.position,
2866
+ )
2867
+ if attempt and allow_redirections:
2868
+ # RETRY MAGIC HAPPENS HERE!
2869
+ # send these remaining commands one at a time using `execute_command`
2870
+ # in the main client. This keeps our retry logic
2871
+ # in one place mostly,
2872
+ # and allows us to be more confident in correctness of behavior.
2873
+ # at this point any speed gains from pipelining have been lost
2874
+ # anyway, so we might as well make the best
2875
+ # attempt to get the correct behavior.
2876
+ #
2877
+ # The client command will handle retries for each
2878
+ # individual command sequentially as we pass each
2879
+ # one into `execute_command`. Any exceptions
2880
+ # that bubble out should only appear once all
2881
+ # retries have been exhausted.
2882
+ #
2883
+ # If a lot of commands have failed, we'll be setting the
2884
+ # flag to rebuild the slots table from scratch.
2885
+ # So MOVED errors should correct themselves fairly quickly.
2886
+ self._pipe.reinitialize_counter += 1
2887
+ if self._pipe._should_reinitialized():
2888
+ self._nodes_manager.initialize()
2889
+ if is_default_node:
2890
+ self._pipe.replace_default_node()
2891
+ for c in attempt:
2892
+ try:
2893
+ # send each command individually like we
2894
+ # do in the main client.
2895
+ c.result = self._pipe.parent_execute_command(*c.args, **c.options)
2896
+ except RedisError as e:
2897
+ c.result = e
2898
+
2899
+ # turn the response back into a simple flat array that corresponds
2900
+ # to the sequence of commands issued in the stack in pipeline.execute()
2901
+ response = []
2902
+ for c in sorted(stack, key=lambda x: x.position):
2903
+ if c.args[0] in self._pipe.cluster_response_callbacks:
2904
+ # Remove keys entry, it needs only for cache.
2905
+ c.options.pop("keys", None)
2906
+ c.result = self._pipe.cluster_response_callbacks[c.args[0]](
2907
+ c.result, **c.options
2908
+ )
2909
+ response.append(c.result)
2910
+
2911
+ if raise_on_error:
2912
+ self._raise_first_error(stack)
2913
+
2914
+ return response
2915
+
2916
+ def _is_nodes_flag(self, target_nodes):
2917
+ return isinstance(target_nodes, str) and target_nodes in self._pipe.node_flags
2918
+
2919
+ def _parse_target_nodes(self, target_nodes):
2920
+ if isinstance(target_nodes, list):
2921
+ nodes = target_nodes
2922
+ elif isinstance(target_nodes, ClusterNode):
2923
+ # Supports passing a single ClusterNode as a variable
2924
+ nodes = [target_nodes]
2925
+ elif isinstance(target_nodes, dict):
2926
+ # Supports dictionaries of the format {node_name: node}.
2927
+ # It enables to execute commands with multi nodes as follows:
2928
+ # rc.cluster_save_config(rc.get_primaries())
2929
+ nodes = target_nodes.values()
2930
+ else:
2931
+ raise TypeError(
2932
+ "target_nodes type can be one of the following: "
2933
+ "node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
2934
+ "ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. "
2935
+ f"The passed type is {type(target_nodes)}"
2936
+ )
2937
+ return nodes
2938
+
2939
+ def _determine_nodes(self, *args, **kwargs) -> List["ClusterNode"]:
2940
+ # Determine which nodes should be executed the command on.
2941
+ # Returns a list of target nodes.
2942
+ command = args[0].upper()
2943
+ if (
2944
+ len(args) >= 2
2945
+ and f"{args[0]} {args[1]}".upper() in self._pipe.command_flags
2946
+ ):
2947
+ command = f"{args[0]} {args[1]}".upper()
2948
+
2949
+ nodes_flag = kwargs.pop("nodes_flag", None)
2950
+ if nodes_flag is not None:
2951
+ # nodes flag passed by the user
2952
+ command_flag = nodes_flag
2953
+ else:
2954
+ # get the nodes group for this command if it was predefined
2955
+ command_flag = self._pipe.command_flags.get(command)
2956
+ if command_flag == self._pipe.RANDOM:
2957
+ # return a random node
2958
+ return [self._pipe.get_random_node()]
2959
+ elif command_flag == self._pipe.PRIMARIES:
2960
+ # return all primaries
2961
+ return self._pipe.get_primaries()
2962
+ elif command_flag == self._pipe.REPLICAS:
2963
+ # return all replicas
2964
+ return self._pipe.get_replicas()
2965
+ elif command_flag == self._pipe.ALL_NODES:
2966
+ # return all nodes
2967
+ return self._pipe.get_nodes()
2968
+ elif command_flag == self._pipe.DEFAULT_NODE:
2969
+ # return the cluster's default node
2970
+ return [self._nodes_manager.default_node]
2971
+ elif command in self._pipe.SEARCH_COMMANDS[0]:
2972
+ return [self._nodes_manager.default_node]
2973
+ else:
2974
+ # get the node that holds the key's slot
2975
+ slot = self._pipe.determine_slot(*args)
2976
+ node = self._nodes_manager.get_node_from_slot(
2977
+ slot,
2978
+ self._pipe.read_from_replicas and command in READ_COMMANDS,
2979
+ self._pipe.load_balancing_strategy
2980
+ if command in READ_COMMANDS
2981
+ else None,
2982
+ )
2983
+ return [node]
2984
+
2985
+ def multi(self):
2986
+ raise RedisClusterException(
2987
+ "method multi() is not supported outside of transactional context"
2988
+ )
2989
+
2990
+ def discard(self):
2991
+ raise RedisClusterException(
2992
+ "method discard() is not supported outside of transactional context"
2993
+ )
2994
+
2995
+ def watch(self, *names):
2996
+ raise RedisClusterException(
2997
+ "method watch() is not supported outside of transactional context"
2998
+ )
2999
+
3000
+ def unwatch(self, *names):
3001
+ raise RedisClusterException(
3002
+ "method unwatch() is not supported outside of transactional context"
3003
+ )
3004
+
3005
+ def delete(self, *names):
3006
+ if len(names) != 1:
3007
+ raise RedisClusterException(
3008
+ "deleting multiple keys is not implemented in pipeline command"
3009
+ )
3010
+
3011
+ return self.execute_command("DEL", names[0])
3012
+
3013
+ def unlink(self, *names):
3014
+ if len(names) != 1:
3015
+ raise RedisClusterException(
3016
+ "unlinking multiple keys is not implemented in pipeline command"
3017
+ )
3018
+
3019
+ return self.execute_command("UNLINK", names[0])
3020
+
3021
+
3022
+ class TransactionStrategy(AbstractStrategy):
3023
+ NO_SLOTS_COMMANDS = {"UNWATCH"}
3024
+ IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
3025
+ UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
3026
+ SLOT_REDIRECT_ERRORS = (AskError, MovedError)
3027
+ CONNECTION_ERRORS = (
3028
+ ConnectionError,
3029
+ OSError,
3030
+ ClusterDownError,
3031
+ SlotNotCoveredError,
3032
+ )
3033
+
3034
+ def __init__(self, pipe: ClusterPipeline):
3035
+ super().__init__(pipe)
3036
+ self._explicit_transaction = False
3037
+ self._watching = False
3038
+ self._pipeline_slots: Set[int] = set()
3039
+ self._transaction_connection: Optional[Connection] = None
3040
+ self._executing = False
3041
+ self._retry = copy(self._pipe.retry)
3042
+ self._retry.update_supported_errors(
3043
+ RedisCluster.ERRORS_ALLOW_RETRY + self.SLOT_REDIRECT_ERRORS
3044
+ )
3045
+
3046
+ def _get_client_and_connection_for_transaction(self) -> Tuple[Redis, Connection]:
3047
+ """
3048
+ Find a connection for a pipeline transaction.
3049
+
3050
+ For running an atomic transaction, watch keys ensure that contents have not been
3051
+ altered as long as the watch commands for those keys were sent over the same
3052
+ connection. So once we start watching a key, we fetch a connection to the
3053
+ node that owns that slot and reuse it.
3054
+ """
3055
+ if not self._pipeline_slots:
3056
+ raise RedisClusterException(
3057
+ "At least a command with a key is needed to identify a node"
3058
+ )
3059
+
3060
+ node: ClusterNode = self._nodes_manager.get_node_from_slot(
3061
+ list(self._pipeline_slots)[0], False
3062
+ )
3063
+ redis_node: Redis = self._pipe.get_redis_connection(node)
3064
+ if self._transaction_connection:
3065
+ if not redis_node.connection_pool.owns_connection(
3066
+ self._transaction_connection
3067
+ ):
3068
+ previous_node = self._nodes_manager.find_connection_owner(
3069
+ self._transaction_connection
3070
+ )
3071
+ previous_node.connection_pool.release(self._transaction_connection)
3072
+ self._transaction_connection = None
3073
+
3074
+ if not self._transaction_connection:
3075
+ self._transaction_connection = get_connection(redis_node)
3076
+
3077
+ return redis_node, self._transaction_connection
3078
+
3079
+ def execute_command(self, *args, **kwargs):
3080
+ slot_number: Optional[int] = None
3081
+ if args[0] not in ClusterPipeline.NO_SLOTS_COMMANDS:
3082
+ slot_number = self._pipe.determine_slot(*args)
3083
+
3084
+ if (
3085
+ self._watching or args[0] in self.IMMEDIATE_EXECUTE_COMMANDS
3086
+ ) and not self._explicit_transaction:
3087
+ if args[0] == "WATCH":
3088
+ self._validate_watch()
3089
+
3090
+ if slot_number is not None:
3091
+ if self._pipeline_slots and slot_number not in self._pipeline_slots:
3092
+ raise CrossSlotTransactionError(
3093
+ "Cannot watch or send commands on different slots"
3094
+ )
3095
+
3096
+ self._pipeline_slots.add(slot_number)
3097
+ elif args[0] not in self.NO_SLOTS_COMMANDS:
3098
+ raise RedisClusterException(
3099
+ f"Cannot identify slot number for command: {args[0]},"
3100
+ "it cannot be triggered in a transaction"
3101
+ )
3102
+
3103
+ return self._immediate_execute_command(*args, **kwargs)
3104
+ else:
3105
+ if slot_number is not None:
3106
+ self._pipeline_slots.add(slot_number)
3107
+
3108
+ return self.pipeline_execute_command(*args, **kwargs)
3109
+
3110
+ def _validate_watch(self):
3111
+ if self._explicit_transaction:
3112
+ raise RedisError("Cannot issue a WATCH after a MULTI")
3113
+
3114
+ self._watching = True
3115
+
3116
+ def _immediate_execute_command(self, *args, **options):
3117
+ return self._retry.call_with_retry(
3118
+ lambda: self._get_connection_and_send_command(*args, **options),
3119
+ self._reinitialize_on_error,
3120
+ )
3121
+
3122
+ def _get_connection_and_send_command(self, *args, **options):
3123
+ redis_node, connection = self._get_client_and_connection_for_transaction()
3124
+ return self._send_command_parse_response(
3125
+ connection, redis_node, args[0], *args, **options
3126
+ )
3127
+
3128
+ def _send_command_parse_response(
3129
+ self, conn, redis_node: Redis, command_name, *args, **options
3130
+ ):
3131
+ """
3132
+ Send a command and parse the response
3133
+ """
3134
+
3135
+ conn.send_command(*args)
3136
+ output = redis_node.parse_response(conn, command_name, **options)
3137
+
3138
+ if command_name in self.UNWATCH_COMMANDS:
3139
+ self._watching = False
3140
+ return output
3141
+
3142
+ def _reinitialize_on_error(self, error):
3143
+ if self._watching:
3144
+ if type(error) in self.SLOT_REDIRECT_ERRORS and self._executing:
3145
+ raise WatchError("Slot rebalancing occurred while watching keys")
3146
+
3147
+ if (
3148
+ type(error) in self.SLOT_REDIRECT_ERRORS
3149
+ or type(error) in self.CONNECTION_ERRORS
3150
+ ):
3151
+ if self._transaction_connection:
3152
+ self._transaction_connection = None
3153
+
3154
+ self._pipe.reinitialize_counter += 1
3155
+ if self._pipe._should_reinitialized():
3156
+ self._nodes_manager.initialize()
3157
+ self.reinitialize_counter = 0
3158
+ else:
3159
+ self._nodes_manager.update_moved_exception(error)
3160
+
3161
+ self._executing = False
3162
+
3163
+ def _raise_first_error(self, responses, stack):
3164
+ """
3165
+ Raise the first exception on the stack
3166
+ """
3167
+ for r, cmd in zip(responses, stack):
3168
+ if isinstance(r, Exception):
3169
+ self.annotate_exception(r, cmd.position + 1, cmd.args)
3170
+ raise r
3171
+
3172
+ def execute(self, raise_on_error: bool = True) -> List[Any]:
3173
+ stack = self._command_queue
3174
+ if not stack and (not self._watching or not self._pipeline_slots):
3175
+ return []
3176
+
3177
+ return self._execute_transaction_with_retries(stack, raise_on_error)
3178
+
3179
+ def _execute_transaction_with_retries(
3180
+ self, stack: List["PipelineCommand"], raise_on_error: bool
3181
+ ):
3182
+ return self._retry.call_with_retry(
3183
+ lambda: self._execute_transaction(stack, raise_on_error),
3184
+ self._reinitialize_on_error,
3185
+ )
3186
+
3187
+ def _execute_transaction(
3188
+ self, stack: List["PipelineCommand"], raise_on_error: bool
3189
+ ):
3190
+ if len(self._pipeline_slots) > 1:
3191
+ raise CrossSlotTransactionError(
3192
+ "All keys involved in a cluster transaction must map to the same slot"
3193
+ )
3194
+
3195
+ self._executing = True
3196
+
3197
+ redis_node, connection = self._get_client_and_connection_for_transaction()
3198
+
3199
+ stack = chain(
3200
+ [PipelineCommand(("MULTI",))],
3201
+ stack,
3202
+ [PipelineCommand(("EXEC",))],
3203
+ )
3204
+ commands = [c.args for c in stack if EMPTY_RESPONSE not in c.options]
3205
+ packed_commands = connection.pack_commands(commands)
3206
+ connection.send_packed_command(packed_commands)
3207
+ errors = []
3208
+
3209
+ # parse off the response for MULTI
3210
+ # NOTE: we need to handle ResponseErrors here and continue
3211
+ # so that we read all the additional command messages from
3212
+ # the socket
3213
+ try:
3214
+ redis_node.parse_response(connection, "MULTI")
3215
+ except ResponseError as e:
3216
+ self.annotate_exception(e, 0, "MULTI")
3217
+ errors.append(e)
3218
+ except self.CONNECTION_ERRORS as cluster_error:
3219
+ self.annotate_exception(cluster_error, 0, "MULTI")
3220
+ raise
3221
+
3222
+ # and all the other commands
3223
+ for i, command in enumerate(self._command_queue):
3224
+ if EMPTY_RESPONSE in command.options:
3225
+ errors.append((i, command.options[EMPTY_RESPONSE]))
3226
+ else:
3227
+ try:
3228
+ _ = redis_node.parse_response(connection, "_")
3229
+ except self.SLOT_REDIRECT_ERRORS as slot_error:
3230
+ self.annotate_exception(slot_error, i + 1, command.args)
3231
+ errors.append(slot_error)
3232
+ except self.CONNECTION_ERRORS as cluster_error:
3233
+ self.annotate_exception(cluster_error, i + 1, command.args)
3234
+ raise
3235
+ except ResponseError as e:
3236
+ self.annotate_exception(e, i + 1, command.args)
3237
+ errors.append(e)
3238
+
3239
+ response = None
3240
+ # parse the EXEC.
3241
+ try:
3242
+ response = redis_node.parse_response(connection, "EXEC")
3243
+ except ExecAbortError:
3244
+ if errors:
3245
+ raise errors[0]
3246
+ raise
3247
+
3248
+ self._executing = False
3249
+
3250
+ # EXEC clears any watched keys
3251
+ self._watching = False
3252
+
3253
+ if response is None:
3254
+ raise WatchError("Watched variable changed.")
3255
+
3256
+ # put any parse errors into the response
3257
+ for i, e in errors:
3258
+ response.insert(i, e)
3259
+
3260
+ if len(response) != len(self._command_queue):
3261
+ raise InvalidPipelineStack(
3262
+ "Unexpected response length for cluster pipeline EXEC."
3263
+ " Command stack was {} but response had length {}".format(
3264
+ [c.args[0] for c in self._command_queue], len(response)
3265
+ )
3266
+ )
3267
+
3268
+ # find any errors in the response and raise if necessary
3269
+ if raise_on_error or len(errors) > 0:
3270
+ self._raise_first_error(
3271
+ response,
3272
+ self._command_queue,
3273
+ )
3274
+
3275
+ # We have to run response callbacks manually
3276
+ data = []
3277
+ for r, cmd in zip(response, self._command_queue):
3278
+ if not isinstance(r, Exception):
3279
+ command_name = cmd.args[0]
3280
+ if command_name in self._pipe.cluster_response_callbacks:
3281
+ r = self._pipe.cluster_response_callbacks[command_name](
3282
+ r, **cmd.options
3283
+ )
3284
+ data.append(r)
3285
+ return data
3286
+
3287
+ def reset(self):
3288
+ self._command_queue = []
3289
+
3290
+ # make sure to reset the connection state in the event that we were
3291
+ # watching something
3292
+ if self._transaction_connection:
3293
+ try:
3294
+ # call this manually since our unwatch or
3295
+ # immediate_execute_command methods can call reset()
3296
+ self._transaction_connection.send_command("UNWATCH")
3297
+ self._transaction_connection.read_response()
3298
+ # we can safely return the connection to the pool here since we're
3299
+ # sure we're no longer WATCHing anything
3300
+ node = self._nodes_manager.find_connection_owner(
3301
+ self._transaction_connection
3302
+ )
3303
+ node.redis_connection.connection_pool.release(
3304
+ self._transaction_connection
3305
+ )
3306
+ self._transaction_connection = None
3307
+ except self.CONNECTION_ERRORS:
3308
+ # disconnect will also remove any previous WATCHes
3309
+ if self._transaction_connection:
3310
+ self._transaction_connection.disconnect()
3311
+
3312
+ # clean up the other instance attributes
3313
+ self._watching = False
3314
+ self._explicit_transaction = False
3315
+ self._pipeline_slots = set()
3316
+ self._executing = False
3317
+
3318
+ def send_cluster_commands(
3319
+ self, stack, raise_on_error=True, allow_redirections=True
3320
+ ):
3321
+ raise NotImplementedError(
3322
+ "send_cluster_commands cannot be executed in transactional context."
3323
+ )
3324
+
3325
+ def multi(self):
3326
+ if self._explicit_transaction:
3327
+ raise RedisError("Cannot issue nested calls to MULTI")
3328
+ if self._command_queue:
3329
+ raise RedisError(
3330
+ "Commands without an initial WATCH have already been issued"
3331
+ )
3332
+ self._explicit_transaction = True
3333
+
3334
+ def watch(self, *names):
3335
+ if self._explicit_transaction:
3336
+ raise RedisError("Cannot issue a WATCH after a MULTI")
3337
+
3338
+ return self.execute_command("WATCH", *names)
3339
+
3340
+ def unwatch(self):
3341
+ if self._watching:
3342
+ return self.execute_command("UNWATCH")
3343
+
3344
+ return True
3345
+
3346
+ def discard(self):
3347
+ self.reset()
3348
+
3349
+ def delete(self, *names):
3350
+ return self.execute_command("DEL", *names)
3351
+
3352
+ def unlink(self, *names):
3353
+ return self.execute_command("UNLINK", *names)