Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/asyncio/cluster.py: 15%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

2436 statements  

1import asyncio 

2import collections 

3import logging 

4import math 

5import random 

6import threading 

7import time 

8import warnings 

9import weakref 

10from abc import ABC, abstractmethod 

11from collections import defaultdict 

12from contextlib import asynccontextmanager, nullcontext 

13from copy import copy 

14from itertools import chain 

15from types import MethodType 

16from typing import ( 

17 TYPE_CHECKING, 

18 Any, 

19 AsyncGenerator, 

20 Callable, 

21 Coroutine, 

22 Deque, 

23 Dict, 

24 Generator, 

25 Iterable, 

26 Iterator, 

27 List, 

28 Literal, 

29 Mapping, 

30 Optional, 

31 Set, 

32 Tuple, 

33 Type, 

34 TypeVar, 

35 Union, 

36) 

37 

38if TYPE_CHECKING: 

39 from redis.asyncio.keyspace_notifications import ( 

40 AsyncClusterKeyspaceNotifications, 

41 ) 

42 

43from redis._defaults import ( 

44 DEFAULT_RETRY_BASE, 

45 DEFAULT_RETRY_CAP, 

46 DEFAULT_RETRY_COUNT, 

47 DEFAULT_SOCKET_CONNECT_TIMEOUT, 

48 DEFAULT_SOCKET_READ_SIZE, 

49 DEFAULT_SOCKET_TIMEOUT, 

50) 

51from redis._parsers import AsyncCommandsParser, Encoder 

52from redis._parsers.helpers import decode_info, get_response_callbacks 

53from redis._parsers.response_callbacks import _get_response_callback 

54from redis.asyncio import _himport_exec 

55from redis.asyncio.client import ( 

56 _PIPELINE_YIELD_MIN_COMMANDS, 

57 PubSub, 

58 ResponseCallbackT, 

59 _pack_pipeline_commands, 

60 _yield_in_read_loop, 

61) 

62from redis.asyncio.connection import ( 

63 AbstractConnection, 

64 Connection, 

65 ConnectionPoolInterface, 

66 SSLConnection, 

67 parse_url, 

68) 

69from redis.asyncio.lock import Lock 

70from redis.asyncio.maint_notifications import AsyncOSSMaintNotificationsHandler 

71from redis.asyncio.observability.recorder import ( 

72 record_error_count, 

73 record_operation_duration, 

74) 

75from redis.asyncio.retry import Retry, _to_async_retry 

76from redis.auth.token import TokenInterface 

77from redis.backoff import ExponentialWithJitterBackoff, NoBackoff 

78from redis.client import EMPTY_RESPONSE, NEVER_DECODE, AbstractRedis 

79from redis.cluster import ( 

80 _EVAL_COMMANDS, 

81 _REPLICAS_ONLY_STRATEGIES, 

82 _RESPONSE_POLICY_CALLBACKS, 

83 _SPECIAL_RESPONSE_CALLBACKS, 

84 _UNANSWERED, 

85 PIPELINE_BLOCKED_COMMANDS, 

86 PRIMARY, 

87 REPLICA, 

88 SLOT_ID, 

89 AbstractRedisCluster, 

90 LoadBalancer, 

91 LoadBalancingStrategy, 

92 _error_to_raise, 

93 _fill_missing_redirect_host, 

94 _is_demoted_primary, 

95 _keep_target_replies, 

96 _merge_multi_shard_replies, 

97 _MultiShardSplit, 

98 _record_replies, 

99 _resolve_localhost, 

100 _should_request_refresh, 

101 _split_by_slot, 

102 _split_successes_and_failure, 

103 _topology_refresh_delay, 

104 _with_keys, 

105 block_pipeline_command, 

106 get_node_name, 

107 is_zero_key_eval_command, 

108 parse_cluster_shards, 

109 parse_cluster_shards_unified, 

110 parse_cluster_shards_with_str_keys, 

111 parse_cluster_slots, 

112) 

113from redis.commands import AsyncRedisClusterCommands 

114from redis.commands.helpers import list_or_args, parse_pubsub_subscriptions 

115from redis.commands.metadata import ( 

116 _DEFAULT_KEYED_METADATA, 

117 _DEFAULT_KEYLESS_METADATA, 

118 _METADATA_BY_REQUEST_POLICY, 

119 AsyncMetadataResolver, 

120 AsyncStaticMetadataResolver, 

121 CommandMetadata, 

122 CommandPolicies, 

123 RequestPolicy, 

124 ResponsePolicy, 

125) 

126from redis.commands.policies import AsyncPolicyResolver, AsyncStaticPolicyResolver 

127from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot 

128from redis.credentials import CredentialProvider 

129from redis.driver_info import DriverInfo, resolve_driver_info 

130from redis.event import ( 

131 AfterAsyncClusterInstantiationEvent, 

132 AsyncAfterSlotsCacheRefreshEvent, 

133 AsyncEventListenerInterface, 

134 EventDispatcher, 

135 _log_re_auth_failure, 

136) 

137from redis.exceptions import ( 

138 AskError, 

139 AuthenticationError, 

140 AuthorizationError, 

141 BusyLoadingError, 

142 ClusterDownError, 

143 ClusterError, 

144 ConnectionError, 

145 CrossSlotTransactionError, 

146 DataError, 

147 ExecAbortError, 

148 InvalidPipelineStack, 

149 MaxClientsReachedError, 

150 MaxConnectionsError, 

151 MovedError, 

152 ReadOnlyError, 

153 RedisClusterException, 

154 RedisClusterUnreachableError, 

155 RedisError, 

156 ResponseError, 

157 SlotNotCoveredError, 

158 TimeoutError, 

159 TryAgainError, 

160 WatchError, 

161) 

162from redis.himport import HImportRegistry, parse_himport_set_args 

163from redis.maint_notifications import MaintNotificationsConfig 

164from redis.typing import ( 

165 AnyKeyT, 

166 ChannelT, 

167 EncodableT, 

168 FieldT, 

169 KeyT, 

170 PubSubHandler, 

171 Subscription, 

172) 

173from redis.utils import ( 

174 SENTINEL, 

175 SSL_AVAILABLE, 

176 check_protocol_version, 

177 command_text, 

178 deprecated_args, 

179 deprecated_function, 

180 experimental_method, 

181 safe_str, 

182 str_if_bytes, 

183 truncate_text, 

184) 

185 

186if SSL_AVAILABLE: 

187 from ssl import TLSVersion, VerifyFlags, VerifyMode 

188else: 

189 TLSVersion = None 

190 VerifyMode = None 

191 VerifyFlags = None 

192 

193logger = logging.getLogger(__name__) 

194 

195TargetNodesT = TypeVar( 

196 "TargetNodesT", str, "ClusterNode", List["ClusterNode"], Dict[Any, "ClusterNode"] 

197) 

198 

199_T = TypeVar("_T") 

200 

201 

202def _run_coroutine_in_thread(coro: Coroutine[Any, Any, _T]) -> _T: 

203 """ 

204 Runs ``coro`` to completion on a private event loop in a worker thread. 

205 

206 The bridge for the places where a synchronous entry point has to drive an awaitable 

207 body. The caller may already be running an event loop, which rules out both awaiting 

208 the coroutine and running it here with ``asyncio.run``, so it gets a loop of its own 

209 and the calling thread blocks until it finishes. Whatever the coroutine raised is 

210 re-raised to the caller, so the entry point fails the way it would have had the body 

211 run in place. 

212 

213 .. warning:: 

214 

215 **Deadlock hazard. Pass only a coroutine that touches nothing bound to the 

216 caller's loop.** The ``thread.join()`` below blocks the calling thread for the 

217 whole run, so when that thread is the one running an event loop, the loop stops 

218 making progress for the duration. A body that then awaits anything owned by that 

219 loop - a future, a task, a lock, or I/O over a pooled connection - is waiting on a 

220 loop that is itself blocked on this very ``join()``. The result is a permanent 

221 stall, not an exception: nothing times out and nothing is raised. Loop-bound 

222 futures may instead fail with a cross-loop ``RuntimeError``, which is the luckier 

223 outcome because at least it is visible. 

224 

225 Pass only a body whose awaits are self-contained, and prefer restructuring the entry 

226 point to be ``async`` over reaching for this. 

227 """ 

228 result: Any = None 

229 error: BaseException | None = None 

230 

231 def runner() -> None: 

232 nonlocal result 

233 nonlocal error 

234 try: 

235 result = asyncio.run(coro) 

236 except BaseException as e: 

237 error = e 

238 

239 thread = threading.Thread(target=runner) 

240 thread.start() 

241 # Unconditional and untimed by design: the caller expects a value, so there is no 

242 # partial result to return early with. If the caller's thread is running an event 

243 # loop, that loop is blocked here, which is why the coroutine must never await 

244 # anything owned by it. See the deadlock hazard in the docstring above. 

245 thread.join() 

246 

247 if error is not None: 

248 raise error 

249 

250 return result 

251 

252 

253# How the nodes a command is sent to are picked, by the command's request policy. Each 

254# callback is handed the cluster client, the command name and the remaining arguments, and is 

255# a coroutine so that every policy is awaited alike: resolving a keyless target is a 

256# coroutine here. The keyed policies map to None: ``RedisCluster._determine_nodes`` awaits 

257# ``get_nodes_from_slot`` for them directly, as the hottest path, without a wrapper 

258# coroutine of their own. 

259async def _keyless_target_nodes(cluster, command, *args): 

260 return [await cluster.get_keyless_target_node(command)] 

261 

262 

263async def _default_target_nodes(cluster, command, *args): 

264 return [cluster.get_default_node()] 

265 

266 

267async def _primary_target_nodes(cluster, command, *args): 

268 return cluster.get_primaries() 

269 

270 

271async def _all_target_nodes(cluster, command, *args): 

272 return cluster.get_nodes() 

273 

274 

275async def _replica_target_nodes(cluster, command, *args): 

276 return cluster.get_replicas() 

277 

278 

279async def _special_target_nodes(cluster, command, *args): 

280 return cluster.get_special_nodes() 

281 

282 

283_REQUEST_POLICY_CALLBACKS: Dict[ 

284 RequestPolicy, Optional[Callable[..., Coroutine[Any, Any, List["ClusterNode"]]]] 

285] = { 

286 RequestPolicy.DEFAULT_KEYLESS: _keyless_target_nodes, 

287 RequestPolicy.DEFAULT_KEYED: None, 

288 RequestPolicy.MULTI_SHARD: None, 

289 RequestPolicy.DEFAULT_NODE: _default_target_nodes, 

290 RequestPolicy.ALL_SHARDS: _primary_target_nodes, 

291 RequestPolicy.ALL_NODES: _all_target_nodes, 

292 RequestPolicy.ALL_REPLICAS: _replica_target_nodes, 

293 RequestPolicy.SPECIAL: _special_target_nodes, 

294} 

295 

296 

297class AsyncMaintNotificationsAbstractRedisCluster: 

298 """ 

299 Mixin for async cluster maintenance notifications handling. 

300 

301 Intended to be used with multiple inheritance alongside RedisCluster. 

302 All logic related to cluster-level maintenance notifications is encapsulated here. 

303 """ 

304 

305 def __init__( 

306 self, 

307 maint_notifications_config: MaintNotificationsConfig | None, 

308 **kwargs, 

309 ) -> None: 

310 # The RESP3 requirement is validated in RedisCluster.__init__ before the 

311 # NodesManager is constructed; this mixin is only ever run from there, so 

312 # the config it receives has already been validated. 

313 is_protocol_supported = check_protocol_version(kwargs.get("protocol"), 3) 

314 

315 if maint_notifications_config is None and is_protocol_supported: 

316 maint_notifications_config = MaintNotificationsConfig() 

317 

318 self.maint_notifications_config = maint_notifications_config 

319 

320 if self.maint_notifications_config and self.maint_notifications_config.enabled: 

321 self._oss_cluster_maint_notifications_handler = ( 

322 AsyncOSSMaintNotificationsHandler(self, self.maint_notifications_config) 

323 ) 

324 self._update_connection_kwargs_for_maint_notifications( 

325 self._oss_cluster_maint_notifications_handler 

326 ) 

327 # Connections are created lazily via ClusterNode.acquire_connection() 

328 # during nodes_manager.initialize() (which runs after __init__), so 

329 # injecting into the shared connection_kwargs covers nodes discovered 

330 # later. Startup nodes are the exception — they were built before this 

331 # runs with their own kwargs snapshot — so the helper above also 

332 # updates them directly. 

333 else: 

334 self._oss_cluster_maint_notifications_handler = None 

335 

336 def _update_connection_kwargs_for_maint_notifications( 

337 self, 

338 oss_cluster_maint_notifications_handler: AsyncOSSMaintNotificationsHandler, 

339 ) -> None: 

340 maint_kwargs = { 

341 "oss_cluster_maint_notifications_handler": oss_cluster_maint_notifications_handler, 

342 "maint_notifications_config": oss_cluster_maint_notifications_handler.config, 

343 } 

344 # Shared template used for every node created from now on (e.g. nodes 

345 # discovered during nodes_manager.initialize()). 

346 self.nodes_manager.connection_kwargs.update(maint_kwargs) 

347 # Startup nodes were constructed before this mixin ran, so each one 

348 # snapshotted connection_kwargs without the handler. Their connections 

349 # are created lazily, so updating their per-node kwargs now is in time — 

350 # otherwise initialize() opens the topology-discovery connection (CLUSTER 

351 # SLOTS) on a startup node with no push handler wired and silently drops 

352 # the maintenance notifications carried on that connection. 

353 for node in self.nodes_manager.startup_nodes.values(): 

354 node.connection_kwargs.update(maint_kwargs) 

355 

356 

357class RedisCluster( 

358 AbstractRedis, 

359 AbstractRedisCluster, 

360 AsyncMaintNotificationsAbstractRedisCluster, 

361 AsyncRedisClusterCommands, 

362): 

363 """ 

364 Create a new RedisCluster client. 

365 

366 Pass one of parameters: 

367 

368 - `host` & `port` 

369 - `startup_nodes` 

370 

371 | Use ``await`` :meth:`initialize` to find cluster nodes & create connections. 

372 | Use ``await`` :meth:`close` to disconnect connections & close client. 

373 

374 Many commands support the target_nodes kwarg. It can be one of the 

375 :attr:`NODE_FLAGS`: 

376 

377 - :attr:`PRIMARIES` 

378 - :attr:`REPLICAS` 

379 - :attr:`ALL_NODES` 

380 - :attr:`RANDOM` 

381 - :attr:`DEFAULT_NODE` 

382 

383 Note: This client is not thread/process/fork safe. 

384 

385 :param host: 

386 | Can be used to point to a startup node 

387 :param port: 

388 | Port used if **host** is provided 

389 :param startup_nodes: 

390 | :class:`~.ClusterNode` to used as a startup node 

391 :param require_full_coverage: 

392 | When set to ``False``: the client will not require a full coverage of 

393 the slots. However, if not all slots are covered, and at least one node 

394 has ``cluster-require-full-coverage`` set to ``yes``, the server will throw 

395 a :class:`~.ClusterDownError` for some key-based commands. 

396 | When set to ``True``: all slots must be covered to construct the cluster 

397 client. If not all slots are covered, :class:`~.RedisClusterException` will be 

398 thrown. 

399 | See: 

400 https://redis.io/docs/manual/scaling/#redis-cluster-configuration-parameters 

401 :param read_from_replicas: 

402 | @deprecated - please use load_balancing_strategy instead 

403 | Enable read from replicas in READONLY mode. 

404 When set to true, read commands will be assigned between the primary and 

405 its replications in a Round-Robin manner. 

406 The data read from replicas is eventually consistent with the data in primary nodes. 

407 :param load_balancing_strategy: 

408 | Enable read from replicas in READONLY mode and defines the load balancing 

409 strategy that will be used for cluster node selection. 

410 The data read from replicas is eventually consistent with the data in primary nodes. 

411 :param metadata_resolver: 

412 | Optional :class:`~.AsyncMetadataResolver` instance used to map command names 

413 to replica-safe routing rules. If not provided, an AsyncStaticMetadataResolver 

414 is used by default. The routing view of it is derived into the default 

415 ``policy_resolver``; an explicit ``policy_resolver`` supersedes that view, but 

416 replica safety keeps resolving through this argument either way. 

417 :param dynamic_startup_nodes: 

418 | Set the RedisCluster's startup nodes to all the discovered nodes. 

419 If true (default value), the cluster's discovered nodes will be used to 

420 determine the cluster nodes-slots mapping in the next topology refresh. 

421 It will remove the initial passed startup nodes if their endpoints aren't 

422 listed in the CLUSTER SLOTS output. 

423 If you use dynamic DNS endpoints for startup nodes but CLUSTER SLOTS lists 

424 specific IP addresses, it is best to set it to false. 

425 Either way, a topology refresh that gets no slot map covering all 

426 slots from the startup nodes also asks the nodes of the current 

427 topology. 

428 :param reinitialize_steps: 

429 | Specifies the number of MOVED errors that need to occur before reinitializing 

430 the whole cluster topology. If a MOVED error occurs and the cluster does not 

431 need to be reinitialized on this current error handling, only the MOVED slot 

432 will be patched with the redirected node. 

433 To reinitialize the cluster on every MOVED error, set reinitialize_steps to 1. 

434 To avoid reinitializing the cluster on moved errors, set reinitialize_steps to 

435 0. A negative value is not the same as 0: it works like its absolute value 

436 (-3 is the same as 3). 

437 Every MOVED error patches its slot, so the redirect goes to the new owner; 

438 the refresh is only asked for, and like every refresh triggered by an 

439 error, it is run by the next command attempt once due, at most once per 

440 ``topology_refresh_min_interval``. 

441 :param cluster_error_retry_attempts: 

442 | @deprecated - Please configure the 'retry' object instead 

443 In case 'retry' object is set - this argument is ignored! 

444 

445 Number of times to retry before raising an error when :class:`~.TimeoutError`, 

446 :class:`~.ConnectionError`, :class:`~.SlotNotCoveredError` 

447 or :class:`~.ClusterDownError` are encountered, or when a node cached as a 

448 primary answers with :class:`~.ReadOnlyError` 

449 :param retry: 

450 | A retry object that defines the retry strategy and the number of 

451 retries for the cluster client. Its backoff sets the delay before each 

452 retry of a command or a pipeline; one that failed with 

453 :class:`~.ClusterDownError` or :class:`~.SlotNotCoveredError` also 

454 waits a fixed 0.25 seconds before it. A topology refresh triggered by an 

455 error (connection errors, the ``reinitialize_steps`` MOVED threshold) is 

456 run by the first command attempt to start once it is due, at most once 

457 per ``topology_refresh_min_interval``; after refreshes that failed in a 

458 row, the next one waits as long as the backoff gives for that many 

459 failures, but at least ``topology_refresh_min_interval``. A command that 

460 failed with a connection error or a timeout gives up with 

461 :class:`~.RedisClusterUnreachableError` once a refresh that ended since 

462 reached no node, or when it runs out of retries while the last refresh 

463 did. 

464 Backoffs that keep state between calls 

465 (:class:`~.DecorrelatedJitterBackoff`) are not fully supported: the 

466 retry object is shared by every command and pipeline of the client, so 

467 concurrent retries reset and advance each other's backoff, and the 

468 delays can come out shorter or longer than configured. 

469 :param max_connections: 

470 | Maximum number of connections per node. If there are no free connections & the 

471 maximum number of connections are already created, a 

472 :class:`~.MaxConnectionsError` is raised. 

473 :param socket_keepalive: 

474 | If ``True``, TCP keepalive is enabled for TCP socket connections. 

475 :param socket_keepalive_options: 

476 | Mapping of TCP keepalive socket option constants to values, for 

477 example ``{socket.TCP_KEEPIDLE: 30}``. If left unspecified, redis-py 

478 uses TCP keepalive defaults when ``socket_keepalive`` is enabled: 

479 idle 30 seconds, interval 5 seconds, and 3 probes. 

480 Platform-specific options that are not available are skipped. 

481 Pass ``None`` or ``{}`` to avoid setting additional TCP keepalive 

482 options. 

483 :param address_remap: 

484 | An optional callable which, when provided with an internal network 

485 address of a node, e.g. a `(host, port)` tuple, will return the address 

486 where the node is reachable. This can be used to map the addresses at 

487 which the nodes _think_ they are, to addresses at which a client may 

488 reach them, such as when they sit behind a proxy. 

489 :param topology_refresh_min_interval: 

490 | The minimum number of seconds between two topology refreshes triggered 

491 by errors (connection errors, the ``reinitialize_steps`` MOVED 

492 threshold, pipeline failures, pubsub repair). Requests made in between 

493 are collapsed into one refresh, run by the next command attempt once 

494 the interval has passed. After refreshes that failed in a row, the 

495 ``retry`` backoff can make the wait longer, never shorter. 0 lets every 

496 requested refresh run at once. Must be finite and not negative. 

497 Server-pushed refreshes (SMIGRATED), the first initialization and the 

498 refresh a ``CLUSTERDOWN`` or an uncovered slot runs are not limited. 

499 Defaults to one second when not set. 

500 

501 | Rest of the arguments will be passed to the 

502 :class:`~redis.asyncio.connection.Connection` instances when created 

503 

504 :raises RedisClusterException: 

505 if any arguments are invalid or unknown. Eg: 

506 

507 - `db` != 0 or None 

508 - `path` argument for unix socket connection 

509 - none of the `host`/`port` & `startup_nodes` were provided 

510 

511 """ 

512 

513 @classmethod 

514 def from_url(cls, url: str, **kwargs: Any) -> "RedisCluster": 

515 """ 

516 Return a Redis client object configured from the given URL. 

517 

518 For example:: 

519 

520 redis://[[username]:[password]]@localhost:6379/0 

521 rediss://[[username]:[password]]@localhost:6379/0 

522 

523 Three URL schemes are supported: 

524 

525 - `redis://` creates a TCP socket connection. See more at: 

526 <https://www.iana.org/assignments/uri-schemes/prov/redis> 

527 - `rediss://` creates a SSL wrapped TCP socket connection. See more at: 

528 <https://www.iana.org/assignments/uri-schemes/prov/rediss> 

529 

530 The username, password, hostname and path are passed through 

531 ``urllib.parse.unquote`` in order to replace any percent-encoded values with 

532 their corresponding characters. Querystring values are decoded by 

533 ``urllib.parse.parse_qs`` and are not unquoted again. 

534 

535 All querystring options are cast to their appropriate Python types. Boolean 

536 arguments can be specified with string values "True"/"False" or "Yes"/"No". 

537 Values that cannot be properly cast cause a ``ValueError`` to be raised. Once 

538 parsed, the querystring arguments and keyword arguments are passed to 

539 :class:`~redis.asyncio.connection.Connection` when created. 

540 In the case of conflicting arguments, querystring arguments are used. 

541 """ 

542 kwargs.update(parse_url(url)) 

543 if kwargs.pop("connection_class", None) is SSLConnection: 

544 kwargs["ssl"] = True 

545 return cls(**kwargs) 

546 

547 # Type discrimination marker for @overload self-type pattern 

548 _is_async_client: Literal[True] = True 

549 

550 __slots__ = ( 

551 "_initialize", 

552 "_lock", 

553 "_topology_ready", 

554 "maint_notifications_config", 

555 "_oss_cluster_maint_notifications_handler", 

556 "_himport_registry", 

557 "retry", 

558 "command_flags", 

559 "commands_parser", 

560 "connection_kwargs", 

561 "encoder", 

562 "node_flags", 

563 "nodes_manager", 

564 "read_from_replicas", 

565 "reinitialize_counter", 

566 "reinitialize_steps", 

567 "response_callbacks", 

568 "result_callbacks", 

569 ) 

570 

571 @deprecated_args( 

572 args_to_warn=["read_from_replicas"], 

573 reason="Please configure the 'load_balancing_strategy' instead", 

574 version="5.3.0", 

575 ) 

576 @deprecated_args( 

577 args_to_warn=[ 

578 "cluster_error_retry_attempts", 

579 ], 

580 reason="Please configure the 'retry' object instead", 

581 version="6.0.0", 

582 ) 

583 @deprecated_args( 

584 args_to_warn=["lib_name", "lib_version"], 

585 reason="Use 'driver_info' parameter instead. " 

586 "lib_name and lib_version will be removed in a future version.", 

587 ) 

588 def __init__( 

589 self, 

590 host: str | None = None, 

591 port: str | int = 6379, 

592 # Cluster related kwargs 

593 startup_nodes: List["ClusterNode"] | None = None, 

594 require_full_coverage: bool = True, 

595 read_from_replicas: bool = False, 

596 load_balancing_strategy: LoadBalancingStrategy | None = None, 

597 dynamic_startup_nodes: bool = True, 

598 reinitialize_steps: int = 5, 

599 cluster_error_retry_attempts: int = DEFAULT_RETRY_COUNT, 

600 max_connections: int = 100, 

601 retry: Retry | None = None, 

602 retry_on_error: List[Type[Exception]] | None = None, 

603 # Client related kwargs 

604 db: str | int = 0, 

605 path: str | None = None, 

606 credential_provider: CredentialProvider | None = None, 

607 username: str | None = None, 

608 password: str | None = None, 

609 client_name: str | None = None, 

610 lib_name: str | object | None = SENTINEL, 

611 lib_version: str | object | None = SENTINEL, 

612 driver_info: DriverInfo | object | None = SENTINEL, 

613 # Encoding related kwargs 

614 encoding: str = "utf-8", 

615 encoding_errors: str = "strict", 

616 decode_responses: bool = False, 

617 # Connection related kwargs 

618 health_check_interval: float = 0, 

619 socket_timeout: float | None = DEFAULT_SOCKET_TIMEOUT, 

620 socket_connect_timeout: float | None = DEFAULT_SOCKET_CONNECT_TIMEOUT, 

621 socket_read_size: int = DEFAULT_SOCKET_READ_SIZE, 

622 socket_keepalive: bool = True, 

623 socket_keepalive_options: Mapping[int, int | bytes] | object | None = SENTINEL, 

624 # SSL related kwargs 

625 ssl: bool = False, 

626 ssl_ca_certs: str | None = None, 

627 ssl_ca_data: str | None = None, 

628 ssl_cert_reqs: "str | VerifyMode" = "required", 

629 ssl_include_verify_flags: List["VerifyFlags"] | None = None, 

630 ssl_exclude_verify_flags: List["VerifyFlags"] | None = None, 

631 ssl_certfile: str | None = None, 

632 ssl_check_hostname: bool = True, 

633 ssl_keyfile: str | None = None, 

634 ssl_min_version: "TLSVersion | None" = None, 

635 ssl_ciphers: str | None = None, 

636 protocol: int | None = None, 

637 legacy_responses: bool = True, 

638 address_remap: Callable[[Tuple[str, int]], Tuple[str, int]] | None = None, 

639 event_dispatcher: EventDispatcher | None = None, 

640 policy_resolver: AsyncPolicyResolver | None = None, 

641 maint_notifications_config: MaintNotificationsConfig | None = None, 

642 metadata_resolver: AsyncMetadataResolver | None = None, 

643 topology_refresh_min_interval: float | None = None, 

644 ) -> None: 

645 if db: 

646 raise RedisClusterException( 

647 "Argument 'db' must be 0 or None in cluster mode" 

648 ) 

649 

650 if path: 

651 raise RedisClusterException( 

652 "Unix domain socket is not supported in cluster mode" 

653 ) 

654 

655 if topology_refresh_min_interval is not None and ( 

656 not math.isfinite(topology_refresh_min_interval) 

657 or topology_refresh_min_interval < 0 

658 ): 

659 raise RedisClusterException( 

660 "Argument 'topology_refresh_min_interval' must be a finite," 

661 " non-negative number" 

662 ) 

663 

664 port_is_provided = bool(port) or type(port) is int 

665 if (not host or not port_is_provided) and not startup_nodes: 

666 raise RedisClusterException( 

667 "RedisCluster requires at least one node to discover the cluster.\n" 

668 "Please provide one of the following or use RedisCluster.from_url:\n" 

669 ' - host and port: RedisCluster(host="localhost", port=6379)\n' 

670 " - startup_nodes: RedisCluster(startup_nodes=[" 

671 'ClusterNode("localhost", 6379), ClusterNode("localhost", 6380)])' 

672 ) 

673 

674 computed_driver_info = resolve_driver_info(driver_info, lib_name, lib_version) 

675 

676 kwargs: Dict[str, Any] = { 

677 "max_connections": max_connections, 

678 "connection_class": Connection, 

679 # Client related kwargs 

680 "credential_provider": credential_provider, 

681 "username": username, 

682 "password": password, 

683 "client_name": client_name, 

684 "driver_info": computed_driver_info, 

685 # Encoding related kwargs 

686 "encoding": encoding, 

687 "encoding_errors": encoding_errors, 

688 "decode_responses": decode_responses, 

689 # Connection related kwargs 

690 "health_check_interval": health_check_interval, 

691 "socket_connect_timeout": socket_connect_timeout, 

692 "socket_keepalive": socket_keepalive, 

693 "socket_keepalive_options": socket_keepalive_options, 

694 "socket_read_size": socket_read_size, 

695 "socket_timeout": socket_timeout, 

696 "protocol": protocol, 

697 "legacy_responses": legacy_responses, 

698 } 

699 

700 if ssl: 

701 # SSL related kwargs 

702 kwargs.update( 

703 { 

704 "connection_class": SSLConnection, 

705 "ssl_ca_certs": ssl_ca_certs, 

706 "ssl_ca_data": ssl_ca_data, 

707 "ssl_cert_reqs": ssl_cert_reqs, 

708 "ssl_include_verify_flags": ssl_include_verify_flags, 

709 "ssl_exclude_verify_flags": ssl_exclude_verify_flags, 

710 "ssl_certfile": ssl_certfile, 

711 "ssl_check_hostname": ssl_check_hostname, 

712 "ssl_keyfile": ssl_keyfile, 

713 "ssl_min_version": ssl_min_version, 

714 "ssl_ciphers": ssl_ciphers, 

715 } 

716 ) 

717 

718 if read_from_replicas or load_balancing_strategy: 

719 # Call our on_connect function to configure READONLY mode 

720 kwargs["redis_connect_func"] = self.on_connect 

721 

722 if retry: 

723 self.retry = _to_async_retry(retry) 

724 else: 

725 self.retry = Retry( 

726 backoff=ExponentialWithJitterBackoff( 

727 base=DEFAULT_RETRY_BASE, cap=DEFAULT_RETRY_CAP 

728 ), 

729 retries=cluster_error_retry_attempts, 

730 ) 

731 if retry_on_error: 

732 self.retry.update_supported_errors(retry_on_error) 

733 

734 kwargs["response_callbacks"] = get_response_callbacks( 

735 user_protocol=kwargs.get("protocol"), 

736 legacy_responses=kwargs.get("legacy_responses", True), 

737 ) 

738 if not kwargs.get("legacy_responses", True): 

739 kwargs["response_callbacks"]["CLUSTER SHARDS"] = ( 

740 parse_cluster_shards_unified 

741 ) 

742 elif kwargs.get("protocol") is None: 

743 kwargs["response_callbacks"]["CLUSTER SHARDS"] = ( 

744 parse_cluster_shards_with_str_keys 

745 ) 

746 else: 

747 kwargs["response_callbacks"]["CLUSTER SHARDS"] = parse_cluster_shards 

748 

749 # Build the client-level HIMPORT registry once (always empty at construction) 

750 # and share the same object with every node connection. It rides in 

751 # connection_kwargs -> ClusterNode -> each node's Connection, so the registry is 

752 # shared cluster-wide and runtime himport_prepare mutates one object. (Async has 

753 # no per-node Redis client, so the object flows via connection_kwargs directly to 

754 # the Connection, which is internal plumbing, not a public param.) 

755 self._himport_registry = HImportRegistry() 

756 kwargs["himport_registry"] = self._himport_registry 

757 

758 self.connection_kwargs = kwargs 

759 

760 # Validate maint_notifications_config before NodesManager is constructed 

761 # so that a bad config doesn't leak an open NodesManager. 

762 if ( 

763 maint_notifications_config 

764 and maint_notifications_config.enabled 

765 and not check_protocol_version(protocol, 3) 

766 ): 

767 raise RedisError( 

768 "Maintenance notifications are only supported with RESP version 3" 

769 ) 

770 if check_protocol_version(protocol, 3) and maint_notifications_config is None: 

771 maint_notifications_config = MaintNotificationsConfig() 

772 # Initialize to None so aclose() and any error-path code never sees an 

773 # unset slot, even if __init__ raises before the mixin runs. 

774 self._oss_cluster_maint_notifications_handler = None 

775 

776 if startup_nodes: 

777 passed_nodes = [] 

778 for node in startup_nodes: 

779 passed_nodes.append( 

780 ClusterNode(node.host, node.port, **self.connection_kwargs) 

781 ) 

782 startup_nodes = passed_nodes 

783 else: 

784 startup_nodes = [] 

785 if host and port_is_provided: 

786 startup_nodes.append(ClusterNode(host, port, **self.connection_kwargs)) 

787 

788 if event_dispatcher is None: 

789 self._event_dispatcher = EventDispatcher() 

790 else: 

791 self._event_dispatcher = event_dispatcher 

792 

793 self.startup_nodes = startup_nodes 

794 self.nodes_manager = NodesManager( 

795 startup_nodes, 

796 require_full_coverage, 

797 kwargs, 

798 dynamic_startup_nodes=dynamic_startup_nodes, 

799 address_remap=address_remap, 

800 event_dispatcher=self._event_dispatcher, 

801 topology_refresh_min_interval=topology_refresh_min_interval, 

802 ) 

803 AsyncMaintNotificationsAbstractRedisCluster.__init__( 

804 self, 

805 maint_notifications_config=maint_notifications_config, 

806 protocol=protocol, 

807 ) 

808 self.encoder = Encoder(encoding, encoding_errors, decode_responses) 

809 self.read_from_replicas = read_from_replicas 

810 self.load_balancing_strategy = load_balancing_strategy 

811 self.reinitialize_steps = reinitialize_steps 

812 self.reinitialize_counter = 0 

813 

814 # For backward compatibility, mapping from existing policies to new one 

815 self._command_flags_mapping: dict[str, Union[RequestPolicy, ResponsePolicy]] = { 

816 self.__class__.RANDOM: RequestPolicy.DEFAULT_KEYLESS, 

817 self.__class__.PRIMARIES: RequestPolicy.ALL_SHARDS, 

818 self.__class__.ALL_NODES: RequestPolicy.ALL_NODES, 

819 self.__class__.REPLICAS: RequestPolicy.ALL_REPLICAS, 

820 self.__class__.DEFAULT_NODE: RequestPolicy.DEFAULT_NODE, 

821 SLOT_ID: RequestPolicy.DEFAULT_KEYED, 

822 } 

823 

824 # Built here rather than defaulted in the signature, so that each client owns its 

825 # resolver and the memos it accumulates are released with the client. The async 

826 # ClusterPipeline holds the client and reads this attribute, so a pipeline routes by 

827 # whatever the client routes by without any propagation of its own. 

828 if metadata_resolver is None: 

829 self._metadata_resolver: AsyncMetadataResolver = ( 

830 AsyncStaticMetadataResolver() 

831 ) 

832 else: 

833 self._metadata_resolver = metadata_resolver 

834 

835 # ``policy_resolver`` is the routing view of a metadata resolver, so the two 

836 # arguments overlap. Resolved by precedence rather than by rejecting the 

837 # combination, because a user migrating from one to the other will legitimately pass 

838 # both: an explicit ``policy_resolver`` - the extension point that shipped in 7.1.0 

839 # - keeps deciding which nodes a command targets, and otherwise those policies are 

840 # derived from the metadata resolver. 

841 # 

842 # The precedence covers the routing view only. Replica safety is read from 

843 # ``_metadata_resolver`` either way, because the projection a policy resolver serves 

844 # drops the flag it is decided from - a ``CommandPolicies`` record has no 

845 # ``is_readonly``. Mirrors the sync stack, including the log below. 

846 if policy_resolver is None: 

847 self._policy_resolver: AsyncPolicyResolver = AsyncStaticPolicyResolver( 

848 metadata_resolver=self._metadata_resolver 

849 ) 

850 else: 

851 self._policy_resolver = policy_resolver 

852 if metadata_resolver is not None: 

853 logger.debug( 

854 "Both policy_resolver and metadata_resolver were given; the nodes a " 

855 "command targets resolve through policy_resolver and ignore " 

856 "metadata_resolver. Replica safety still resolves through " 

857 "metadata_resolver." 

858 ) 

859 self.commands_parser = AsyncCommandsParser() 

860 self._aggregate_nodes = None 

861 self.node_flags = self.__class__.NODE_FLAGS.copy() 

862 self.command_flags = self.__class__.COMMAND_FLAGS.copy() 

863 self.response_callbacks = kwargs["response_callbacks"] 

864 self.result_callbacks = self.__class__.RESULT_CALLBACKS.copy() 

865 self.result_callbacks["CLUSTER SLOTS"] = lambda cmd, res, **kwargs: ( 

866 parse_cluster_slots(list(res.values())[0], **kwargs) 

867 ) 

868 

869 self._initialize = True 

870 self._lock: Optional[asyncio.Lock] = None 

871 # Set once a refresh has finished, commands parser included, and cleared 

872 # by aclose(): the default node is published before the first refresh 

873 # finishes, so it does not tell whether the topology can serve yet 

874 self._topology_ready = False 

875 

876 # When used as an async context manager, we need to increment and decrement 

877 # a usage counter so that we can close the connection pool when no one is 

878 # using the client. 

879 self._usage_counter = 0 

880 self._usage_lock = asyncio.Lock() 

881 

882 def _initialize_due(self) -> bool: 

883 """ 

884 Whether initialize() has work to do now: the client has no topology 

885 yet, or a refresh was asked for, is due and no other task is running 

886 it. The command, pipeline and transaction attempts check this before 

887 awaiting initialize(), so an attempt made while a requested refresh is 

888 not due yet costs no coroutine. 

889 """ 

890 return self._initialize and not ( 

891 self._topology_ready 

892 and ( 

893 not self.nodes_manager._refresh_due(self.retry) 

894 or (self._lock is not None and self._lock.locked()) 

895 ) 

896 ) 

897 

898 async def initialize( 

899 self, 

900 additional_startup_nodes_info: List[Tuple[str, int]] | None = None, 

901 last_failed_node_name: str | None = None, 

902 ) -> "RedisCluster": 

903 """ 

904 Get all nodes from startup nodes & creates connections if not initialized. 

905 

906 Once initialized, this refreshes the topology only when one was asked 

907 for (``_initialize`` is set by the error paths), and no sooner than 

908 ``topology_refresh_min_interval`` after the previous refresh, 

909 or longer after refreshes that failed (see ``_topology_refresh_delay``). 

910 Until then it returns at once and the current topology keeps serving. 

911 It also returns at once while another task runs the refresh: only the 

912 first initialize, which has no topology to serve yet, makes the other 

913 callers wait for it. 

914 A refresh that reached no node, or whose nodes answered with a topology 

915 that cannot replace the current one (slots not covered, or nodes that 

916 disagree on them), is logged and asked for again instead of raised; the 

917 current topology keeps serving until a refresh succeeds. 

918 """ 

919 if self._initialize: 

920 if not self._initialize_due(): 

921 # A refresh was asked for but is not due yet, or another task 

922 # is running it; the current topology keeps serving. The flag 

923 # stays until a refresh succeeds, so a later call runs it 

924 return self 

925 if not self._lock: 

926 self._lock = asyncio.Lock() 

927 async with self._lock: 

928 if self._initialize: 

929 # A client that never initialized (or was closed since) 

930 # has no topology to serve yet 

931 first_initialize = not self._topology_ready 

932 if not first_initialize and not self.nodes_manager._refresh_due( 

933 self.retry 

934 ): 

935 # A refresh that failed while this task waited for the 

936 # lock moved the next one out; the current topology 

937 # keeps serving until it is due 

938 return self 

939 requested_at_epoch = self.nodes_manager._refresh_requested_at_epoch 

940 if ( 

941 not first_initialize 

942 and requested_at_epoch is not None 

943 and requested_at_epoch != self.nodes_manager._epoch 

944 ): 

945 # A refresh completed after the last request (for 

946 # example one SMIGRATED ran) and counts as answering 

947 # it, the nodes it named included 

948 self.nodes_manager._refresh_requested_at_epoch = None 

949 self.nodes_manager._requested_last_failed_node_name = None 

950 self.nodes_manager._requested_additional_startup_nodes = () 

951 self._initialize = False 

952 return self 

953 try: 

954 await self._refresh_topology( 

955 additional_startup_nodes_info=additional_startup_nodes_info, 

956 last_failed_node_name=last_failed_node_name, 

957 ) 

958 self._initialize = False 

959 self._topology_ready = True 

960 self.nodes_manager._refresh_requested_at_epoch = None 

961 except BaseException as e: 

962 # Only a client that never initialized is torn down. A 

963 # failed or cancelled refresh keeps the connections of 

964 # the current topology, which every other task is using, 

965 # and leaves _initialize set so the next command retries. 

966 if first_initialize: 

967 # Every node is closed, and the refresh error is 

968 # raised: a close failure of a client that never 

969 # initialized must not hide why it failed 

970 try: 

971 await self.nodes_manager._aclose_all() 

972 except Exception: 

973 pass 

974 raise 

975 if isinstance(e, RedisClusterException): 

976 # No node answered, or nodes answered with a 

977 # topology that cannot replace the current one. The 

978 # current topology keeps serving until a refresh 

979 # succeeds: this may be a command for a healthy 

980 # shard, which must not fail for a refresh another 

981 # error asked for. The failure is counted, so the 

982 # next refresh runs once the backoff allows. 

983 logger.error( 

984 f"Topology refresh failed, keeping the current one: {e}" 

985 ) 

986 return self 

987 raise 

988 return self 

989 

990 async def _refresh_topology( 

991 self, 

992 additional_startup_nodes_info: Optional[List[Tuple[str, int]]] = None, 

993 last_failed_node_name: Optional[str] = None, 

994 ) -> None: 

995 """ 

996 Refresh the nodes and slots caches, and point the commands parser at a 

997 node of the current topology. 

998 """ 

999 await self.nodes_manager.initialize( 

1000 additional_startup_nodes_info=additional_startup_nodes_info, 

1001 last_failed_node_name=last_failed_node_name, 

1002 ) 

1003 if self.commands_parser.commands: 

1004 # The command table is fetched once, as on the sync client. A command 

1005 # missing from it (e.g. added by a server upgrade) makes get_keys 

1006 # fetch it again, from this node, so the node must be one that is 

1007 # still part of the cluster; it also serves COMMAND GETKEYS 

1008 self.commands_parser.node = self.nodes_manager.default_node 

1009 else: 

1010 await self.commands_parser.initialize(self.nodes_manager.default_node) 

1011 

1012 def _request_refresh( 

1013 self, 

1014 additional_startup_nodes_info: Optional[List[Tuple[str, int]]] = None, 

1015 last_failed_node_name: Optional[str] = None, 

1016 ) -> None: 

1017 """ 

1018 Ask for a topology refresh after an error. Requests are merged until 

1019 initialize() runs them, once due. The nodes they name are kept until a 

1020 refresh succeeds, so the refresh uses them whichever command runs it. 

1021 """ 

1022 nodes_manager = self.nodes_manager 

1023 if additional_startup_nodes_info: 

1024 requested = nodes_manager._requested_additional_startup_nodes 

1025 new_nodes = tuple( 

1026 node_info 

1027 for node_info in additional_startup_nodes_info 

1028 if node_info not in requested 

1029 ) 

1030 if new_nodes: 

1031 nodes_manager._requested_additional_startup_nodes = ( 

1032 *requested, 

1033 *new_nodes, 

1034 ) 

1035 if last_failed_node_name is not None: 

1036 nodes_manager._requested_last_failed_node_name = last_failed_node_name 

1037 # The epoch of the newest request. A refresh that completes after it 

1038 # counts as answering every merged request, even one that started 

1039 # before the error and read a slot map from before it: an error that 

1040 # outlives it asks again 

1041 nodes_manager._refresh_requested_at_epoch = nodes_manager._epoch 

1042 self._initialize = True 

1043 

1044 async def aclose(self) -> None: 

1045 """Close all connections & client if initialized.""" 

1046 # Initialized means the client has a topology (a default node), not that 

1047 # _initialize is clear: the error paths set _initialize to ask for a 

1048 # refresh, and a client closed before that refresh ran must still close 

1049 if self.nodes_manager.default_node is not None: 

1050 if not self._lock: 

1051 self._lock = asyncio.Lock() 

1052 async with self._lock: 

1053 if self.nodes_manager.default_node is not None: 

1054 self._initialize = True 

1055 self._topology_ready = False 

1056 if self._oss_cluster_maint_notifications_handler: 

1057 tasks = list( 

1058 self._oss_cluster_maint_notifications_handler._background_tasks 

1059 ) 

1060 for task in tasks: 

1061 task.cancel() 

1062 await asyncio.gather(*tasks, return_exceptions=True) 

1063 await self.nodes_manager._aclose_all() 

1064 

1065 @deprecated_function(version="5.0.0", reason="Use aclose() instead", name="close") 

1066 async def close(self) -> None: 

1067 """alias for aclose() for backwards compatibility""" 

1068 await self.aclose() 

1069 

1070 async def __aenter__(self) -> "RedisCluster": 

1071 """ 

1072 Async context manager entry. Increments a usage counter so that the 

1073 connection pool is only closed (via aclose()) when no context is using 

1074 the client. 

1075 """ 

1076 await self._increment_usage() 

1077 try: 

1078 # Initialize the client (i.e. establish connection, etc.) 

1079 return await self.initialize() 

1080 except (Exception, asyncio.CancelledError): 

1081 # If initialization fails, decrement the counter to keep it in sync 

1082 await asyncio.shield(self._decrement_usage()) 

1083 raise 

1084 

1085 async def _increment_usage(self) -> int: 

1086 """ 

1087 Helper coroutine to increment the usage counter while holding the lock. 

1088 Returns the new value of the usage counter. 

1089 """ 

1090 async with self._usage_lock: 

1091 self._usage_counter += 1 

1092 return self._usage_counter 

1093 

1094 async def _decrement_usage(self) -> int: 

1095 """ 

1096 Helper coroutine to decrement the usage counter while holding the lock. 

1097 Returns the new value of the usage counter. 

1098 """ 

1099 async with self._usage_lock: 

1100 self._usage_counter -= 1 

1101 return self._usage_counter 

1102 

1103 async def _release_usage(self) -> None: 

1104 """ 

1105 Decrement the usage counter and close the client on the last exit. 

1106 

1107 Hold the lock through closing so a new context cannot use connections 

1108 that are still being disconnected by the previous context. 

1109 """ 

1110 async with self._usage_lock: 

1111 self._usage_counter -= 1 

1112 if self._usage_counter == 0: 

1113 await self.aclose() 

1114 

1115 async def __aexit__(self, exc_type, exc_value, traceback): 

1116 """ 

1117 Async context manager exit. Decrements a usage counter. If this is the 

1118 last exit (counter becomes zero), the client closes its connection pool. 

1119 """ 

1120 await asyncio.shield(self._release_usage()) 

1121 

1122 def __await__(self) -> Generator[Any, None, "RedisCluster"]: 

1123 return self.initialize().__await__() 

1124 

1125 _DEL_MESSAGE = "Unclosed RedisCluster client" 

1126 

1127 def __del__( 

1128 self, 

1129 _warn: Any = warnings.warn, 

1130 _grl: Any = asyncio.get_running_loop, 

1131 ) -> None: 

1132 # Initialized means the client has a topology, as in aclose(): an error 

1133 # path can leave _initialize set on a client that is still open 

1134 nodes_manager = getattr(self, "nodes_manager", None) 

1135 if nodes_manager is not None and nodes_manager.default_node is not None: 

1136 _warn(f"{self._DEL_MESSAGE} {self!r}", ResourceWarning, source=self) 

1137 try: 

1138 context = {"client": self, "message": self._DEL_MESSAGE} 

1139 _grl().call_exception_handler(context) 

1140 except RuntimeError: 

1141 pass 

1142 

1143 async def on_connect(self, connection: Connection) -> None: 

1144 await connection.on_connect() 

1145 

1146 # Sending READONLY command to server to configure connection as 

1147 # readonly. Since each cluster node may change its server type due 

1148 # to a failover, we should establish a READONLY connection 

1149 # regardless of the server type. If this is a primary connection, 

1150 # READONLY would not affect executing write commands. 

1151 await connection.send_command("READONLY") 

1152 if str_if_bytes(await connection.read_response()) != "OK": 

1153 raise ConnectionError("READONLY command failed") 

1154 

1155 def get_nodes(self) -> List["ClusterNode"]: 

1156 """Get all nodes of the cluster.""" 

1157 return list(self.nodes_manager.nodes_cache.values()) 

1158 

1159 def get_primaries(self) -> List["ClusterNode"]: 

1160 """Get the primary nodes of the cluster.""" 

1161 return self.nodes_manager.get_nodes_by_server_type(PRIMARY) 

1162 

1163 def get_replicas(self) -> List["ClusterNode"]: 

1164 """Get the replica nodes of the cluster.""" 

1165 return self.nodes_manager.get_nodes_by_server_type(REPLICA) 

1166 

1167 def get_random_node(self) -> "ClusterNode": 

1168 """Get a random node of the cluster.""" 

1169 return random.choice(list(self.nodes_manager.nodes_cache.values())) 

1170 

1171 def get_default_node(self) -> "ClusterNode": 

1172 """Get the default node of the client.""" 

1173 return self.nodes_manager.default_node 

1174 

1175 def set_default_node(self, node: "ClusterNode") -> None: 

1176 """ 

1177 Set the default node of the client. 

1178 

1179 :raises DataError: if None is passed or node does not exist in cluster. 

1180 """ 

1181 if not node or not self.get_node(node_name=node.name): 

1182 raise DataError("The requested node does not exist in the cluster.") 

1183 

1184 self.nodes_manager.default_node = node 

1185 

1186 def get_node( 

1187 self, 

1188 host: Optional[str] = None, 

1189 port: Optional[int] = None, 

1190 node_name: Optional[str] = None, 

1191 ) -> Optional["ClusterNode"]: 

1192 """Get node by (host, port) or node_name.""" 

1193 return self.nodes_manager.get_node(host, port, node_name) 

1194 

1195 def get_node_from_key( 

1196 self, key: str, replica: bool = False 

1197 ) -> Optional["ClusterNode"]: 

1198 """ 

1199 Get the cluster node corresponding to the provided key. 

1200 

1201 :param key: 

1202 :param replica: 

1203 | Indicates if a replica should be returned 

1204 | 

1205 None will returned if no replica holds this key 

1206 

1207 :raises SlotNotCoveredError: if the key is not covered by any slot. 

1208 """ 

1209 slot = self.keyslot(key) 

1210 slot_cache = self.nodes_manager.slots_cache.get(slot) 

1211 if not slot_cache: 

1212 raise SlotNotCoveredError(f'Slot "{slot}" is not covered by the cluster.') 

1213 

1214 if replica: 

1215 if len(self.nodes_manager.slots_cache[slot]) < 2: 

1216 return None 

1217 node_idx = 1 

1218 else: 

1219 node_idx = 0 

1220 

1221 return slot_cache[node_idx] 

1222 

1223 async def get_keyless_target_node(self, command_name: str) -> "ClusterNode": 

1224 """ 

1225 Returns the node a keyless command is routed to: a random node when replica reads 

1226 are enabled and the command is safe to serve from a replica, a random primary 

1227 otherwise. 

1228 

1229 A replicas-only ``load_balancing_strategy`` is honored by picking from the replicas 

1230 alone, so a strategy that asks for replicas cannot land on a primary here. The 

1231 strategy is not applied any further than that: the rest of it is an index into one 

1232 shard's node list and a round-robin counter kept per primary name, and a keyless 

1233 command has no shard to index - so the pick is uniform over the eligible nodes. 

1234 

1235 Falls back to the whole node set when the cluster has no replicas to pick from, 

1236 which is every primary. That is also the answer for the two strategies that 

1237 include the primary, and for ``read_from_replicas`` on its own, which is what this 

1238 method has returned for a replica-safe command since 7.1.0. 

1239 """ 

1240 replica_safe = ( 

1241 self.read_from_replicas or self.load_balancing_strategy is not None 

1242 ) and await self._is_replica_safe(command_name) 

1243 if replica_safe: 

1244 if self.load_balancing_strategy in _REPLICAS_ONLY_STRATEGIES: 

1245 replicas = self.get_replicas() 

1246 if replicas: 

1247 return random.choice(replicas) 

1248 

1249 return self.get_random_node() 

1250 

1251 return self.get_random_primary_node() 

1252 

1253 @deprecated_function( 

1254 version="8.2.0", 

1255 reason="Use get_keyless_target_node() instead.", 

1256 ) 

1257 def get_random_primary_or_all_nodes(self, command_name: str) -> "ClusterNode": 

1258 """ 

1259 Returns random primary or all nodes depends on READONLY mode. 

1260 

1261 Deprecated wrapper over :meth:`get_keyless_target_node`, kept so the name that 

1262 has been public since 7.1.0 keeps working. Replica safety is resolved through the 

1263 metadata resolver, which is awaitable, so the coroutine runs on its own event loop 

1264 in a worker thread to keep this entry point synchronous. 

1265 

1266 .. warning:: 

1267 

1268 **Do not extend this method, and do not call it from a running event loop.** 

1269 Keeping the 7.1.0 signature synchronous costs a thread bridge 

1270 (``_run_coroutine_in_thread``) that blocks the calling thread until the 

1271 resolver answers. Two rules follow, and breaking either one stalls the caller 

1272 permanently rather than raising: 

1273 

1274 1. **Override the right method.** A subclass that customizes keyless routing 

1275 must override :meth:`get_keyless_target_node`, the coroutine the client 

1276 actually awaits. Overriding this name changes nothing, because no code path 

1277 inside the client calls it. 

1278 2. **Keep a custom resolver synchronous in effect.** A caller-supplied 

1279 ``AsyncMetadataResolver`` must implement ``is_replica_safe`` as a 

1280 self-contained in-memory lookup. One that awaits work owned by the caller's 

1281 loop - I/O over a pooled connection, say - waits on a loop this bridge has 

1282 already blocked, and hangs. 

1283 

1284 That bridge is what confines this method to the deprecation window. It is sound 

1285 for the resolvers the library ships, whose ``is_replica_safe`` suspends on nothing, 

1286 and nothing inside the client reaches this path: keyless routing goes through 

1287 :meth:`get_keyless_target_node`, which is awaited normally. So the hazard is 

1288 confined to callers of this deprecated name. 

1289 """ 

1290 return _run_coroutine_in_thread(self.get_keyless_target_node(command_name)) 

1291 

1292 async def _is_replica_safe(self, command_name: str) -> bool: 

1293 return await self._metadata_resolver.is_replica_safe(command_name) 

1294 

1295 def get_random_primary_node(self) -> "ClusterNode": 

1296 """ 

1297 Returns a random primary node 

1298 """ 

1299 return random.choice(self.get_primaries()) 

1300 

1301 async def get_nodes_from_slot(self, command: str, *args): 

1302 """ 

1303 Returns a list of nodes that hold the specified keys' slots. 

1304 """ 

1305 # get the node that holds the key's slot 

1306 slot = await self._determine_slot(command, *args) 

1307 replica_safe = ( 

1308 self.read_from_replicas or self.load_balancing_strategy is not None 

1309 ) and await self._is_replica_safe(command) 

1310 return [ 

1311 self.nodes_manager.get_node_from_slot( 

1312 slot, 

1313 replica_safe, 

1314 self.load_balancing_strategy if replica_safe else None, 

1315 ) 

1316 ] 

1317 

1318 async def _get_node_from_slot(self, command: str, slot: int) -> "ClusterNode": 

1319 """ 

1320 Returns the node a command for the given slot is sent to, a replica when the 

1321 command is replica safe and the client reads from replicas - for a command whose 

1322 slot is already known, so its keys are not hashed again. 

1323 """ 

1324 replica_safe = ( 

1325 self.read_from_replicas or self.load_balancing_strategy is not None 

1326 ) and await self._is_replica_safe(command) 

1327 return self.nodes_manager.get_node_from_slot( 

1328 slot, 

1329 replica_safe, 

1330 self.load_balancing_strategy if replica_safe else None, 

1331 ) 

1332 

1333 def _split_multi_shard_command( 

1334 self, *args: Any 

1335 ) -> Optional[List[_MultiShardSplit]]: 

1336 """ 

1337 Splits a command with the MULTI_SHARD request policy into one command per hash 

1338 slot of its keys - see ``redis.cluster._split_by_slot``. 

1339 """ 

1340 return _split_by_slot( 

1341 args, 

1342 self.commands_parser.commands.get(str(args[0]).lower()), 

1343 self.keyslot, 

1344 ) 

1345 

1346 async def _execute_multi_shard_command( 

1347 self, 

1348 command: str, 

1349 splits: List[_MultiShardSplit], 

1350 response_policy: ResponsePolicy, 

1351 **kwargs: Any, 

1352 ) -> Any: 

1353 """ 

1354 Sends the commands of a split MULTI_SHARD command in one pipeline and merges the 

1355 replies - see ``redis.cluster._merge_multi_shard_replies``. 

1356 

1357 The pipeline batches the commands per node, so the command costs one round trip 

1358 per node rather than one per slot, and holds one connection per node. Each command 

1359 names the node holding its slot, so the pipeline does not split it again, and a 

1360 command that fails is retried on its own, routed by its keys: the pipeline retries 

1361 a redirection, and the errors the client retries - a connection error, CLUSTERDOWN, 

1362 or a slot the client knows no node for - are resent here, with the retries of a 

1363 command sent on its own, as the sync client does. A slot that succeeded is 

1364 therefore not sent again, which would run a write twice and change what a summed 

1365 reply counts. The failed slots are resent one at a time, so they do not take one 

1366 connection each. 

1367 """ 

1368 replica_safe = ( 

1369 self.read_from_replicas or self.load_balancing_strategy is not None 

1370 ) and await self._is_replica_safe(command) 

1371 load_balancing_strategy = self.load_balancing_strategy if replica_safe else None 

1372 pipe = self.pipeline() 

1373 replies: List[Any] = [None] * len(splits) 

1374 # The node each slot's command is queued for. None for a slot that is not queued 

1375 # or is resent: its error is recorded by the command that raised it. 

1376 nodes: List[Optional[ClusterNode]] = [None] * len(splits) 

1377 for index, (slot, slot_args, _, keys) in enumerate(splits): 

1378 try: 

1379 nodes[index] = self.nodes_manager.get_node_from_slot( 

1380 slot, replica_safe, load_balancing_strategy 

1381 ) 

1382 except SlotNotCoveredError as e: 

1383 replies[index] = e 

1384 continue 

1385 pipe.execute_command( 

1386 *slot_args, target_nodes=[nodes[index]], **_with_keys(kwargs, keys) 

1387 ) 

1388 

1389 queued = [index for index, node in enumerate(nodes) if node is not None] 

1390 for index, reply in zip(queued, await pipe.execute(raise_on_error=False)): 

1391 replies[index] = reply 

1392 for index, ((_, slot_args, _, keys), reply) in enumerate(zip(splits, replies)): 

1393 if isinstance(reply, self.ERRORS_ALLOW_RETRY) and not isinstance( 

1394 reply, self.NOT_NODE_FAILURE_ERRORS 

1395 ): 

1396 nodes[index] = None 

1397 try: 

1398 replies[index] = await self.execute_command( 

1399 *slot_args, **_with_keys(kwargs, keys) 

1400 ) 

1401 except RedisError as e: 

1402 replies[index] = e 

1403 

1404 slot_replies: Dict[int, Any] = {} 

1405 for index, ((slot, _, _, _), reply) in enumerate(zip(splits, replies)): 

1406 if isinstance(reply, BaseException): 

1407 # A command sent on its own counts the error it fails with. The pipeline 

1408 # counts none, so an error read from it is counted here; one a retry 

1409 # raised carries the connection its command already counted it on. 

1410 node = nodes[index] 

1411 if node is not None and not hasattr(reply, "connection"): 

1412 await self._record_error_metric( 

1413 error=reply, connection=node, is_internal=False 

1414 ) 

1415 raise reply 

1416 slot_replies[slot] = reply 

1417 return _merge_multi_shard_replies(slot_replies, splits, response_policy) 

1418 

1419 def get_special_nodes(self) -> Optional[list["ClusterNode"]]: 

1420 """ 

1421 Returns a list of nodes for commands with a special policy. 

1422 """ 

1423 if not self._aggregate_nodes: 

1424 raise RedisClusterException( 

1425 "Cannot execute FT.CURSOR commands without FT.AGGREGATE" 

1426 ) 

1427 

1428 return self._aggregate_nodes 

1429 

1430 def keyslot(self, key: EncodableT) -> int: 

1431 """ 

1432 Find the keyslot for a given key. 

1433 

1434 See: https://redis.io/docs/manual/scaling/#redis-cluster-data-sharding 

1435 """ 

1436 return key_slot(self.encoder.encode(key)) 

1437 

1438 # HIMPORT orchestration (async mirror of redis.cluster.RedisCluster). The one 

1439 # shared HImportRegistry is mutated once by PREPARE/DISCARD/DISCARDALL and applied 

1440 # lazily per node; SET routes by key slot to the owning primary's ClusterNode. 

1441 # See ``.agents/himport_client_support_spec.md``. 

1442 

1443 @property 

1444 def himport_registry(self) -> HImportRegistry: 

1445 """The cluster-wide HIMPORT fieldset registry (empty if none was declared). 

1446 

1447 Read-only: the registry is mutated only through the HIMPORT command methods. 

1448 """ 

1449 return self._himport_registry 

1450 

1451 @experimental_method() 

1452 async def himport_prepare( 

1453 self, fieldset_name: str, fields: Iterable[FieldT] 

1454 ) -> bool: 

1455 """Declare an HIMPORT fieldset cluster-wide (shared registry, applied lazily).""" 

1456 await self.initialize() 

1457 self._himport_registry.prepare(fieldset_name, fields) 

1458 return True 

1459 

1460 @experimental_method() 

1461 async def himport_discard(self, fieldset_name: str) -> int: 

1462 """Remove an HIMPORT fieldset cluster-wide (shared registry, applied lazily).""" 

1463 await self.initialize() 

1464 return 1 if self._himport_registry.discard(fieldset_name) else 0 

1465 

1466 @experimental_method() 

1467 async def himport_discard_all(self) -> int: 

1468 """Remove all HIMPORT fieldsets cluster-wide (shared registry, applied lazily).""" 

1469 await self.initialize() 

1470 return self._himport_registry.discard_all() 

1471 

1472 def get_encoder(self) -> Encoder: 

1473 """Get the encoder object of the client.""" 

1474 return self.encoder 

1475 

1476 def get_connection_kwargs(self) -> Dict[str, Optional[Any]]: 

1477 """Get the kwargs passed to :class:`~redis.asyncio.connection.Connection`.""" 

1478 return self.connection_kwargs 

1479 

1480 def set_retry(self, retry: Retry) -> None: 

1481 self.retry = _to_async_retry(retry) 

1482 

1483 def set_response_callback(self, command: str, callback: ResponseCallbackT) -> None: 

1484 """Set a custom response callback.""" 

1485 self.response_callbacks[command] = callback 

1486 

1487 async def _resolve_command_policies( 

1488 self, *args: Any, target_nodes_specified: bool = False 

1489 ) -> Tuple[str, CommandPolicies | CommandMetadata, int | None]: 

1490 """ 

1491 Resolves the policies a command routes and aggregates by, and the slot of its 

1492 keys when finding the policies took computing it. 

1493 

1494 Returns the name the policies were decided by along with the record, because the 

1495 name a command is known by is not always ``args[0]``: a container command is 

1496 keyed by both of its words, and the flag tables are keyed in upper case. Callers 

1497 that look the command up elsewhere - result callbacks, observability - use the 

1498 returned name so they agree with the routing decision. 

1499 

1500 The name is normalized before any branch, so one command answers with one name 

1501 however it got here. The result callbacks are keyed in upper case, so a name that 

1502 kept the caller's spelling on only some paths would fire them on only some paths - 

1503 ``execute_command("dbsize")`` would be summed and ``execute_command("dbsize", 

1504 target_nodes=...)`` would not. 

1505 

1506 First choice is the policy resolver. When it does not know the command, the 

1507 fallbacks are, in order: nothing to route at all because the caller named its 

1508 targets, the command's ``COMMAND_FLAGS`` entry, and finally whether the command 

1509 carries a key. ``target_nodes_specified`` says the caller picked the targets, as 

1510 named nodes or as a nodes flag. 

1511 

1512 That last fallback computes the command's slot, which is returned so the caller 

1513 can pass it to ``_determine_nodes`` instead of computing it again. Every other 

1514 branch returns ``None`` for the slot. 

1515 """ 

1516 command = args[0].upper() 

1517 if len(args) >= 2 and f"{args[0]} {args[1]}".upper() in self.command_flags: 

1518 command = f"{args[0]} {args[1]}".upper() 

1519 

1520 if target_nodes_specified: 

1521 # The caller picked its targets - named nodes, or a nodes flag that 

1522 # ``_determine_nodes`` resolves - so nothing is routed from here, and the 

1523 # command's own aggregation must not apply either. A response policy resolved 

1524 # for the whole cluster (``ONE_SUCCEEDED``, an ``AGG_*``) would short-circuit 

1525 # the loop over the nodes the caller picked, or fold their replies into one. 

1526 # Answer with the record that aggregates nothing, and skip the resolver: with 

1527 # the targets given, neither of its answers is used. 

1528 return command, _DEFAULT_KEYLESS_METADATA, None 

1529 

1530 policies = await self._policy_resolver.resolve(args[0].lower()) 

1531 if policies: 

1532 return command, policies, None 

1533 

1534 command_flag = self.command_flags.get(command) 

1535 if command_flag: 

1536 if command_flag in self._command_flags_mapping: 

1537 return ( 

1538 command, 

1539 _METADATA_BY_REQUEST_POLICY[ 

1540 self._command_flags_mapping[command_flag] 

1541 ], 

1542 None, 

1543 ) 

1544 return command, _DEFAULT_KEYLESS_METADATA, None 

1545 

1546 # Unflagged and unresolved, so the command routes by its key. Without a default 

1547 # node the topology is not known yet and there is no slot to route by. 

1548 if not self.get_default_node(): 

1549 return command, _DEFAULT_KEYLESS_METADATA, None 

1550 

1551 slot = await self._determine_slot(*args) 

1552 if slot is None: 

1553 return command, _DEFAULT_KEYLESS_METADATA, None 

1554 

1555 return command, _DEFAULT_KEYED_METADATA, slot 

1556 

1557 async def _determine_nodes( 

1558 self, 

1559 command: str, 

1560 *args: Any, 

1561 request_policy: RequestPolicy | None = None, 

1562 node_flag: str | None = None, 

1563 slot: int | None = None, 

1564 ) -> List["ClusterNode"]: 

1565 # Determine which nodes should be executed the command on. 

1566 # Returns a list of target nodes. 

1567 # The caller resolves the command's own policy - see 

1568 # ``_resolve_command_policies`` - so the only decision left here is an explicit 

1569 # node flag, which overrides it. ``slot`` is the slot that resolution already 

1570 # computed, if it did, so a keyed command is not hashed twice. 

1571 if node_flag and self._is_node_flag(node_flag): 

1572 if node_flag in self._command_flags_mapping: 

1573 request_policy = self._command_flags_mapping[node_flag] 

1574 

1575 if request_policy is None: 

1576 raise RedisClusterException( 

1577 f"No targets were found to execute {command} command on" 

1578 ) 

1579 

1580 if slot is not None: 

1581 # Only the keyed fallback of ``_resolve_command_policies`` computes a slot 

1582 nodes = [await self._get_node_from_slot(command, slot)] 

1583 else: 

1584 policy_callback = _REQUEST_POLICY_CALLBACKS[request_policy] 

1585 if policy_callback is None: 

1586 # A keyed policy. A MULTI_SHARD command routed here was not split - its 

1587 # keys share a slot, or are not at fixed positions - so it is routed by 

1588 # its keys as a whole. 

1589 nodes = await self.get_nodes_from_slot(command, *args) 

1590 else: 

1591 nodes = await policy_callback(self, command, *args) 

1592 

1593 if command.lower() == "ft.aggregate": 

1594 self._aggregate_nodes = nodes 

1595 

1596 return nodes 

1597 

1598 async def _determine_slot(self, command: str, *args: Any) -> int: 

1599 if self.command_flags.get(command.upper()) == SLOT_ID: 

1600 # The command contains the slot ID 

1601 return int(args[0]) 

1602 

1603 # Get the keys in the command 

1604 

1605 # EVAL and EVALSHA are common enough that it's wasteful to go to the 

1606 # redis server to parse the keys. Besides, there is a bug in redis<7.0 

1607 # where `self._get_command_keys()` fails anyway. So, we special case 

1608 # EVAL/EVALSHA, and their read-only variants, which take the same arguments. 

1609 # - issue: https://github.com/redis/redis/issues/9493 

1610 # - fix: https://github.com/redis/redis/pull/9733 

1611 if command.upper() in _EVAL_COMMANDS: 

1612 # command syntax: EVAL "script body" num_keys ... 

1613 if len(args) < 2: 

1614 raise RedisClusterException( 

1615 "Invalid args in command: " 

1616 f"{truncate_text(command_text((command, *args)))}" 

1617 ) 

1618 keys = args[2 : 2 + int(args[1])] 

1619 # if there are 0 keys, that means the script can be run on any node 

1620 # so we can just return a random slot 

1621 if not keys: 

1622 return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS) 

1623 else: 

1624 keys = await self.commands_parser.get_keys(command, *args) 

1625 if not keys: 

1626 # FCALL can call a function with 0 keys, that means the function 

1627 # can be run on any node so we can just return a random slot 

1628 if command.upper() in ("FCALL", "FCALL_RO"): 

1629 return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS) 

1630 raise RedisClusterException( 

1631 "No way to dispatch this command to Redis Cluster. " 

1632 "Missing key.\nYou can execute the command by specifying " 

1633 "target nodes.\nCommand: " 

1634 f"{truncate_text(command_text((command, *args)))}" 

1635 ) 

1636 

1637 # single key command 

1638 if len(keys) == 1: 

1639 return self.keyslot(keys[0]) 

1640 

1641 # multi-key command; we need to make sure all keys are mapped to 

1642 # the same slot 

1643 slots = {self.keyslot(key) for key in keys} 

1644 if len(slots) != 1: 

1645 raise RedisClusterException( 

1646 f"{command} - all keys must map to the same key slot" 

1647 ) 

1648 

1649 return slots.pop() 

1650 

1651 def _is_node_flag(self, target_nodes: Any) -> bool: 

1652 return isinstance(target_nodes, str) and target_nodes in self.node_flags 

1653 

1654 def _parse_target_nodes(self, target_nodes: Any) -> List["ClusterNode"]: 

1655 if isinstance(target_nodes, list): 

1656 nodes = target_nodes 

1657 elif isinstance(target_nodes, ClusterNode): 

1658 # Supports passing a single ClusterNode as a variable 

1659 nodes = [target_nodes] 

1660 elif isinstance(target_nodes, dict): 

1661 # Supports dictionaries of the format {node_name: node}. 

1662 # It enables to execute commands with multi nodes as follows: 

1663 # rc.cluster_save_config(rc.get_primaries()) 

1664 nodes = list(target_nodes.values()) 

1665 else: 

1666 raise TypeError( 

1667 "target_nodes type can be one of the following: " 

1668 "node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES)," 

1669 "ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. " 

1670 f"The passed type is {type(target_nodes)}" 

1671 ) 

1672 return nodes 

1673 

1674 async def _record_error_metric( 

1675 self, 

1676 error: Exception, 

1677 connection: Union[Connection, "ClusterNode"], 

1678 is_internal: bool = True, 

1679 retry_attempts: Optional[int] = None, 

1680 ): 

1681 """ 

1682 Records error count metric directly. 

1683 Accepts either a Connection or ClusterNode object. 

1684 """ 

1685 await record_error_count( 

1686 server_address=connection.host, 

1687 server_port=connection.port, 

1688 network_peer_address=connection.host, 

1689 network_peer_port=connection.port, 

1690 error_type=error, 

1691 retry_attempts=retry_attempts if retry_attempts is not None else 0, 

1692 is_internal=is_internal, 

1693 ) 

1694 

1695 async def _record_command_metric( 

1696 self, 

1697 command_name: str, 

1698 duration_seconds: float, 

1699 connection: Union[Connection, "ClusterNode"], 

1700 error: Optional[Exception] = None, 

1701 ): 

1702 """ 

1703 Records operation duration metric directly. 

1704 Accepts either a Connection or ClusterNode object. 

1705 """ 

1706 # Connection has db attribute, ClusterNode has connection_kwargs 

1707 if hasattr(connection, "db"): 

1708 db = connection.db 

1709 else: 

1710 db = connection.connection_kwargs.get("db", 0) 

1711 await record_operation_duration( 

1712 command_name=command_name, 

1713 duration_seconds=duration_seconds, 

1714 server_address=connection.host, 

1715 server_port=connection.port, 

1716 db_namespace=str(db) if db is not None else None, 

1717 error=error, 

1718 ) 

1719 

1720 async def execute_command(self, *args: EncodableT, **kwargs: Any) -> Any: 

1721 """ 

1722 Execute a raw command on the appropriate cluster node or target_nodes. 

1723 

1724 It will retry the command as specified by the retries property of 

1725 the :attr:`retry` & then raise an exception. 

1726 

1727 :param args: 

1728 | Raw command args 

1729 :param kwargs: 

1730 

1731 - target_nodes: :attr:`NODE_FLAGS` or :class:`~.ClusterNode` 

1732 or List[:class:`~.ClusterNode`] or Dict[Any, :class:`~.ClusterNode`] 

1733 - Rest of the kwargs are passed to the Redis connection 

1734 

1735 :raises RedisClusterException: if target_nodes is not provided & the command 

1736 can't be mapped to a slot 

1737 """ 

1738 target_nodes = [] 

1739 target_nodes_specified = False 

1740 retry_attempts = self.retry.get_retries() 

1741 

1742 passed_targets = kwargs.pop("target_nodes", None) 

1743 node_flag = False 

1744 if passed_targets is not None: 

1745 node_flag = self._is_node_flag(passed_targets) 

1746 if not node_flag and not ( 

1747 isinstance(passed_targets, (list, dict, str)) and not passed_targets 

1748 ): 

1749 target_nodes = self._parse_target_nodes(passed_targets) 

1750 target_nodes_specified = True 

1751 retry_attempts = 0 

1752 

1753 # A nodes flag picks the targets too: ``_determine_nodes`` resolves it, and the 

1754 # command's own aggregation must not apply to the replies 

1755 command, command_policies, slot = await self._resolve_command_policies( 

1756 *args, target_nodes_specified=target_nodes_specified or node_flag 

1757 ) 

1758 

1759 # Add one for the first execution 

1760 execute_attempts = 1 + retry_attempts 

1761 failure_count = 0 

1762 

1763 # Start timing for observability 

1764 start_time = time.monotonic() 

1765 

1766 # The error the previous attempt failed with, and when the last refresh 

1767 # had ended by then: a refresh since that reached no node ends the 

1768 # retries (see NodesManager._error_instead_of_retry) 

1769 last_error: Optional[Exception] = None 

1770 last_refresh_at: Optional[float] = None 

1771 

1772 # Whether the attempt targets the default node alone: only an attempt 

1773 # that failed on it replaces it, not one made while a refresh another 

1774 # error asked for is pending 

1775 is_default_node = False 

1776 

1777 # A MULTI_SHARD command whose keys span several slots is sent in one pipeline, 

1778 # which retries the failed slots itself, so it is not retried here as well. 

1779 splits = None 

1780 if ( 

1781 not target_nodes_specified 

1782 and command_policies.request_policy == RequestPolicy.MULTI_SHARD 

1783 ): 

1784 if self._initialize_due(): 

1785 # The command metadata the split reads arrives with the topology 

1786 await self.initialize() 

1787 splits = self._split_multi_shard_command(*args) 

1788 if splits is not None and len(splits) > 1: 

1789 return await self._execute_multi_shard_command( 

1790 command, splits, command_policies.response_policy, **kwargs 

1791 ) 

1792 

1793 # The replies of the nodes a command sent to several nodes already got, kept 

1794 # across the attempts so a retry asks only the nodes that have not answered: 

1795 # asking a node again would run a write twice, and change what a summed reply 

1796 # counts. Allocated only for such a command: one sent to one node is retried 

1797 # whole. 

1798 replies: Optional[Dict[str, Any]] = None 

1799 

1800 for _ in range(execute_attempts): 

1801 if self._initialize_due(): 

1802 # The node that failed is kept on the nodes manager, so the 

1803 # refresh tries it last even when it runs on a later command 

1804 await self.initialize() 

1805 if last_error is not None: 

1806 outage_error = self.nodes_manager._error_instead_of_retry( 

1807 last_error, last_refresh_at 

1808 ) 

1809 if outage_error is not None: 

1810 raise outage_error 

1811 try: 

1812 if not target_nodes_specified: 

1813 if splits is None: 

1814 # Only the first attempt reuses the slot. A retry computes it 

1815 # again, as a command without keys gets a new random slot on 

1816 # each attempt - also after an attempt that found no node for it 

1817 attempt_slot, slot = slot, None 

1818 # Determine the nodes to execute the command on 

1819 target_nodes = await self._determine_nodes( 

1820 *args, 

1821 request_policy=command_policies.request_policy, 

1822 node_flag=passed_targets, 

1823 slot=attempt_slot, 

1824 ) 

1825 else: 

1826 # One slot: sent as it is, to the node of the slot the split 

1827 # already computed 

1828 target_nodes = [ 

1829 await self._get_node_from_slot(command, splits[0][0]) 

1830 ] 

1831 if not target_nodes: 

1832 raise RedisClusterException( 

1833 "No targets were found to execute " 

1834 f"{truncate_text(command_text(args))} command on" 

1835 ) 

1836 is_default_node = ( 

1837 len(target_nodes) == 1 

1838 and target_nodes[0] == self.get_default_node() 

1839 ) 

1840 

1841 if len(target_nodes) == 1: 

1842 # Return the processed result 

1843 ret = await self._execute_command(target_nodes[0], *args, **kwargs) 

1844 res = {target_nodes[0].name: ret} 

1845 else: 

1846 # Every node is asked: the one that succeeds is not known up front. 

1847 # SCRIPT KILL succeeds only on the shard running the script. A node 

1848 # that answered on an earlier attempt is not asked again. 

1849 if replies is None: 

1850 replies = {} 

1851 asked = [node for node in target_nodes if node.name not in replies] 

1852 # Every task settles before an error is raised, so a retry never 

1853 # asks a node again while its task is still running the command 

1854 values = await asyncio.gather( 

1855 *( 

1856 asyncio.create_task( 

1857 self._execute_command(node, *args, **kwargs) 

1858 ) 

1859 for node in asked 

1860 ), 

1861 return_exceptions=True, 

1862 ) 

1863 res = { 

1864 node.name: replies[node.name] 

1865 for node in target_nodes 

1866 if node.name in replies 

1867 } 

1868 for node, value in zip(asked, values): 

1869 res[node.name] = value 

1870 if not isinstance(value, BaseException): 

1871 replies[node.name] = value 

1872 # Any error fails the command, except under ONE_SUCCEEDED, which 

1873 # fails only when no node succeeded 

1874 res, error = _split_successes_and_failure( 

1875 res, command_policies.response_policy 

1876 ) 

1877 if error is not None: 

1878 raise error 

1879 return self._process_result( 

1880 command, 

1881 res, 

1882 response_policy=command_policies.response_policy, 

1883 **kwargs, 

1884 ) 

1885 except Exception as e: 

1886 if retry_attempts > 0 and ( 

1887 type(e) in self.__class__.ERRORS_ALLOW_RETRY 

1888 or getattr(e, "demoted_primary", False) 

1889 ): 

1890 if is_default_node: 

1891 # Replace the default cluster node 

1892 self.replace_default_node() 

1893 # The nodes and slots cache were should be reinitialized. 

1894 # Try again with the new cluster setup. 

1895 retry_attempts -= 1 

1896 failure_count += 1 

1897 last_error = e 

1898 last_refresh_at = self.nodes_manager._last_refresh_at 

1899 

1900 if hasattr(e, "connection"): 

1901 # ``args[0]``, not the resolved ``command``: every other metric in 

1902 # this class - including the per-command one ``_execute_command`` 

1903 # records on success - names the command the caller spelled. Using 

1904 # the routed name only here would report one command under two 

1905 # names depending on whether it was retried. 

1906 await self._record_command_metric( 

1907 command_name=args[0], 

1908 duration_seconds=time.monotonic() - start_time, 

1909 connection=e.connection, 

1910 error=e, 

1911 ) 

1912 await self._record_error_metric( 

1913 error=e, 

1914 connection=e.connection, 

1915 retry_attempts=failure_count, 

1916 ) 

1917 # Space the attempts out as the retry backoff says; the 

1918 # refresh the error asked for runs after this delay 

1919 delay = self._retry_backoff_delay(self.retry, failure_count) 

1920 if delay > 0: 

1921 await asyncio.sleep(delay) 

1922 continue 

1923 else: 

1924 # raise the exception 

1925 if hasattr(e, "connection"): 

1926 await self._record_error_metric( 

1927 error=e, 

1928 connection=e.connection, 

1929 retry_attempts=failure_count, 

1930 is_internal=False, 

1931 ) 

1932 raise _error_to_raise( 

1933 self.nodes_manager._last_refresh_unreachable_args, e 

1934 ) 

1935 

1936 def _process_result( 

1937 self, 

1938 command: str, 

1939 res: Dict[str, Any], 

1940 response_policy: ResponsePolicy, 

1941 **kwargs: Any, 

1942 ) -> Any: 

1943 """ 

1944 Process the result of the executed command. 

1945 The function would return a dict or a single value. 

1946 

1947 `res` should be in the following format: 

1948 Dict<node_name, command_result> 

1949 

1950 A command's own result callback merges the replies when it has one. Otherwise a 

1951 single reply is returned as it is, and the replies of several nodes are folded by 

1952 the command's response policy. 

1953 """ 

1954 if command in self.result_callbacks: 

1955 return self.result_callbacks[command](command, res, **kwargs) 

1956 elif len(res) == 1: 

1957 # When we execute the command on a single node, we can 

1958 # remove the dictionary and return a single response 

1959 return list(res.values())[0] 

1960 elif response_policy == ResponsePolicy.SPECIAL: 

1961 special = _SPECIAL_RESPONSE_CALLBACKS.get(command) 

1962 if special is not None: 

1963 return special(res) 

1964 

1965 return _RESPONSE_POLICY_CALLBACKS[response_policy](res) 

1966 

1967 async def _execute_command( 

1968 self, target_node: "ClusterNode", *args: Union[KeyT, EncodableT], **kwargs: Any 

1969 ) -> Any: 

1970 asking = moved = False 

1971 redirect_addr = None 

1972 ttl = self.RedisClusterRequestTTL 

1973 command = args[0] 

1974 start_time = time.monotonic() 

1975 

1976 while ttl > 0: 

1977 ttl -= 1 

1978 ask_himport = False 

1979 try: 

1980 if asking: 

1981 target_node = self.get_node(*redirect_addr) 

1982 if parse_himport_set_args(args) is not None: 

1983 # ASKING must sit on the same connection as the SET, 

1984 # immediately before it. HIMPORT SET's own executor folds 

1985 # ASKING into the SET's packed write after the session setup, 

1986 # so don't send it here as a separately pooled command. 

1987 ask_himport = True 

1988 else: 

1989 await target_node.execute_command("ASKING") 

1990 asking = False 

1991 elif moved: 

1992 # MOVED occurred and the slots cache was updated, 

1993 # refresh the target node 

1994 slot = await self._determine_slot(*args) 

1995 replica_safe = ( 

1996 self.read_from_replicas 

1997 or self.load_balancing_strategy is not None 

1998 ) and await self._is_replica_safe(args[0]) 

1999 target_node = self.nodes_manager.get_node_from_slot( 

2000 slot, 

2001 replica_safe, 

2002 self.load_balancing_strategy if replica_safe else None, 

2003 ) 

2004 moved = False 

2005 

2006 response = await target_node.execute_command( 

2007 *args, asking=ask_himport, **kwargs 

2008 ) 

2009 await self._record_command_metric( 

2010 command_name=command, 

2011 duration_seconds=time.monotonic() - start_time, 

2012 connection=target_node, 

2013 ) 

2014 return response 

2015 except BusyLoadingError as e: 

2016 e.connection = target_node 

2017 await self._record_command_metric( 

2018 command_name=command, 

2019 duration_seconds=time.monotonic() - start_time, 

2020 connection=target_node, 

2021 error=e, 

2022 ) 

2023 raise 

2024 except AuthenticationError as e: 

2025 # Rejected or expired credentials are not a node failure: 

2026 # recycling the node's connections or refreshing the topology 

2027 # cannot repair them, so re-raise without either. 

2028 e.connection = target_node 

2029 await self._record_command_metric( 

2030 command_name=command, 

2031 duration_seconds=time.monotonic() - start_time, 

2032 connection=target_node, 

2033 error=e, 

2034 ) 

2035 raise 

2036 except MaxConnectionsError as e: 

2037 # MaxConnectionsError indicates client-side resource exhaustion 

2038 # (too many connections in the pool), not a node failure. 

2039 # Don't treat this as a node failure - just re-raise the error 

2040 # without reinitializing the cluster. 

2041 e.connection = target_node 

2042 await self._record_command_metric( 

2043 command_name=command, 

2044 duration_seconds=time.monotonic() - start_time, 

2045 connection=target_node, 

2046 error=e, 

2047 ) 

2048 raise 

2049 except MaxClientsReachedError as e: 

2050 # The server refused a new connection because it is at its 

2051 # maxclients limit: server-side capacity, not a node failure. 

2052 # Recycling the node's working connections or refreshing the 

2053 # topology would only open more connections the server refuses, 

2054 # so re-raise without either. The connection that read the error 

2055 # has already disconnected itself: read_response drops the 

2056 # connection on any error it raises. 

2057 e.connection = target_node 

2058 await self._record_command_metric( 

2059 command_name=command, 

2060 duration_seconds=time.monotonic() - start_time, 

2061 connection=target_node, 

2062 error=e, 

2063 ) 

2064 raise 

2065 except (ConnectionError, TimeoutError) as e: 

2066 if logger.isEnabledFor(logging.DEBUG): 

2067 # Log only the command name - argument values can carry 

2068 # secrets or user data. 

2069 args_log_str = safe_str(args[0]) 

2070 logger.debug( 

2071 f"{type(e).__name__} received for command {args_log_str}, " 

2072 f"on node {target_node.name}, error: {e}" 

2073 ) 

2074 # Connection retries are being handled in the node's 

2075 # Retry object. The failed connection has disconnected itself; 

2076 # the node's other connections are kept: one error, such as a 

2077 # refused connect, does not mean they are broken, and closing 

2078 # them all would reconnect every caller of a node that may be 

2079 # healthy. A free connection the server has closed is found and 

2080 # reconnected when it is acquired. 

2081 

2082 # Move the failed node to the end of the cached nodes. The 

2083 # refresh keeps that order, so it does not pick this node as the 

2084 # default node while it is still a primary. The order the 

2085 # refresh queries nodes in comes from last_failed_node_name 

2086 # below: it shuffles the startup nodes and tries this one last. 

2087 self.nodes_manager.move_node_to_end_of_cached_nodes(target_node.name) 

2088 e.last_failed_node_name = target_node.name 

2089 

2090 # Signal that reinitialization is needed 

2091 # The retry loop will handle initialize() AND replace_default_node() 

2092 self._request_refresh(last_failed_node_name=target_node.name) 

2093 e.connection = target_node 

2094 await self._record_command_metric( 

2095 command_name=command, 

2096 duration_seconds=time.monotonic() - start_time, 

2097 connection=target_node, 

2098 error=e, 

2099 ) 

2100 raise 

2101 except (ClusterDownError, SlotNotCoveredError) as e: 

2102 # ClusterDownError can occur during a failover and to get 

2103 # self-healed, we will try to reinitialize the cluster layout 

2104 # and retry executing the command 

2105 

2106 # SlotNotCoveredError can occur when the cluster is not fully 

2107 # initialized or can be temporary issue. 

2108 # We will try to reinitialize the cluster topology 

2109 # and retry executing the command 

2110 

2111 await asyncio.sleep(0.25) 

2112 # Refreshed here, in place and without closing the connections, 

2113 # not paced or asked for: this command raises the refresh error 

2114 # if it fails. Under the lock, as in initialize(), so aclose() 

2115 # waits for it instead of closing a client this refresh then 

2116 # reopens. A client closed meanwhile is left to the next 

2117 # attempt's initialize(), and a refresh another task completed 

2118 # meanwhile already answers this error. 

2119 epoch = self.nodes_manager._epoch 

2120 async with self._lock: 

2121 if self._topology_ready and self.nodes_manager._epoch == epoch: 

2122 await self._refresh_topology() 

2123 self._initialize = False 

2124 e.connection = target_node 

2125 await self._record_command_metric( 

2126 command_name=command, 

2127 duration_seconds=time.monotonic() - start_time, 

2128 connection=target_node, 

2129 error=e, 

2130 ) 

2131 raise 

2132 except MovedError as e: 

2133 if logger.isEnabledFor(logging.DEBUG): 

2134 # Log only the command name - argument values can carry 

2135 # secrets or user data. 

2136 args_log_str = safe_str(args[0]) 

2137 logger.debug( 

2138 f"MOVED error received for command {args_log_str}, " 

2139 f"on node {target_node.name}, error: {e}" 

2140 ) 

2141 _fill_missing_redirect_host(e, target_node.host) 

2142 # Patch the slots/nodes cache with the redirected node and try 

2143 # again. Every 'reinitialize_steps' MOVED errors, also ask for a 

2144 # refresh of the whole topology, run by the next attempt of any 

2145 # command once due: the redirect needs only this slot, which the 

2146 # patch already points to the node that owns it. 

2147 # 'reinitialize_steps' counter will increase faster when 

2148 # the same client object is shared between multiple tasks. To 

2149 # reduce the frequency you can set this variable in the 

2150 # RedisCluster constructor. 

2151 self.reinitialize_counter += 1 

2152 await self.nodes_manager.move_slot(e) 

2153 if _should_request_refresh( 

2154 self.reinitialize_steps, self.reinitialize_counter 

2155 ): 

2156 # The refresh also queries the node the error pointed to 

2157 self._request_refresh( 

2158 additional_startup_nodes_info=[ 

2159 self.nodes_manager.remap_host_port(e.host, e.port) 

2160 ] 

2161 ) 

2162 # Reset the counter 

2163 self.reinitialize_counter = 0 

2164 moved = True 

2165 await self._record_command_metric( 

2166 command_name=command, 

2167 duration_seconds=time.monotonic() - start_time, 

2168 connection=target_node, 

2169 error=e, 

2170 ) 

2171 await self._record_error_metric( 

2172 error=e, 

2173 connection=target_node, 

2174 ) 

2175 except AskError as e: 

2176 if logger.isEnabledFor(logging.DEBUG): 

2177 # Log only the command name - argument values can carry 

2178 # secrets or user data. 

2179 args_log_str = safe_str(args[0]) 

2180 logger.debug( 

2181 f"ASK error received for command {args_log_str}, " 

2182 f"on node {target_node.name}, error: {e}" 

2183 ) 

2184 _fill_missing_redirect_host(e, target_node.host) 

2185 redirect_addr = self.nodes_manager.remap_host_port(e.host, e.port) 

2186 asking = True 

2187 await self._record_command_metric( 

2188 command_name=command, 

2189 duration_seconds=time.monotonic() - start_time, 

2190 connection=target_node, 

2191 error=e, 

2192 ) 

2193 await self._record_error_metric( 

2194 error=e, 

2195 connection=target_node, 

2196 ) 

2197 except TryAgainError as e: 

2198 if logger.isEnabledFor(logging.DEBUG): 

2199 # Log only the command name - argument values can carry 

2200 # secrets or user data. 

2201 args_log_str = safe_str(args[0]) 

2202 logger.debug( 

2203 f"TRYAGAIN error received for command {args_log_str}, " 

2204 f"on node {target_node.name}" 

2205 ) 

2206 if ttl < self.RedisClusterRequestTTL / 2: 

2207 await asyncio.sleep(0.05) 

2208 await self._record_command_metric( 

2209 command_name=command, 

2210 duration_seconds=time.monotonic() - start_time, 

2211 connection=target_node, 

2212 error=e, 

2213 ) 

2214 await self._record_error_metric( 

2215 error=e, 

2216 connection=target_node, 

2217 ) 

2218 except ResponseError as e: 

2219 if _is_demoted_primary(e, target_node): 

2220 e.demoted_primary = True 

2221 # Ask for a topology refresh, run by the next attempt, of 

2222 # any command, once due; the caller retries this one 

2223 self._request_refresh() 

2224 e.connection = target_node 

2225 await self._record_command_metric( 

2226 command_name=command, 

2227 duration_seconds=time.monotonic() - start_time, 

2228 connection=target_node, 

2229 error=e, 

2230 ) 

2231 raise 

2232 except Exception as e: 

2233 e.connection = target_node 

2234 await self._record_command_metric( 

2235 command_name=command, 

2236 duration_seconds=time.monotonic() - start_time, 

2237 connection=target_node, 

2238 error=e, 

2239 ) 

2240 raise 

2241 

2242 e = ClusterError("TTL exhausted.") 

2243 e.connection = target_node 

2244 await self._record_command_metric( 

2245 command_name=command, 

2246 duration_seconds=time.monotonic() - start_time, 

2247 connection=target_node, 

2248 error=e, 

2249 ) 

2250 raise e 

2251 

2252 def pipeline( 

2253 self, transaction: Optional[Any] = None, shard_hint: Optional[Any] = None 

2254 ) -> "ClusterPipeline": 

2255 """ 

2256 Create & return a new :class:`~.ClusterPipeline` object. 

2257 

2258 Cluster implementation of pipeline does not support transaction or shard_hint. 

2259 

2260 :raises RedisClusterException: if transaction or shard_hint are truthy values 

2261 """ 

2262 if shard_hint: 

2263 raise RedisClusterException("shard_hint is deprecated in cluster mode") 

2264 

2265 return ClusterPipeline(self, transaction) 

2266 

2267 def pubsub( 

2268 self, 

2269 node: Optional["ClusterNode"] = None, 

2270 host: Optional[str] = None, 

2271 port: Optional[int] = None, 

2272 **kwargs: Any, 

2273 ) -> "ClusterPubSub": 

2274 """ 

2275 Create and return a ClusterPubSub instance. 

2276 

2277 Allows passing a ClusterNode, or host&port, to get a pubsub instance 

2278 connected to the specified node 

2279 

2280 :param node: ClusterNode to connect to 

2281 :param host: Host of the node to connect to 

2282 :param port: Port of the node to connect to 

2283 :param kwargs: Additional keyword arguments 

2284 :return: ClusterPubSub instance 

2285 """ 

2286 return ClusterPubSub(self, node=node, host=host, port=port, **kwargs) 

2287 

2288 def keyspace_notifications( 

2289 self, 

2290 key_prefix: Union[str, bytes, None] = None, 

2291 ignore_subscribe_messages: bool = True, 

2292 ) -> "AsyncClusterKeyspaceNotifications": 

2293 """ 

2294 Return an 

2295 :class:`~redis.asyncio.keyspace_notifications.AsyncClusterKeyspaceNotifications` 

2296 object for subscribing to keyspace and keyevent notifications across 

2297 all primary nodes in the cluster. 

2298 

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

2300 via the ``notify-keyspace-events`` configuration option. 

2301 

2302 Args: 

2303 key_prefix: Optional prefix to filter and strip from keys in 

2304 notifications. 

2305 ignore_subscribe_messages: If True, subscribe/unsubscribe 

2306 confirmations are not returned by 

2307 get_message/listen. 

2308 """ 

2309 from redis.asyncio.keyspace_notifications import ( 

2310 AsyncClusterKeyspaceNotifications, 

2311 ) 

2312 

2313 return AsyncClusterKeyspaceNotifications( 

2314 self, 

2315 key_prefix=key_prefix, 

2316 ignore_subscribe_messages=ignore_subscribe_messages, 

2317 ) 

2318 

2319 def lock( 

2320 self, 

2321 name: KeyT, 

2322 timeout: Optional[float] = None, 

2323 sleep: float = 0.1, 

2324 blocking: bool = True, 

2325 blocking_timeout: Optional[float] = None, 

2326 lock_class: Optional[Type[Lock]] = None, 

2327 thread_local: bool = True, 

2328 raise_on_release_error: bool = True, 

2329 ) -> Lock: 

2330 """ 

2331 Return a new Lock object using key ``name`` that mimics 

2332 the behavior of threading.Lock. 

2333 

2334 If specified, ``timeout`` indicates a maximum life for the lock. 

2335 By default, it will remain locked until release() is called. 

2336 

2337 ``sleep`` indicates the amount of time to sleep per loop iteration 

2338 when the lock is in blocking mode and another client is currently 

2339 holding the lock. 

2340 

2341 ``blocking`` indicates whether calling ``acquire`` should block until 

2342 the lock has been acquired or to fail immediately, causing ``acquire`` 

2343 to return False and the lock not being acquired. Defaults to True. 

2344 Note this value can be overridden by passing a ``blocking`` 

2345 argument to ``acquire``. 

2346 

2347 ``blocking_timeout`` indicates the maximum amount of time in seconds to 

2348 spend trying to acquire the lock. A value of ``None`` indicates 

2349 continue trying forever. ``blocking_timeout`` can be specified as a 

2350 float or integer, both representing the number of seconds to wait. 

2351 

2352 ``lock_class`` forces the specified lock implementation. Note that as 

2353 of redis-py 3.0, the only lock class we implement is ``Lock`` (which is 

2354 a Lua-based lock). So, it's unlikely you'll need this parameter, unless 

2355 you have created your own custom lock class. 

2356 

2357 ``thread_local`` indicates whether the lock token is placed in 

2358 thread-local storage. By default, the token is placed in thread local 

2359 storage so that a thread only sees its token, not a token set by 

2360 another thread. Consider the following timeline: 

2361 

2362 time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds. 

2363 thread-1 sets the token to "abc" 

2364 time: 1, thread-2 blocks trying to acquire `my-lock` using the 

2365 Lock instance. 

2366 time: 5, thread-1 has not yet completed. redis expires the lock 

2367 key. 

2368 time: 5, thread-2 acquired `my-lock` now that it's available. 

2369 thread-2 sets the token to "xyz" 

2370 time: 6, thread-1 finishes its work and calls release(). if the 

2371 token is *not* stored in thread local storage, then 

2372 thread-1 would see the token value as "xyz" and would be 

2373 able to successfully release the thread-2's lock. 

2374 

2375 ``raise_on_release_error`` indicates whether to raise an exception when 

2376 the lock is no longer owned when exiting the context manager. By default, 

2377 this is True, meaning an exception will be raised. If False, the warning 

2378 will be logged and the exception will be suppressed. 

2379 

2380 In some use cases it's necessary to disable thread local storage. For 

2381 example, if you have code where one thread acquires a lock and passes 

2382 that lock instance to a worker thread to release later. If thread 

2383 local storage isn't disabled in this case, the worker thread won't see 

2384 the token set by the thread that acquired the lock. Our assumption 

2385 is that these cases aren't common and as such default to using 

2386 thread local storage.""" 

2387 if lock_class is None: 

2388 lock_class = Lock 

2389 return lock_class( 

2390 self, 

2391 name, 

2392 timeout=timeout, 

2393 sleep=sleep, 

2394 blocking=blocking, 

2395 blocking_timeout=blocking_timeout, 

2396 thread_local=thread_local, 

2397 raise_on_release_error=raise_on_release_error, 

2398 ) 

2399 

2400 async def transaction( 

2401 self, func: Coroutine[None, "ClusterPipeline", Any], *watches, **kwargs 

2402 ): 

2403 """ 

2404 Convenience method for executing the callable `func` as a transaction 

2405 while watching all keys specified in `watches`. The 'func' callable 

2406 should expect a single argument which is a Pipeline object. 

2407 """ 

2408 shard_hint = kwargs.pop("shard_hint", None) 

2409 value_from_callable = kwargs.pop("value_from_callable", False) 

2410 watch_delay = kwargs.pop("watch_delay", None) 

2411 async with self.pipeline(True, shard_hint) as pipe: 

2412 while True: 

2413 try: 

2414 if watches: 

2415 await pipe.watch(*watches) 

2416 func_value = await func(pipe) 

2417 exec_value = await pipe.execute() 

2418 return func_value if value_from_callable else exec_value 

2419 except WatchError: 

2420 if watch_delay is not None and watch_delay > 0: 

2421 await asyncio.sleep(watch_delay) 

2422 continue 

2423 

2424 

2425class ClusterNode: 

2426 """ 

2427 Create a new ClusterNode. 

2428 

2429 Each ClusterNode manages multiple :class:`~redis.asyncio.connection.Connection` 

2430 objects for the (host, port). 

2431 """ 

2432 

2433 __slots__ = ( 

2434 "_background_tasks", 

2435 "_connections", 

2436 "_free", 

2437 "_lock", 

2438 "_event_dispatcher", 

2439 "connection_class", 

2440 "connection_kwargs", 

2441 "host", 

2442 "max_connections", 

2443 "name", 

2444 "port", 

2445 "response_callbacks", 

2446 "server_type", 

2447 ) 

2448 

2449 def __init__( 

2450 self, 

2451 host: str, 

2452 port: Union[str, int], 

2453 server_type: Optional[str] = None, 

2454 *, 

2455 max_connections: int = 100, 

2456 connection_class: Type[Connection] = Connection, 

2457 **connection_kwargs: Any, 

2458 ) -> None: 

2459 if host == "localhost": 

2460 host = _resolve_localhost() 

2461 

2462 connection_kwargs["host"] = host 

2463 connection_kwargs["port"] = port 

2464 self.host = host 

2465 self.port = port 

2466 self.name = get_node_name(host, port) 

2467 self.server_type = server_type 

2468 

2469 self.max_connections = max_connections 

2470 self.connection_class = connection_class 

2471 self.connection_kwargs = connection_kwargs 

2472 self.response_callbacks = connection_kwargs.pop("response_callbacks", {}) 

2473 

2474 self._connections: List[Connection] = [] 

2475 self._free: Deque[Connection] = collections.deque(maxlen=self.max_connections) 

2476 self._background_tasks: Set[asyncio.Task] = set() 

2477 self._event_dispatcher = self.connection_kwargs.get("event_dispatcher", None) 

2478 if self._event_dispatcher is None: 

2479 self._event_dispatcher = EventDispatcher() 

2480 

2481 def __repr__(self) -> str: 

2482 return ( 

2483 f"[host={self.host}, port={self.port}, " 

2484 f"name={self.name}, server_type={self.server_type}]" 

2485 ) 

2486 

2487 def __eq__(self, obj: Any) -> bool: 

2488 return isinstance(obj, ClusterNode) and obj.name == self.name 

2489 

2490 def __hash__(self) -> int: 

2491 return hash(self.name) 

2492 

2493 _DEL_MESSAGE = "Unclosed ClusterNode object" 

2494 

2495 def __del__( 

2496 self, 

2497 _warn: Any = warnings.warn, 

2498 _grl: Any = asyncio.get_running_loop, 

2499 ) -> None: 

2500 for connection in self._connections: 

2501 if connection.is_connected: 

2502 _warn(f"{self._DEL_MESSAGE} {self!r}", ResourceWarning, source=self) 

2503 

2504 try: 

2505 context = {"client": self, "message": self._DEL_MESSAGE} 

2506 _grl().call_exception_handler(context) 

2507 except RuntimeError: 

2508 pass 

2509 break 

2510 

2511 async def disconnect(self) -> None: 

2512 ret = await asyncio.gather( 

2513 *( 

2514 asyncio.create_task(connection.disconnect()) 

2515 for connection in self._connections 

2516 ), 

2517 return_exceptions=True, 

2518 ) 

2519 exc = next((res for res in ret if isinstance(res, BaseException)), None) 

2520 if exc: 

2521 raise exc 

2522 

2523 def acquire_connection(self) -> Connection: 

2524 try: 

2525 return self._free.popleft() 

2526 except IndexError: 

2527 if len(self._connections) < self.max_connections: 

2528 # We are configuring the connection pool not to retry 

2529 # connections on lower level clients to avoid retrying 

2530 # connections to nodes that are not reachable 

2531 # and to avoid blocking the connection pool. 

2532 # The only error that will have some handling in the lower 

2533 # level clients is ConnectionError which will trigger disconnection 

2534 # of the socket. 

2535 # The retries will be handled on cluster client level 

2536 # where we will have proper handling of the cluster topology 

2537 retry = Retry( 

2538 backoff=NoBackoff(), 

2539 retries=0, 

2540 supported_errors=(ConnectionError,), 

2541 ) 

2542 connection_kwargs = self.connection_kwargs.copy() 

2543 connection_kwargs["retry"] = retry 

2544 connection = self.connection_class(**connection_kwargs) 

2545 self._connections.append(connection) 

2546 return connection 

2547 

2548 raise MaxConnectionsError() 

2549 

2550 async def disconnect_if_needed(self, connection: Connection) -> None: 

2551 """ 

2552 Disconnect a connection if it's marked for reconnect. 

2553 This implements lazy disconnection to avoid race conditions. 

2554 The connection will auto-reconnect on next use. 

2555 

2556 The old socket is closed without waiting for the close to finish. The 

2557 caller never needs it again, so a slow close must not fail the command, 

2558 and after a reply was read it must not turn a finished command into a 

2559 retried one. 

2560 """ 

2561 if connection.should_reconnect(): 

2562 # Render the connection before disconnecting: extract_connection_details() 

2563 # reads the local port and the in-flight read deadline off the transport, so 

2564 # after disconnect() it can only report "not connected". This line is what 

2565 # records the maintenance state and relaxed timeout at the moment they are 

2566 # discarded, so a maintenance-driven recycle is attributable in the logs. 

2567 if logger.isEnabledFor(logging.DEBUG): 

2568 logger.debug( 

2569 "Disconnecting acquired connection marked for reconnect: " 

2570 f"{connection}, {connection.extract_connection_details()}" 

2571 ) 

2572 await connection.disconnect(nowait=True) 

2573 

2574 async def _prepare_acquired_connection(self, connection: Connection) -> None: 

2575 """ 

2576 Ensure a connection just taken from the free queue is ready for the send command flow. 

2577 

2578 A connection marked for reconnect is disconnected. A connected one is 

2579 checked the way ``ConnectionPool.ensure_connection`` checks it: 

2580 ``can_read`` reports a stream the server has closed or reset from 

2581 ``at_eof()`` / ``exception()``, with no I/O, and pending data on an idle 

2582 connection means it is dirty, unless it is push notifications to apply. 

2583 A dead or dirty connection is disconnected and connects again lazily on 

2584 the send, so only the connections that are broken get reconnected. 

2585 """ 

2586 if connection.should_reconnect(): 

2587 await self.disconnect_if_needed(connection) 

2588 return 

2589 if not connection.is_connected: 

2590 return 

2591 try: 

2592 if await connection.can_read(): 

2593 maint_notifications_config = self.connection_kwargs.get( 

2594 "maint_notifications_config" 

2595 ) 

2596 if maint_notifications_config and maint_notifications_config.enabled: 

2597 await connection.handle_pending_push_notifications() 

2598 else: 

2599 raise ConnectionError("Connection has data") 

2600 except (ConnectionError, TimeoutError, OSError) as e: 

2601 logger.debug( 

2602 "Disconnecting acquired connection that is not ready: %s, %r", 

2603 connection, 

2604 e, 

2605 ) 

2606 # The socket is dead or dirty, so there is no clean close to wait 

2607 # for, and a close that times out must not fail the caller 

2608 await connection.disconnect(nowait=True) 

2609 return 

2610 

2611 # The AUTH a token renewal deferred while the connection was in use, 

2612 # if any. A failure must not fail the command about to use the 

2613 # connection, so it is logged instead, and the token stays pending. 

2614 try: 

2615 await connection.re_auth() 

2616 except Exception as e: 

2617 _log_re_auth_failure(connection, e) 

2618 

2619 def release(self, connection: Connection) -> None: 

2620 """ 

2621 Release connection back to free queue. 

2622 If a connected connection is marked for reconnect, disconnect it before 

2623 returning it to the free queue. An already-closed connection can be 

2624 returned immediately after clearing its reconnect flag. 

2625 """ 

2626 if connection.should_reconnect(): 

2627 if connection.is_connected: 

2628 # Logged here rather than in _disconnect_and_release: that runs as a 

2629 # task after the fact, by which point extract_connection_details() 

2630 # may already have lost the transport it reads from. 

2631 if logger.isEnabledFor(logging.DEBUG): 

2632 logger.debug( 

2633 "Disconnecting released connection marked for reconnect: " 

2634 f"{connection}, {connection.extract_connection_details()}" 

2635 ) 

2636 task = asyncio.create_task(self._disconnect_and_release(connection)) 

2637 self._background_tasks.add(task) 

2638 task.add_done_callback(self._background_tasks.discard) 

2639 return 

2640 # It may have been re-marked while its own disconnect was in progress. 

2641 connection.reset_should_reconnect() 

2642 self._free.append(connection) 

2643 

2644 async def _disconnect_and_release(self, connection: Connection) -> None: 

2645 try: 

2646 await connection.disconnect() 

2647 except Exception as exc: 

2648 logger.debug( 

2649 "disconnecting released cluster connection failed: %r", 

2650 exc, 

2651 exc_info=True, 

2652 ) 

2653 try: 

2654 self._connections.remove(connection) 

2655 except ValueError: 

2656 pass 

2657 return 

2658 

2659 self._free.append(connection) 

2660 

2661 def get_encoder(self) -> Encoder: 

2662 """Return an :class:`Encoder` derived from this node's connection kwargs.""" 

2663 kwargs = self.connection_kwargs 

2664 encoder_class = kwargs.get("encoder_class", Encoder) 

2665 return encoder_class( 

2666 encoding=kwargs.get("encoding", "utf-8"), 

2667 encoding_errors=kwargs.get("encoding_errors", "strict"), 

2668 decode_responses=kwargs.get("decode_responses", False), 

2669 ) 

2670 

2671 def update_active_connections_for_reconnect(self) -> None: 

2672 """ 

2673 Mark all in-use (active) connections for reconnect. 

2674 In-use connections are those in _connections but not currently in _free. 

2675 They will be disconnected after their current operation completes. 

2676 """ 

2677 free_set = set(self._free) 

2678 for connection in self._connections: 

2679 if connection not in free_set: 

2680 connection.mark_for_reconnect() 

2681 

2682 async def disconnect_free_connections(self) -> None: 

2683 """ 

2684 Disconnect all free/idle connections in the pool. 

2685 This is useful after topology changes (e.g., failover) to clear 

2686 stale connection state like READONLY mode. 

2687 The connections remain in the pool and will reconnect on next use. 

2688 """ 

2689 if self._free: 

2690 # Take the connections out of _free while they close, so 

2691 # acquire_connection cannot hand one out mid-disconnect, and put 

2692 # them back behind any connection released meanwhile. 

2693 connections = tuple(self._free) 

2694 self._free.clear() 

2695 try: 

2696 await asyncio.gather( 

2697 *(connection.disconnect() for connection in connections), 

2698 return_exceptions=True, 

2699 ) 

2700 finally: 

2701 self._free.extend(connections) 

2702 

2703 async def parse_response( 

2704 self, connection: Connection, command: str, **kwargs: Any 

2705 ) -> Any: 

2706 try: 

2707 if NEVER_DECODE in kwargs: 

2708 response = await connection.read_response(disable_decoding=True) 

2709 kwargs.pop(NEVER_DECODE) 

2710 if command == "INFO": 

2711 response = decode_info(response, self.get_encoder()) 

2712 else: 

2713 response = await connection.read_response() 

2714 except ResponseError: 

2715 if EMPTY_RESPONSE in kwargs: 

2716 return kwargs[EMPTY_RESPONSE] 

2717 raise 

2718 

2719 if EMPTY_RESPONSE in kwargs: 

2720 kwargs.pop(EMPTY_RESPONSE) 

2721 

2722 # Remove keys entry, it needs only for cache. 

2723 kwargs.pop("keys", None) 

2724 

2725 # Return response 

2726 if connection._resp2_fallback: 

2727 callback = _get_response_callback( 

2728 self.response_callbacks, command, connection 

2729 ) 

2730 else: 

2731 callback = self.response_callbacks.get(command) 

2732 if callback is not None: 

2733 return callback(response, **kwargs) 

2734 

2735 return response 

2736 

2737 async def execute_command( 

2738 self, *args: Any, asking: bool = False, **kwargs: Any 

2739 ) -> Any: 

2740 # Acquire connection 

2741 connection = self.acquire_connection() 

2742 try: 

2743 # Disconnect a connection that is marked, dead or dirty; the send 

2744 # connects it again 

2745 await self._prepare_acquired_connection(connection) 

2746 

2747 # HIMPORT SET is the one command whose wire form depends on 

2748 # per-connection state: the fieldset must be PREPAREd on this 

2749 # connection first, and any fieldset discarded since this connection 

2750 # last reconciled must be dropped. Doing it here (rather than in 

2751 # RedisCluster.himport_set) reuses the caller's full retry, MOVED/ASK 

2752 # and disconnect-on-error handling for HIMPORT SET too. 

2753 # This per-command branch in the hot dispatch path is deliberate and has 

2754 # no cleaner alternative: this is the only seam where the concrete routed 

2755 # connection is known, and connection-scoped session setup can only happen 

2756 # once that connection is chosen. The overhead is one comparison per 

2757 # command. 

2758 # On an ASK redirect ``asking`` is passed here rather than sent as a 

2759 # separate ASKING command so the allowance sits on this same connection, 

2760 # folded into the SET's own write immediately before the SET. 

2761 himport_set = parse_himport_set_args(args) 

2762 if himport_set is not None: 

2763 # HIMPORT SET in the joined ("HIMPORT SET", key, ...) or split 

2764 # ("HIMPORT", "SET", key, ...) raw form; operands at the right 

2765 # offsets. Too few operands returns None and falls through to the 

2766 # normal send path below so the server returns its arity error 

2767 # instead of a client-side IndexError. 

2768 key, fieldset_name, values = himport_set 

2769 return await self._himport_execute_set( 

2770 connection, key, fieldset_name, values, asking=asking 

2771 ) 

2772 

2773 # Execute command 

2774 await connection.send_packed_command(connection.pack_command(*args)) 

2775 

2776 # Read response 

2777 return await self.parse_response(connection, args[0], **kwargs) 

2778 finally: 

2779 try: 

2780 await self.disconnect_if_needed(connection) 

2781 finally: 

2782 # Release connection 

2783 self.release(connection) 

2784 

2785 async def _himport_reconcile_discards(self, conn: "Connection") -> None: 

2786 """Delegate to the shared async HIMPORT executor.""" 

2787 return await _himport_exec.reconcile_discards(self, conn) 

2788 

2789 async def _himport_prepare_and_set( 

2790 self, 

2791 conn: "Connection", 

2792 key: KeyT, 

2793 fieldset_name: str, 

2794 values: List, 

2795 fieldset, 

2796 asking: bool = False, 

2797 ) -> Any: 

2798 """Delegate to the shared async HIMPORT executor.""" 

2799 return await _himport_exec.prepare_and_set( 

2800 self, conn, key, fieldset_name, values, fieldset, asking=asking 

2801 ) 

2802 

2803 async def _himport_execute_set( 

2804 self, 

2805 conn: "Connection", 

2806 key: KeyT, 

2807 fieldset_name: str, 

2808 values: List, 

2809 asking: bool = False, 

2810 ) -> Any: 

2811 """Delegate to the shared async HIMPORT executor.""" 

2812 return await _himport_exec.execute_set( 

2813 self, conn, key, fieldset_name, values, asking=asking 

2814 ) 

2815 

2816 async def _himport_prepare_pipeline( 

2817 self, conn: "Connection", commands: List["PipelineCommand"] 

2818 ) -> None: 

2819 """Delegate to the shared async HIMPORT executor.""" 

2820 await _himport_exec.prepare_pipeline(self, conn, [cmd.args for cmd in commands]) 

2821 

2822 async def execute_pipeline(self, commands: List["PipelineCommand"]) -> bool: 

2823 # Acquire connection 

2824 connection = self.acquire_connection() 

2825 try: 

2826 # Disconnect a connection that is marked, dead or dirty; the send 

2827 # connects it again 

2828 await self._prepare_acquired_connection(connection) 

2829 

2830 # PREPARE fieldsets referenced by buffered HIMPORT SETs before the 

2831 # batched write (it bypasses the per-command lazy prepare path). 

2832 await self._himport_prepare_pipeline(connection, commands) 

2833 

2834 # Execute command 

2835 await connection.send_packed_command( 

2836 await _pack_pipeline_commands( 

2837 connection, [cmd.args for cmd in commands] 

2838 ) 

2839 ) 

2840 

2841 # Read responses 

2842 ret = False 

2843 may_yield = len(commands) >= _PIPELINE_YIELD_MIN_COMMANDS 

2844 for i, cmd in enumerate(commands): 

2845 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS: 

2846 await _yield_in_read_loop(connection) 

2847 try: 

2848 cmd.result = await self.parse_response( 

2849 connection, cmd.args[0], **cmd.kwargs 

2850 ) 

2851 except Exception as e: 

2852 cmd.result = e 

2853 ret = True 

2854 

2855 return ret 

2856 finally: 

2857 try: 

2858 await self.disconnect_if_needed(connection) 

2859 finally: 

2860 # Release connection 

2861 self.release(connection) 

2862 

2863 async def re_auth_callback(self, token: TokenInterface): 

2864 """ 

2865 Send AUTH with ``token`` on every connected free connection, and defer 

2866 it to the next acquire of every in-use one. 

2867 

2868 A free connection whose AUTH fails keeps ``token`` pending, like an 

2869 in-use one. The first error is raised after every connection is 

2870 handled, an ``AuthenticationError`` first. 

2871 """ 

2872 auth_error = None 

2873 first_error = None 

2874 tmp_queue = collections.deque() 

2875 # A connection created while this awaits authenticates with the 

2876 # current token in its handshake, so only these need it deferred 

2877 existing = list(self._connections) 

2878 try: 

2879 # Send every AUTH before reading any reply, so the free 

2880 # connections are out of the queue for about one round trip 

2881 # instead of one per connection 

2882 sent = [] 

2883 # Replies read so far, in send order 

2884 done = 0 

2885 while self._free: 

2886 conn = self._free.popleft() 

2887 tmp_queue.append(conn) 

2888 # This AUTH replaces any deferred one, so the prepare below 

2889 # does not send that one first 

2890 conn.set_re_auth_token(None) 

2891 if conn.should_reconnect() or not conn.is_connected: 

2892 # Not connected, or marked for reconnect: it authenticates 

2893 # with fresh credentials when it (re)connects on acquire, 

2894 # and opening a socket here only to authenticate could 

2895 # raise and stop the token renewal 

2896 continue 

2897 try: 

2898 # A connection the server has closed, or a dirty one, is 

2899 # disconnected here instead of failing the AUTH, for the 

2900 # same reason 

2901 await self._prepare_acquired_connection(conn) 

2902 if not conn.is_connected: 

2903 continue 

2904 await conn.retry.call_with_retry( 

2905 lambda: conn.send_command( 

2906 "AUTH", token.try_get("oid"), token.get_value() 

2907 ), 

2908 lambda error: self._mock(error), 

2909 ) 

2910 except Exception as e: 

2911 conn.set_re_auth_token(token) 

2912 if first_error is None: 

2913 first_error = e 

2914 else: 

2915 sent.append(conn) 

2916 for conn in sent: 

2917 try: 

2918 await conn.retry.call_with_retry( 

2919 lambda: conn.read_response(), 

2920 lambda error: self._mock(error), 

2921 is_retryable=lambda error: not isinstance( 

2922 error, AuthenticationError 

2923 ), 

2924 ) 

2925 except AuthenticationError as e: 

2926 conn.set_re_auth_token(token) 

2927 if auth_error is None: 

2928 auth_error = e 

2929 except Exception as e: 

2930 conn.set_re_auth_token(token) 

2931 if first_error is None: 

2932 first_error = e 

2933 done += 1 

2934 free = set(tmp_queue) 

2935 for conn in existing: 

2936 if conn not in free: 

2937 conn.set_re_auth_token(token) 

2938 except BaseException: 

2939 # Interrupted, for example cancelled: the replies not read yet 

2940 # would be read by the next command on those connections 

2941 for conn in sent[done:]: 

2942 conn._force_disconnect() 

2943 raise 

2944 finally: 

2945 # Return every popped connection to the free queue, also when a 

2946 # re-authentication raised 

2947 while tmp_queue: 

2948 self._free.append(tmp_queue.popleft()) 

2949 if auth_error is not None: 

2950 raise auth_error 

2951 if first_error is not None: 

2952 raise first_error 

2953 

2954 async def _mock(self, error: RedisError): 

2955 """ 

2956 Dummy functions, needs to be passed as error callback to retry object. 

2957 :param error: 

2958 :return: 

2959 """ 

2960 pass 

2961 

2962 

2963class NodesManager: 

2964 __slots__ = ( 

2965 "_dynamic_startup_nodes", 

2966 "_event_dispatcher", 

2967 "_background_tasks", 

2968 "connection_kwargs", 

2969 "default_node", 

2970 "nodes_cache", 

2971 "_epoch", 

2972 "read_load_balancer", 

2973 "_initialize_lock", 

2974 "require_full_coverage", 

2975 "slots_cache", 

2976 "startup_nodes", 

2977 "address_remap", 

2978 "_topology_refresh_min_interval", 

2979 "_last_refresh_at", 

2980 "_failed_refreshes", 

2981 "_refresh_due_at", 

2982 "_last_refresh_unreachable_args", 

2983 "_refresh_requested_at_epoch", 

2984 "_requested_last_failed_node_name", 

2985 "_requested_additional_startup_nodes", 

2986 ) 

2987 

2988 def __init__( 

2989 self, 

2990 startup_nodes: List["ClusterNode"], 

2991 require_full_coverage: bool, 

2992 connection_kwargs: Dict[str, Any], 

2993 dynamic_startup_nodes: bool = True, 

2994 address_remap: Callable[[Tuple[str, int]], Tuple[str, int]] | None = None, 

2995 event_dispatcher: EventDispatcher | None = None, 

2996 topology_refresh_min_interval: float | None = None, 

2997 ) -> None: 

2998 self.startup_nodes = {node.name: node for node in startup_nodes} 

2999 self.require_full_coverage = require_full_coverage 

3000 self.connection_kwargs = connection_kwargs 

3001 self.address_remap = address_remap 

3002 # The minimum interval between error-triggered refreshes, or None for 

3003 # _TOPOLOGY_REFRESH_MIN_INTERVAL_SECONDS. See _refresh_due. 

3004 self._topology_refresh_min_interval = topology_refresh_min_interval 

3005 

3006 self.default_node: "ClusterNode" = None 

3007 self.nodes_cache: Dict[str, "ClusterNode"] = {} 

3008 self.slots_cache: Dict[int, List["ClusterNode"]] = {} 

3009 self._epoch: int = 0 

3010 self.read_load_balancer = LoadBalancer() 

3011 self._initialize_lock: asyncio.Lock = asyncio.Lock() 

3012 # When the last refresh ended, how many failed in a row, and when the 

3013 # next error-triggered refresh is due. Every refresh that ends clears 

3014 # the due time and the next check computes it, once, from the backoff 

3015 # of the caller's retry (a jittered backoff returns a new value on 

3016 # every call). See _refresh_due. 

3017 self._last_refresh_at: Optional[float] = None 

3018 self._failed_refreshes = 0 

3019 self._refresh_due_at: Optional[float] = None 

3020 # The message (args) of the error of the last refresh if it reached no 

3021 # node, cleared by a refresh that ends otherwise; only the message, so 

3022 # the error does not keep the frames of that refresh alive. See 

3023 # _error_to_raise. 

3024 self._last_refresh_unreachable_args: Optional[Tuple[Any, ...]] = None 

3025 # The epoch of the newest refresh request, until a refresh answers it: 

3026 # a refresh that completes after it, such as one SMIGRATED runs, 

3027 # already does 

3028 self._refresh_requested_at_epoch: Optional[int] = None 

3029 # The node whose connection error asked for the pending refresh: the 

3030 # refresh tries it last when no other name is passed in 

3031 self._requested_last_failed_node_name: Optional[str] = None 

3032 # The nodes a MOVED error that asked for the pending refresh pointed 

3033 # to: the refresh also queries them, after the startup nodes 

3034 self._requested_additional_startup_nodes: Tuple[Tuple[str, int], ...] = () 

3035 

3036 self._background_tasks: Set[asyncio.Task] = set() 

3037 self._dynamic_startup_nodes: bool = dynamic_startup_nodes 

3038 if event_dispatcher is None: 

3039 self._event_dispatcher = EventDispatcher() 

3040 else: 

3041 self._event_dispatcher = event_dispatcher 

3042 

3043 def get_node( 

3044 self, 

3045 host: Optional[str] = None, 

3046 port: Optional[int] = None, 

3047 node_name: Optional[str] = None, 

3048 ) -> Optional["ClusterNode"]: 

3049 if host and port: 

3050 # the user passed host and port 

3051 if host == "localhost": 

3052 host = _resolve_localhost() 

3053 return self.nodes_cache.get(get_node_name(host=host, port=port)) 

3054 elif node_name: 

3055 return self.nodes_cache.get(node_name) 

3056 else: 

3057 raise DataError( 

3058 "get_node requires one of the following: 1. node name 2. host and port" 

3059 ) 

3060 

3061 def set_nodes( 

3062 self, 

3063 old: Dict[str, "ClusterNode"], 

3064 new: Dict[str, "ClusterNode"], 

3065 remove_old: bool = False, 

3066 ) -> None: 

3067 if remove_old: 

3068 for name in list(old.keys()): 

3069 if name not in new: 

3070 # Node is removed from cache before disconnect starts, 

3071 # so it won't be found in lookups during disconnect 

3072 # Mark active connections so in-flight commands can 

3073 # finish, then disconnect them when their current 

3074 # operation completes. Free connections can be 

3075 # disconnected immediately. 

3076 # 

3077 # TODO: Make this method async in the next major release to 

3078 # disconnect the free connections inline instead of in a 

3079 # background task. 

3080 removed_node = old.pop(name) 

3081 removed_node.update_active_connections_for_reconnect() 

3082 task = asyncio.create_task( 

3083 removed_node.disconnect_free_connections() 

3084 ) 

3085 self._background_tasks.add(task) 

3086 task.add_done_callback(self._background_tasks.discard) 

3087 

3088 for name, node in new.items(): 

3089 if name in old: 

3090 # Preserve the existing node and its connections, whatever its 

3091 # role. The server keeps the session state of a connection 

3092 # across a role change, READONLY is sent on every connection 

3093 # when reads from replicas are enabled, and a command that 

3094 # reaches a node that no longer serves its slot gets MOVED. 

3095 old[name].server_type = node.server_type 

3096 continue 

3097 # New node is detected and should be added to the pool 

3098 old[name] = node 

3099 

3100 def move_node_to_end_of_cached_nodes(self, node_name: str) -> None: 

3101 """ 

3102 Move a failing node to the end of startup_nodes and nodes_cache so it's 

3103 tried last during reinitialization and when selecting the default node. 

3104 If the node is not in the respective list, nothing is done. 

3105 """ 

3106 # Move in startup_nodes 

3107 if node_name in self.startup_nodes and len(self.startup_nodes) > 1: 

3108 node = self.startup_nodes.pop(node_name) 

3109 self.startup_nodes[node_name] = node # Re-insert at end 

3110 

3111 # Move in nodes_cache - this affects get_nodes_by_server_type ordering 

3112 # which is used to select the default_node during initialize() 

3113 if node_name in self.nodes_cache and len(self.nodes_cache) > 1: 

3114 node = self.nodes_cache.pop(node_name) 

3115 self.nodes_cache[node_name] = node # Re-insert at end 

3116 

3117 async def move_slot(self, e: AskError | MovedError): 

3118 node_changed = False 

3119 # The redirect carries the address the node advertises, like 

3120 # CLUSTER SLOTS does, so it needs the same remapping to be reachable 

3121 host, port = self.remap_host_port(e.host, e.port) 

3122 redirected_node = self.get_node(host=host, port=port) 

3123 if redirected_node: 

3124 # The node already exists 

3125 if redirected_node.server_type != PRIMARY: 

3126 # Update the node's server type 

3127 redirected_node.server_type = PRIMARY 

3128 else: 

3129 # This is a new node, we will add it to the nodes cache 

3130 redirected_node = ClusterNode(host, port, PRIMARY, **self.connection_kwargs) 

3131 self.set_nodes(self.nodes_cache, {redirected_node.name: redirected_node}) 

3132 slot_nodes = self.slots_cache[e.slot_id] 

3133 if redirected_node not in slot_nodes: 

3134 # The new slot owner is a new server, or a server from a different 

3135 # shard. We need to remove all current nodes from the slot's list 

3136 # (including replications) and add just the new node. 

3137 self.slots_cache[e.slot_id] = [redirected_node] 

3138 node_changed = True 

3139 elif redirected_node is not slot_nodes[0]: 

3140 # The MOVED error resulted from a failover, and the new slot owner 

3141 # had previously been a replica. 

3142 old_primary = slot_nodes[0] 

3143 # Update the old primary to be a replica and add it to the end of 

3144 # the slot's node list 

3145 old_primary.server_type = REPLICA 

3146 slot_nodes.append(old_primary) 

3147 # Remove the old replica, which is now a primary, from the slot's 

3148 # node list 

3149 slot_nodes.remove(redirected_node) 

3150 # Override the old primary with the new one 

3151 slot_nodes[0] = redirected_node 

3152 if self.default_node == old_primary: 

3153 # Update the default node with the new primary 

3154 self.default_node = redirected_node 

3155 node_changed = True 

3156 # else: circular MOVED to current primary -> no-op 

3157 # Dispatch so listeners can run shard-pubsub reconciliation; skipped on 

3158 # the no-op branch to avoid needless walks under MOVED storms. A 

3159 # listener must not break slots-cache refresh; log and continue so a 

3160 # single buggy listener cannot starve the rest. 

3161 if node_changed: 

3162 try: 

3163 await self._event_dispatcher.dispatch_async( 

3164 AsyncAfterSlotsCacheRefreshEvent() 

3165 ) 

3166 except Exception as exc: 

3167 # Don't shadow the method parameter ``e``: ``except as`` binds 

3168 # the listener exception in the function scope and ``del``s 

3169 # the name on block exit (PEP 3134), which would also wipe 

3170 # out the original AskError/MovedError parameter. 

3171 logger.exception( 

3172 "listener raised during slots-cache refresh: %s: %s", 

3173 type(exc).__name__, 

3174 exc, 

3175 ) 

3176 

3177 def get_node_from_slot( 

3178 self, 

3179 slot: int, 

3180 read_from_replicas: bool = False, 

3181 load_balancing_strategy=None, 

3182 ) -> "ClusterNode": 

3183 if read_from_replicas is True and load_balancing_strategy is None: 

3184 load_balancing_strategy = LoadBalancingStrategy.ROUND_ROBIN 

3185 

3186 try: 

3187 if len(self.slots_cache[slot]) > 1 and load_balancing_strategy: 

3188 # get the server index using the strategy defined in load_balancing_strategy 

3189 primary_name = self.slots_cache[slot][0].name 

3190 node_idx = self.read_load_balancer.get_server_index( 

3191 primary_name, len(self.slots_cache[slot]), load_balancing_strategy 

3192 ) 

3193 return self.slots_cache[slot][node_idx] 

3194 return self.slots_cache[slot][0] 

3195 except (IndexError, KeyError, TypeError): 

3196 raise SlotNotCoveredError( 

3197 f'Slot "{slot}" not covered by the cluster. ' 

3198 f'"require_full_coverage={self.require_full_coverage}"' 

3199 ) 

3200 

3201 def get_nodes_by_server_type(self, server_type: str) -> List["ClusterNode"]: 

3202 return [ 

3203 node 

3204 for node in self.nodes_cache.values() 

3205 if node.server_type == server_type 

3206 ] 

3207 

3208 @asynccontextmanager 

3209 async def _counting_failed_refresh(self) -> AsyncGenerator[None, None]: 

3210 """ 

3211 Record a refresh that raised, so error-triggered refreshes back off. 

3212 

3213 A refresh cancelled before it ended (for example by a timeout around 

3214 the command that ran it) is not counted as failed, but the next one 

3215 still waits the delay, so callers that keep timing out do not run one 

3216 refresh after another. Its outcome is unknown, so it clears the record 

3217 of a refresh that reached no node. 

3218 """ 

3219 try: 

3220 yield 

3221 except BaseException as e: 

3222 if isinstance(e, Exception): 

3223 self._failed_refreshes += 1 

3224 self._last_refresh_unreachable_args = ( 

3225 e.args if isinstance(e, RedisClusterUnreachableError) else None 

3226 ) 

3227 self._last_refresh_at = time.monotonic() 

3228 self._refresh_due_at = None 

3229 raise 

3230 

3231 @asynccontextmanager 

3232 async def _closing_temporary_nodes( 

3233 self, 

3234 ) -> AsyncGenerator[List["ClusterNode"], None]: 

3235 """ 

3236 Yield a list to fill with the ClusterNode objects built only to query 

3237 CLUSTER SLOTS during a refresh (the additional startup nodes), and 

3238 close the connections they opened once the refresh ends, whether it 

3239 succeeded or raised. The topology keeps its own ClusterNode objects. 

3240 """ 

3241 temporary_nodes: List["ClusterNode"] = [] 

3242 try: 

3243 yield temporary_nodes 

3244 finally: 

3245 if temporary_nodes: 

3246 await asyncio.gather( 

3247 *(node.disconnect() for node in temporary_nodes), 

3248 return_exceptions=True, 

3249 ) 

3250 

3251 def _refresh_due(self, retry: Retry | None = None) -> bool: 

3252 """ 

3253 Whether a topology refresh triggered by an error may run now: not 

3254 before the delay of _topology_refresh_delay has passed since the 

3255 previous refresh ended. 

3256 """ 

3257 due_at = self._refresh_due_at 

3258 if due_at is None: 

3259 # The first check since a refresh ended 

3260 last_refresh_at = self._last_refresh_at 

3261 if last_refresh_at is None: 

3262 return True 

3263 due_at = last_refresh_at + _topology_refresh_delay( 

3264 retry, 

3265 self._failed_refreshes, 

3266 self._topology_refresh_min_interval, 

3267 ) 

3268 self._refresh_due_at = due_at 

3269 return time.monotonic() >= due_at 

3270 

3271 def _error_instead_of_retry( 

3272 self, error: Exception, last_refresh_at: Optional[float] 

3273 ) -> Optional[Exception]: 

3274 """ 

3275 The error to raise instead of retrying :error:, the connection or 

3276 timeout error of the previous attempt, or None to retry. A refresh that 

3277 ended since that attempt failed (``_last_refresh_at`` moved from 

3278 :last_refresh_at:, read when the error was raised) and reached no node 

3279 leaves the retry the slot map that attempt failed on, so the caller 

3280 gives up now with the :class:`~.RedisClusterUnreachableError` that 

3281 _error_to_raise builds. 

3282 """ 

3283 if ( 

3284 self._last_refresh_unreachable_args is None 

3285 or self._last_refresh_at == last_refresh_at 

3286 ): 

3287 return None 

3288 outage_error = _error_to_raise(self._last_refresh_unreachable_args, error) 

3289 return None if outage_error is error else outage_error 

3290 

3291 def _current_topology_nodes( 

3292 self, 

3293 queried_nodes: Iterable["ClusterNode"], 

3294 last_failed_node_name: str | None, 

3295 ) -> Iterator["ClusterNode"]: 

3296 """ 

3297 The nodes of the current topology that are not in :queried_nodes:, for 

3298 a refresh that got no slot map covering all slots from them. With 

3299 dynamic_startup_nodes=False the startup nodes are only the seeds, which 

3300 may fail while the nodes of the current topology still answer. The 

3301 order is random, so clients don't all ask the same node, with the 

3302 nodes that have a connection open first, as they served commands 

3303 lately and no error closed it, and :last_failed_node_name: last. A 

3304 generator: nothing is computed unless the refresh reaches it. 

3305 """ 

3306 queried_names = {node.name for node in queried_nodes} 

3307 nodes = [ 

3308 node for name, node in self.nodes_cache.items() if name not in queried_names 

3309 ] 

3310 random.shuffle(nodes) 

3311 connected_nodes = [] 

3312 other_nodes = [] 

3313 last_failed_node = None 

3314 for node in nodes: 

3315 if node.name == last_failed_node_name: 

3316 last_failed_node = node 

3317 elif any(connection.is_connected for connection in node._connections): 

3318 connected_nodes.append(node) 

3319 else: 

3320 other_nodes.append(node) 

3321 yield from connected_nodes 

3322 yield from other_nodes 

3323 if last_failed_node is not None: 

3324 yield last_failed_node 

3325 

3326 async def initialize( 

3327 self, 

3328 additional_startup_nodes_info: Optional[List[Tuple[str, int]]] = None, 

3329 last_failed_node_name: Optional[str] = None, 

3330 ) -> None: 

3331 """ 

3332 Initializes the nodes cache and slots cache. CLUSTER SLOTS is asked of 

3333 the startup nodes, the additional startup nodes and the last failed 

3334 node, then, while no slot map covers all slots, of the other nodes of 

3335 the current topology. 

3336 """ 

3337 self.read_load_balancer.reset() 

3338 tmp_nodes_cache: Dict[str, "ClusterNode"] = {} 

3339 tmp_slots: Dict[int, List["ClusterNode"]] = {} 

3340 disagreements = [] 

3341 startup_nodes_reachable = False 

3342 fully_covered = False 

3343 exception = None 

3344 epoch = self._epoch 

3345 if additional_startup_nodes_info is None: 

3346 additional_startup_nodes_info = [] 

3347 

3348 # The temporary nodes are closed after the lock is released 

3349 async with ( 

3350 self._closing_temporary_nodes() as temporary_nodes, 

3351 self._initialize_lock, 

3352 self._counting_failed_refresh(), 

3353 ): 

3354 if self._epoch != epoch: 

3355 # another initialize call has already reinitialized the 

3356 # nodes since we started waiting for the lock; 

3357 # we don't need to do it again. 

3358 return 

3359 

3360 # Register the nodes for re-authentication before the first 

3361 # connection is opened: that connection's handshake starts the 

3362 # streaming credential provider, whose first renewal is cancelled 

3363 # for good if no callback is registered yet. The event holds the 

3364 # nodes_cache dict itself, which set_nodes updates in place, so the 

3365 # nodes this refresh adds are covered without another dispatch. 

3366 self._event_dispatcher.dispatch( 

3367 AfterAsyncClusterInstantiationEvent( 

3368 self.nodes_cache, 

3369 self.connection_kwargs.get("credential_provider", None), 

3370 ) 

3371 ) 

3372 

3373 requested_last_failed_node_name = self._requested_last_failed_node_name 

3374 if last_failed_node_name is None: 

3375 last_failed_node_name = requested_last_failed_node_name 

3376 requested_additional_startup_nodes = ( 

3377 self._requested_additional_startup_nodes 

3378 ) 

3379 if requested_additional_startup_nodes: 

3380 # A new list: the one passed in belongs to the caller 

3381 additional_startup_nodes_info = additional_startup_nodes_info + [ 

3382 node_info 

3383 for node_info in requested_additional_startup_nodes 

3384 if node_info not in additional_startup_nodes_info 

3385 ] 

3386 

3387 # Copy to a list to prevent RuntimeError if self.startup_nodes 

3388 # is modified during iteration, then shuffle the iteration order. 

3389 startup_nodes = list(self.startup_nodes.values()) 

3390 deferred_failed_nodes = [] 

3391 if last_failed_node_name is not None: 

3392 for index, node in enumerate(startup_nodes): 

3393 if node.name == last_failed_node_name: 

3394 deferred_failed_nodes.append(startup_nodes.pop(index)) 

3395 break 

3396 if len(startup_nodes) > 1: 

3397 # Vary which startup node is queried first so clients do not 

3398 # all reinitialize through the same node. 

3399 random.shuffle(startup_nodes) 

3400 # An address that is already a startup node is queried through that 

3401 # node, so no temporary node is built for it. One that is a node of 

3402 # the current topology (e.g. the target of the MOVED that asked for 

3403 # this refresh) is queried through that node, over the connections 

3404 # it already has, and keeps them. Startup nodes are named after the 

3405 # resolved localhost, like ClusterNode names them. 

3406 additional_startup_nodes = [] 

3407 for host, port in additional_startup_nodes_info: 

3408 name = get_node_name( 

3409 _resolve_localhost() if host == "localhost" else host, port 

3410 ) 

3411 if name in self.startup_nodes: 

3412 continue 

3413 node = self.nodes_cache.get(name) 

3414 if node is None: 

3415 node = ClusterNode(host, port, **self.connection_kwargs) 

3416 temporary_nodes.append(node) 

3417 additional_startup_nodes.append(node) 

3418 if last_failed_node_name is not None: 

3419 for index, node in enumerate(additional_startup_nodes): 

3420 if node.name == last_failed_node_name: 

3421 if not deferred_failed_nodes: 

3422 deferred_failed_nodes.append(node) 

3423 additional_startup_nodes.pop(index) 

3424 break 

3425 for startup_node in chain( 

3426 startup_nodes, 

3427 additional_startup_nodes, 

3428 deferred_failed_nodes, 

3429 # Only reached while no node gave a slot map covering all slots 

3430 self._current_topology_nodes( 

3431 chain( 

3432 startup_nodes, additional_startup_nodes, deferred_failed_nodes 

3433 ), 

3434 last_failed_node_name, 

3435 ), 

3436 ): 

3437 try: 

3438 # Make sure cluster mode is enabled on this node 

3439 try: 

3440 if logger.isEnabledFor(logging.DEBUG): 

3441 logger.debug( 

3442 "Topology refresh: querying CLUSTER SLOTS on " 

3443 f"{startup_node.name}" 

3444 ) 

3445 cluster_slots = await startup_node.execute_command( 

3446 "CLUSTER SLOTS" 

3447 ) 

3448 except ResponseError: 

3449 raise RedisClusterException( 

3450 "Cluster mode is not enabled on this node" 

3451 ) 

3452 startup_nodes_reachable = True 

3453 # An error from an earlier startup node is only raised when 

3454 # no node answers, so drop it. Its traceback refers to this 

3455 # frame: keeping it forms a reference cycle that holds 

3456 # tmp_slots and tmp_nodes_cache until the GC runs. 

3457 exception = None 

3458 except Exception as e: 

3459 # Try the next startup node. 

3460 # The last error is kept while no node has answered, and is 

3461 # raised only if none does. 

3462 if logger.isEnabledFor(logging.DEBUG): 

3463 logger.debug( 

3464 "Topology refresh: CLUSTER SLOTS failed on " 

3465 f"{startup_node.name}: {type(e).__name__}: {e}" 

3466 ) 

3467 # Once a node has answered, later errors are not stored: they 

3468 # would bring the cycle back. 

3469 if not startup_nodes_reachable: 

3470 exception = e 

3471 continue 

3472 

3473 # CLUSTER SLOTS command results in the following output: 

3474 # [[slot_section[from_slot,to_slot,master,replica1,...,replicaN]]] 

3475 # where each node contains the following list: [IP, port, node_id] 

3476 # Therefore, cluster_slots[0][2][0] will be the IP address of the 

3477 # primary node of the first slot section. 

3478 # If there's only one server in the cluster, its ``host`` is '' 

3479 # Fix it to the host in startup_nodes 

3480 if ( 

3481 len(cluster_slots) == 1 

3482 and not cluster_slots[0][2][0] 

3483 and len(self.startup_nodes) == 1 

3484 ): 

3485 cluster_slots[0][2][0] = startup_node.host 

3486 

3487 for slot in cluster_slots: 

3488 for i in range(2, len(slot)): 

3489 slot[i] = [str_if_bytes(val) for val in slot[i]] 

3490 primary_node = slot[2] 

3491 host = primary_node[0] 

3492 # A node that does not know its own address sends an empty 

3493 # host, and one whose endpoint is unknown 

3494 # (cluster-preferred-endpoint-type unknown-endpoint) a null 

3495 # one: both are reached on the host that answered 

3496 if not host: 

3497 host = startup_node.host 

3498 port = int(primary_node[1]) 

3499 host, port = self.remap_host_port(host, port) 

3500 

3501 nodes_for_slot = [] 

3502 

3503 target_node = tmp_nodes_cache.get(get_node_name(host, port)) 

3504 if not target_node: 

3505 target_node = ClusterNode( 

3506 host, port, PRIMARY, **self.connection_kwargs 

3507 ) 

3508 # add this node to the nodes cache 

3509 tmp_nodes_cache[target_node.name] = target_node 

3510 nodes_for_slot.append(target_node) 

3511 

3512 replica_nodes = slot[3:] 

3513 for replica_node in replica_nodes: 

3514 host = replica_node[0] 

3515 if not host: 

3516 host = startup_node.host 

3517 port = replica_node[1] 

3518 host, port = self.remap_host_port(host, port) 

3519 

3520 target_replica_node = tmp_nodes_cache.get( 

3521 get_node_name(host, port) 

3522 ) 

3523 if not target_replica_node: 

3524 target_replica_node = ClusterNode( 

3525 host, port, REPLICA, **self.connection_kwargs 

3526 ) 

3527 # add this node to the nodes cache 

3528 tmp_nodes_cache[target_replica_node.name] = target_replica_node 

3529 nodes_for_slot.append(target_replica_node) 

3530 

3531 for i in range(int(slot[0]), int(slot[1]) + 1): 

3532 if i not in tmp_slots: 

3533 tmp_slots[i] = nodes_for_slot 

3534 else: 

3535 # Validate that 2 nodes want to use the same slot cache 

3536 # setup 

3537 tmp_slot = tmp_slots[i][0] 

3538 if tmp_slot.name != target_node.name: 

3539 disagreements.append( 

3540 f"{tmp_slot.name} vs {target_node.name} on slot: {i}" 

3541 ) 

3542 

3543 if len(disagreements) > 5: 

3544 raise RedisClusterException( 

3545 f"startup_nodes could not agree on a valid " 

3546 f"slots cache: {', '.join(disagreements)}" 

3547 ) 

3548 

3549 # Validate if all slots are covered or if we should try next startup node 

3550 fully_covered = True 

3551 for i in range(REDIS_CLUSTER_HASH_SLOTS): 

3552 if i not in tmp_slots: 

3553 fully_covered = False 

3554 break 

3555 if logger.isEnabledFor(logging.DEBUG): 

3556 logger.debug( 

3557 f"Topology refresh: CLUSTER SLOTS from {startup_node.name} " 

3558 f"reported nodes {sorted(tmp_nodes_cache)}; " 

3559 f"slots fully covered: {fully_covered}" 

3560 ) 

3561 if fully_covered: 

3562 break 

3563 

3564 if not startup_nodes_reachable: 

3565 # The unreachable subtype is reserved for connectivity failures: 

3566 # MultiDB registers it as retryable, so a deterministic 

3567 # server/configuration error (e.g. cluster mode disabled or 

3568 # invalid credentials - AuthenticationError and 

3569 # AuthorizationError subclass ConnectionError but cannot be 

3570 # repaired by a failover) must keep surfacing as a plain 

3571 # RedisClusterException. 

3572 try: 

3573 if isinstance( 

3574 exception, (ConnectionError, TimeoutError, OSError) 

3575 ) and not isinstance( 

3576 exception, (AuthenticationError, AuthorizationError) 

3577 ): 

3578 raise RedisClusterUnreachableError( 

3579 f"Redis Cluster cannot be connected. Please provide at least " 

3580 f"one reachable node: {str(exception)}" 

3581 ) from exception 

3582 raise RedisClusterException( 

3583 f"Redis Cluster cannot be connected. Please provide at least " 

3584 f"one reachable node: {str(exception)}" 

3585 ) from exception 

3586 finally: 

3587 # Ensure we clear local references to caught exceptions 

3588 exception = None 

3589 

3590 # Check if the slots are not fully covered 

3591 if not fully_covered and self.require_full_coverage: 

3592 # Despite the requirement that the slots be covered, there 

3593 # isn't a full coverage 

3594 raise RedisClusterException( 

3595 f"All slots are not covered after query all startup_nodes. " 

3596 f"{len(tmp_slots)} of {REDIS_CLUSTER_HASH_SLOTS} " 

3597 f"covered..." 

3598 ) 

3599 

3600 # Set the tmp variables to the real variables 

3601 self.set_nodes(self.nodes_cache, tmp_nodes_cache, remove_old=True) 

3602 # tmp_slots was built from CLUSTER SLOTS responses and can contain 

3603 # newly-created ClusterNode objects for nodes we already know about. 

3604 # Rebuild the slots cache with the preserved nodes_cache instances 

3605 # so existing per-node connection pools stay in use after refresh. 

3606 # Keep the shared node-list-per-slot-range shape from tmp_slots to 

3607 # avoid allocating a separate list for every slot. 

3608 node_lists_by_id: Dict[int, List["ClusterNode"]] = {} 

3609 new_slots_cache: Dict[int, List["ClusterNode"]] = {} 

3610 for slot, nodes in tmp_slots.items(): 

3611 node_list_id = id(nodes) 

3612 slot_nodes = node_lists_by_id.get(node_list_id) 

3613 if slot_nodes is None: 

3614 slot_nodes = [self.nodes_cache[node.name] for node in nodes] 

3615 node_lists_by_id[node_list_id] = slot_nodes 

3616 new_slots_cache[slot] = slot_nodes 

3617 self.slots_cache = new_slots_cache 

3618 

3619 if self._dynamic_startup_nodes: 

3620 # Populate the startup nodes with all discovered nodes 

3621 self.set_nodes(self.startup_nodes, self.nodes_cache, remove_old=True) 

3622 

3623 # Set the default node 

3624 self.default_node = self.get_nodes_by_server_type(PRIMARY)[0] 

3625 self._last_refresh_at = time.monotonic() 

3626 self._failed_refreshes = 0 

3627 if self._requested_last_failed_node_name == requested_last_failed_node_name: 

3628 # Answered by this refresh; another node that failed while it 

3629 # ran stays for the next one 

3630 self._requested_last_failed_node_name = None 

3631 if ( 

3632 self._requested_additional_startup_nodes 

3633 == requested_additional_startup_nodes 

3634 ): 

3635 self._requested_additional_startup_nodes = () 

3636 self._refresh_due_at = None 

3637 self._last_refresh_unreachable_args = None 

3638 self._epoch += 1 

3639 # Dispatch so listeners (e.g. ClusterPubSub) can reconcile per-node 

3640 # state after slot ownership may have changed. A listener must not 

3641 # break slots-cache refresh; log and continue so a single buggy 

3642 # listener cannot starve the rest. 

3643 try: 

3644 await self._event_dispatcher.dispatch_async( 

3645 AsyncAfterSlotsCacheRefreshEvent() 

3646 ) 

3647 except Exception as e: 

3648 logger.exception( 

3649 "listener raised during slots-cache refresh: %s: %s", 

3650 type(e).__name__, 

3651 e, 

3652 ) 

3653 

3654 async def aclose(self, attr: str = "nodes_cache") -> None: 

3655 self.default_node = None 

3656 # Wait for every node to close before raising, so one node's close 

3657 # failure does not return while the others are still closing 

3658 ret = await asyncio.gather( 

3659 *( 

3660 asyncio.create_task(node.disconnect()) 

3661 for node in getattr(self, attr).values() 

3662 ), 

3663 return_exceptions=True, 

3664 ) 

3665 exc = next((res for res in ret if isinstance(res, BaseException)), None) 

3666 if exc: 

3667 raise exc 

3668 

3669 async def _aclose_all(self) -> None: 

3670 """ 

3671 Close the nodes of the topology, then the startup nodes. 

3672 

3673 The startup nodes are closed even when closing the topology nodes fails 

3674 or is cancelled. The first error is the one raised, so a later close 

3675 failure cannot replace it, or turn a cancellation into an error. 

3676 """ 

3677 try: 

3678 await self.aclose() 

3679 except BaseException: 

3680 try: 

3681 await self.aclose("startup_nodes") 

3682 except Exception: 

3683 pass 

3684 raise 

3685 await self.aclose("startup_nodes") 

3686 

3687 def remap_host_port(self, host: str, port: int) -> Tuple[str, int]: 

3688 """ 

3689 Remap the host and port returned from the cluster to a different 

3690 internal value. Useful if the client is not connecting directly 

3691 to the cluster. 

3692 """ 

3693 if self.address_remap: 

3694 return self.address_remap((host, port)) 

3695 return host, port 

3696 

3697 

3698class ClusterPipeline(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands): 

3699 """ 

3700 Create a new ClusterPipeline object. 

3701 

3702 Usage:: 

3703 

3704 result = await ( 

3705 rc.pipeline() 

3706 .set("A", 1) 

3707 .get("A") 

3708 .hset("K", "F", "V") 

3709 .hgetall("K") 

3710 .mset_nonatomic({"A": 2, "B": 3}) 

3711 .get("A") 

3712 .get("B") 

3713 .delete("A", "B", "K") 

3714 .execute() 

3715 ) 

3716 # result = [True, "1", 1, {"F": "V"}, True, True, "2", "3", 1, 1, 1] 

3717 

3718 Note: For commands `DELETE`, `EXISTS`, `TOUCH`, `mset_nonatomic`, which are split 

3719 across multiple nodes, you'll get multiple results for them in the array. 

3720 

3721 Which methods must be awaited: 

3722 

3723 Staging a command returns the pipeline itself, so commands chain and are not 

3724 awaited, as in the example above. The coroutines defined on this class must be 

3725 awaited individually:: 

3726 

3727 watch, unwatch, unlink, discard, reset, execute, initialize, 

3728 himport_prepare, himport_discard, himport_discard_all 

3729 

3730 Of those, only ``initialize`` returns the pipeline, so it is the only one that 

3731 chains once awaited. ``reset``, ``discard``, ``watch``, ``unwatch`` and ``unlink`` 

3732 return ``None``, ``execute`` returns a ``list``, ``himport_prepare`` a ``bool`` and 

3733 the two ``himport_discard`` methods an ``int``. 

3734 

3735 That list covers only the methods defined on this class. Inherited command 

3736 coroutines are not pipeline steps. ``client_tracking_on`` and 

3737 ``client_tracking_off`` await the pipeline itself, which re-initializes it and 

3738 discards everything staged so far. Others cannot run on a pipeline at all: 

3739 ``command_info`` and the ``hotkeys_*`` family raise ``NotImplementedError``, and 

3740 ``cluster_delslots`` raises ``TypeError``. 

3741 

3742 `unlink` is the surprising one, because the inherited `delete` behaves the other 

3743 way:: 

3744 

3745 pipe = rc.pipeline() 

3746 pipe.delete("A") # stages, chainable 

3747 await pipe.unlink("B") # stages, must be awaited, returns None 

3748 await pipe.execute() 

3749 

3750 Between :meth:`watch` and :meth:`multi` a command returns a coroutine rather than 

3751 the pipeline. It is executed only when awaited and resolves to the response, so it 

3752 must be awaited. After :meth:`multi` commands are queued again and chain as usual:: 

3753 

3754 async with rc.pipeline(transaction=True) as pipe: 

3755 await pipe.watch("a") 

3756 a = await pipe.get("a") # executed when awaited 

3757 pipe.multi() 

3758 pipe.set("a", int(a) + 1) # queued, chains 

3759 await pipe.execute() 

3760 

3761 The split commands from the note above and ``unlink`` are the exception: between 

3762 :meth:`watch` and :meth:`multi`, ``delete``, ``exists`` and ``touch`` return the 

3763 pipeline and ``unlink`` returns ``None``, and all four drop the command unsent, so 

3764 do not use them there. ``mset_nonatomic`` raises ``NotImplementedError`` in a 

3765 transactional pipeline. 

3766 

3767 Outside a transactional pipeline ``watch``, ``unwatch`` and ``discard`` raise 

3768 :class:`~.RedisClusterException`, and the ``himport_*`` methods act on the shared 

3769 fieldset registry rather than staging a command. 

3770 

3771 Retryable errors: 

3772 - :class:`~.ClusterDownError` 

3773 - :class:`~.ConnectionError` 

3774 - :class:`~.TimeoutError` 

3775 

3776 Redirection errors: 

3777 - :class:`~.TryAgainError` 

3778 - :class:`~.MovedError` 

3779 - :class:`~.AskError` 

3780 

3781 :param client: 

3782 | Existing :class:`~.RedisCluster` client 

3783 """ 

3784 

3785 __slots__ = ( 

3786 "cluster_client", 

3787 "_transaction", 

3788 "_execution_strategy", 

3789 ) 

3790 

3791 # Type discrimination marker for @overload self-type pattern 

3792 _is_async_client: Literal[True] = True 

3793 

3794 def __init__( 

3795 self, client: RedisCluster, transaction: Optional[bool] = None 

3796 ) -> None: 

3797 self.cluster_client = client 

3798 self._transaction = transaction 

3799 self._execution_strategy: ExecutionStrategy = ( 

3800 PipelineStrategy(self) 

3801 if not self._transaction 

3802 else TransactionStrategy(self) 

3803 ) 

3804 

3805 @property 

3806 def nodes_manager(self) -> "NodesManager": 

3807 """Get the nodes manager from the cluster client.""" 

3808 return self.cluster_client.nodes_manager 

3809 

3810 def get_connection_kwargs(self) -> Dict[str, Optional[Any]]: 

3811 """Get the connection kwargs from the cluster client.""" 

3812 return self.cluster_client.get_connection_kwargs() 

3813 

3814 # HIMPORT lifecycle on a cluster pipeline delegates to the parent client, mutating 

3815 # the one shared registry that every node pool references. A fieldset declared here 

3816 # is therefore visible to the batched himport_set pre-flight, mirroring the sync 

3817 # ClusterPipeline (which inherits these from RedisCluster over the shared registry). 

3818 

3819 @property 

3820 def himport_registry(self) -> HImportRegistry: 

3821 """The cluster-wide HIMPORT fieldset registry (empty if none was declared). 

3822 

3823 Read-only: the registry is mutated only through the HIMPORT command methods. 

3824 """ 

3825 return self.cluster_client.himport_registry 

3826 

3827 async def himport_prepare( 

3828 self, fieldset_name: str, fields: Iterable[FieldT] 

3829 ) -> bool: 

3830 """Declare an HIMPORT fieldset cluster-wide (shared registry, applied lazily).""" 

3831 return await self.cluster_client.himport_prepare(fieldset_name, fields) 

3832 

3833 async def himport_discard(self, fieldset_name: str) -> int: 

3834 """Remove an HIMPORT fieldset cluster-wide (shared registry, applied lazily).""" 

3835 return await self.cluster_client.himport_discard(fieldset_name) 

3836 

3837 async def himport_discard_all(self) -> int: 

3838 """Remove all HIMPORT fieldsets cluster-wide (shared registry, applied lazily).""" 

3839 return await self.cluster_client.himport_discard_all() 

3840 

3841 def set_response_callback(self, command: str, callback: ResponseCallbackT) -> None: 

3842 """Set a custom response callback on the cluster client.""" 

3843 self.cluster_client.set_response_callback(command, callback) 

3844 

3845 async def initialize(self) -> "ClusterPipeline": 

3846 await self._execution_strategy.initialize() 

3847 return self 

3848 

3849 async def __aenter__(self) -> "ClusterPipeline": 

3850 return await self.initialize() 

3851 

3852 async def __aexit__(self, exc_type: None, exc_value: None, traceback: None) -> None: 

3853 await self.reset() 

3854 

3855 def __await__(self) -> Generator[Any, None, "ClusterPipeline"]: 

3856 return self.initialize().__await__() 

3857 

3858 def __bool__(self) -> bool: 

3859 "Pipeline instances should always evaluate to True on Python 3+" 

3860 return True 

3861 

3862 def __len__(self) -> int: 

3863 return len(self._execution_strategy) 

3864 

3865 def execute_command( 

3866 self, *args: Union[KeyT, EncodableT], **kwargs: Any 

3867 ) -> "ClusterPipeline": 

3868 """ 

3869 Append a raw command to the pipeline. 

3870 

3871 :param args: 

3872 | Raw command args 

3873 :param kwargs: 

3874 

3875 - target_nodes: :attr:`NODE_FLAGS` or :class:`~.ClusterNode` 

3876 or List[:class:`~.ClusterNode`] or Dict[Any, :class:`~.ClusterNode`] 

3877 - Rest of the kwargs are passed to the Redis connection 

3878 """ 

3879 return self._execution_strategy.execute_command(*args, **kwargs) 

3880 

3881 async def execute( 

3882 self, raise_on_error: bool = True, allow_redirections: bool = True 

3883 ) -> List[Any]: 

3884 """ 

3885 Execute the pipeline. 

3886 

3887 It will retry the commands as specified by retries specified in :attr:`retry` 

3888 & then raise an exception. 

3889 

3890 :param raise_on_error: 

3891 | Raise the first error if there are any errors 

3892 :param allow_redirections: 

3893 | Whether to retry each failed command individually in case of redirection 

3894 errors 

3895 

3896 :raises RedisClusterException: if target_nodes is not provided & the command 

3897 can't be mapped to a slot 

3898 """ 

3899 try: 

3900 return await self._execution_strategy.execute( 

3901 raise_on_error, allow_redirections 

3902 ) 

3903 finally: 

3904 await self.reset() 

3905 

3906 def _split_command_across_slots( 

3907 self, command: str, *keys: KeyT 

3908 ) -> "ClusterPipeline": 

3909 for slot_keys in self.cluster_client._partition_keys_by_slot(keys).values(): 

3910 self.execute_command(command, *slot_keys) 

3911 

3912 return self 

3913 

3914 async def reset(self): 

3915 """ 

3916 Reset back to empty pipeline. 

3917 """ 

3918 await self._execution_strategy.reset() 

3919 

3920 def multi(self): 

3921 """ 

3922 Start a transactional block of the pipeline after WATCH commands 

3923 are issued. End the transactional block with `execute`. 

3924 """ 

3925 self._execution_strategy.multi() 

3926 

3927 async def discard(self): 

3928 """Discards the transactional block. Must be awaited.""" 

3929 await self._execution_strategy.discard() 

3930 

3931 async def watch(self, *names): 

3932 """Watches the values at keys ``names``""" 

3933 await self._execution_strategy.watch(*names) 

3934 

3935 async def unwatch(self): 

3936 """Unwatches all previously specified keys""" 

3937 await self._execution_strategy.unwatch() 

3938 

3939 async def unlink(self, *names): 

3940 """ 

3941 Stages an `UNLINK` for keys ``names``. Must be awaited, and returns ``None`` 

3942 rather than the pipeline, so unlike `delete` it does not chain:: 

3943 

3944 await pipe.unlink("A") 

3945 

3946 Outside a transactional block only one key is accepted; more raises 

3947 :class:`~.RedisClusterException`. Between :meth:`watch` and :meth:`multi` 

3948 nothing is sent, so do not use it there. 

3949 """ 

3950 await self._execution_strategy.unlink(*names) 

3951 

3952 def mset_nonatomic( 

3953 self, mapping: Mapping[AnyKeyT, EncodableT] 

3954 ) -> "ClusterPipeline": 

3955 return self._execution_strategy.mset_nonatomic(mapping) 

3956 

3957 

3958for command in PIPELINE_BLOCKED_COMMANDS: 

3959 command = command.replace(" ", "_").lower() 

3960 if command == "mset_nonatomic": 

3961 continue 

3962 

3963 setattr(ClusterPipeline, command, block_pipeline_command(command)) 

3964 

3965# client_list_iter has no wire command of its own to add to 

3966# PIPELINE_BLOCKED_COMMANDS - it sends CLIENT LIST, blocked above under its 

3967# own name - so block it explicitly here too, or it would fall through to 

3968# the inherited implementation and queue CLIENT LIST like a real pipelined 

3969# command instead of raising. 

3970setattr(ClusterPipeline, "client_list_iter", block_pipeline_command("client_list_iter")) 

3971 

3972 

3973class PipelineCommand: 

3974 def __init__(self, position: int, *args: Any, **kwargs: Any) -> None: 

3975 self.args = args 

3976 self.kwargs = kwargs 

3977 self.position = position 

3978 self.result: Union[Any, Exception] = _UNANSWERED 

3979 # Either record type: a policy resolver serves ``CommandPolicies``, while the 

3980 # fallbacks below reuse the shared ``CommandMetadata`` defaults. Only the two routing 

3981 # policies, which both carry, are ever read. 

3982 self.command_policies: Optional[Union[CommandPolicies, CommandMetadata]] = None 

3983 # The replies the command already got, kept across the attempts so a retry sends 

3984 # it only where it has not been answered - keyed by slot for a split MULTI_SHARD 

3985 # command, by node name for a command sent to several nodes 

3986 self.replies: Optional[Dict[Any, Any]] = None 

3987 # The ``target_nodes`` a retry must route by again - see 

3988 # ``PipelineStrategy._execute`` 

3989 self.target_nodes: Any = None 

3990 

3991 def __repr__(self) -> str: 

3992 return f"[{self.position}] {self.args} ({self.kwargs})" 

3993 

3994 

3995class ExecutionStrategy(ABC): 

3996 @abstractmethod 

3997 async def initialize(self) -> "ClusterPipeline": 

3998 """ 

3999 Initialize the execution strategy. 

4000 

4001 See ClusterPipeline.initialize() 

4002 """ 

4003 pass 

4004 

4005 @abstractmethod 

4006 def execute_command( 

4007 self, *args: Union[KeyT, EncodableT], **kwargs: Any 

4008 ) -> "ClusterPipeline": 

4009 """ 

4010 Append a raw command to the pipeline. 

4011 

4012 See ClusterPipeline.execute_command() 

4013 """ 

4014 pass 

4015 

4016 @abstractmethod 

4017 async def execute( 

4018 self, raise_on_error: bool = True, allow_redirections: bool = True 

4019 ) -> List[Any]: 

4020 """ 

4021 Execute the pipeline. 

4022 

4023 It will retry the commands as specified by retries specified in :attr:`retry` 

4024 & then raise an exception. 

4025 

4026 See ClusterPipeline.execute() 

4027 """ 

4028 pass 

4029 

4030 @abstractmethod 

4031 def mset_nonatomic( 

4032 self, mapping: Mapping[AnyKeyT, EncodableT] 

4033 ) -> "ClusterPipeline": 

4034 """ 

4035 Executes multiple MSET commands according to the provided slot/pairs mapping. 

4036 

4037 See ClusterPipeline.mset_nonatomic() 

4038 """ 

4039 pass 

4040 

4041 @abstractmethod 

4042 async def reset(self): 

4043 """ 

4044 Resets current execution strategy. 

4045 

4046 See: ClusterPipeline.reset() 

4047 """ 

4048 pass 

4049 

4050 @abstractmethod 

4051 def multi(self): 

4052 """ 

4053 Starts transactional context. 

4054 

4055 See: ClusterPipeline.multi() 

4056 """ 

4057 pass 

4058 

4059 @abstractmethod 

4060 async def watch(self, *names): 

4061 """ 

4062 Watch given keys. 

4063 

4064 See: ClusterPipeline.watch() 

4065 """ 

4066 pass 

4067 

4068 @abstractmethod 

4069 async def unwatch(self): 

4070 """ 

4071 Unwatches all previously specified keys 

4072 

4073 See: ClusterPipeline.unwatch() 

4074 """ 

4075 pass 

4076 

4077 @abstractmethod 

4078 async def discard(self): 

4079 pass 

4080 

4081 @abstractmethod 

4082 async def unlink(self, *names): 

4083 """ 

4084 "Unlink a key specified by ``names``" 

4085 

4086 See: ClusterPipeline.unlink() 

4087 """ 

4088 pass 

4089 

4090 @abstractmethod 

4091 def __len__(self) -> int: 

4092 pass 

4093 

4094 

4095class AbstractStrategy(ExecutionStrategy): 

4096 def __init__(self, pipe: ClusterPipeline) -> None: 

4097 self._pipe: ClusterPipeline = pipe 

4098 self._command_queue: List["PipelineCommand"] = [] 

4099 

4100 async def initialize(self) -> "ClusterPipeline": 

4101 if self._pipe.cluster_client._initialize_due(): 

4102 await self._pipe.cluster_client.initialize() 

4103 self._command_queue = [] 

4104 return self._pipe 

4105 

4106 def execute_command( 

4107 self, *args: Union[KeyT, EncodableT], **kwargs: Any 

4108 ) -> "ClusterPipeline": 

4109 self._command_queue.append( 

4110 PipelineCommand(len(self._command_queue), *args, **kwargs) 

4111 ) 

4112 return self._pipe 

4113 

4114 def _annotate_exception(self, exception, number, command): 

4115 """ 

4116 Provides extra context to the exception prior to it being handled 

4117 """ 

4118 cmd = command_text(command) 

4119 msg = ( 

4120 f"Command # {number} ({truncate_text(cmd)}) of pipeline " 

4121 f"caused error: {exception.args[0]}" 

4122 ) 

4123 exception.args = (msg,) + exception.args[1:] 

4124 

4125 @abstractmethod 

4126 def mset_nonatomic( 

4127 self, mapping: Mapping[AnyKeyT, EncodableT] 

4128 ) -> "ClusterPipeline": 

4129 pass 

4130 

4131 @abstractmethod 

4132 async def execute( 

4133 self, raise_on_error: bool = True, allow_redirections: bool = True 

4134 ) -> List[Any]: 

4135 pass 

4136 

4137 @abstractmethod 

4138 async def reset(self): 

4139 pass 

4140 

4141 @abstractmethod 

4142 def multi(self): 

4143 pass 

4144 

4145 @abstractmethod 

4146 async def watch(self, *names): 

4147 pass 

4148 

4149 @abstractmethod 

4150 async def unwatch(self): 

4151 pass 

4152 

4153 @abstractmethod 

4154 async def discard(self): 

4155 pass 

4156 

4157 @abstractmethod 

4158 async def unlink(self, *names): 

4159 pass 

4160 

4161 def __len__(self) -> int: 

4162 return len(self._command_queue) 

4163 

4164 

4165class PipelineStrategy(AbstractStrategy): 

4166 def __init__(self, pipe: ClusterPipeline) -> None: 

4167 super().__init__(pipe) 

4168 

4169 def mset_nonatomic( 

4170 self, mapping: Mapping[AnyKeyT, EncodableT] 

4171 ) -> "ClusterPipeline": 

4172 encoder = self._pipe.cluster_client.encoder 

4173 

4174 slots_pairs = {} 

4175 for pair in mapping.items(): 

4176 slot = key_slot(encoder.encode(pair[0])) 

4177 slots_pairs.setdefault(slot, []).extend(pair) 

4178 

4179 for pairs in slots_pairs.values(): 

4180 self.execute_command("MSET", *pairs) 

4181 

4182 return self._pipe 

4183 

4184 async def execute( 

4185 self, raise_on_error: bool = True, allow_redirections: bool = True 

4186 ) -> List[Any]: 

4187 """ 

4188 Send the commands, retrying on RedisCluster.ERRORS_ALLOW_RETRY, and on 

4189 a READONLY reply of a node cached as a primary, as many 

4190 times as ``retry`` allows, with the backoff delay before each attempt 

4191 and a fixed 0.25 seconds first after CLUSTERDOWN or an uncovered slot. 

4192 Every retried error asks for a topology refresh, which the next attempt 

4193 runs once due. NOT_NODE_FAILURE_ERRORS are raised at once. Out of 

4194 retries, the last error is raised, as RedisClusterUnreachableError when 

4195 the last refresh reached no node; a refresh that reached no node since 

4196 an attempt failed ends the retries the same way. 

4197 """ 

4198 if not self._command_queue: 

4199 return [] 

4200 

4201 try: 

4202 retry_attempts = self._pipe.cluster_client.retry.get_retries() 

4203 failure_count = 0 

4204 nodes_manager = self._pipe.cluster_client.nodes_manager 

4205 # The error the previous attempt failed with, and when the last 

4206 # refresh had ended by then: a refresh since that reached no node 

4207 # ends the retries (see NodesManager._error_instead_of_retry) 

4208 last_error: Optional[Exception] = None 

4209 last_refresh_at: Optional[float] = None 

4210 while True: 

4211 try: 

4212 if self._pipe.cluster_client._initialize_due(): 

4213 await self._pipe.cluster_client.initialize() 

4214 if last_error is not None: 

4215 outage_error = nodes_manager._error_instead_of_retry( 

4216 last_error, last_refresh_at 

4217 ) 

4218 if outage_error is not None: 

4219 raise outage_error 

4220 return await self._execute( 

4221 self._pipe.cluster_client, 

4222 self._command_queue, 

4223 raise_on_error=raise_on_error, 

4224 allow_redirections=allow_redirections, 

4225 ) 

4226 

4227 except RedisCluster.NOT_NODE_FAILURE_ERRORS: 

4228 raise 

4229 except (*RedisCluster.ERRORS_ALLOW_RETRY, ReadOnlyError) as e: 

4230 if isinstance(e, ReadOnlyError) and not getattr( 

4231 e, "demoted_primary", False 

4232 ): 

4233 raise 

4234 if retry_attempts > 0: 

4235 # Try again with the new cluster setup. All other errors 

4236 # should be raised. 

4237 retry_attempts -= 1 

4238 # Refresh the topology on the next attempt, without 

4239 # closing the connections of the shared client 

4240 self._pipe.cluster_client._request_refresh() 

4241 failure_count += 1 

4242 last_error = e 

4243 last_refresh_at = nodes_manager._last_refresh_at 

4244 if type(e) in (ClusterDownError, SlotNotCoveredError): 

4245 # Give the cluster time to recover first, as a 

4246 # command that failed so does 

4247 await asyncio.sleep(0.25) 

4248 # Space the attempts out as the retry backoff says 

4249 delay = self._pipe.cluster_client._retry_backoff_delay( 

4250 self._pipe.cluster_client.retry, failure_count 

4251 ) 

4252 if delay > 0: 

4253 await asyncio.sleep(delay) 

4254 else: 

4255 # All other errors should be raised. 

4256 raise _error_to_raise( 

4257 nodes_manager._last_refresh_unreachable_args, e 

4258 ) 

4259 finally: 

4260 await self.reset() 

4261 

4262 async def _execute( 

4263 self, 

4264 client: "RedisCluster", 

4265 stack: List["PipelineCommand"], 

4266 raise_on_error: bool = True, 

4267 allow_redirections: bool = True, 

4268 ) -> List[Any]: 

4269 # A retry resends only the commands no node answered and the ones that failed: 

4270 # resending one that succeeded would run a write twice. 

4271 todo = [ 

4272 cmd 

4273 for cmd in stack 

4274 if cmd.result is _UNANSWERED or isinstance(cmd.result, Exception) 

4275 ] 

4276 

4277 nodes = {} 

4278 # the commands sent to several nodes, each with the name it was routed by, its 

4279 # copies - keyed by node name, or by slot for a split MULTI_SHARD command - and the 

4280 # split, if it was one. 

4281 fanned_out: List[ 

4282 Tuple[ 

4283 PipelineCommand, 

4284 str, 

4285 Dict[Any, PipelineCommand], 

4286 Optional[List[_MultiShardSplit]], 

4287 ] 

4288 ] = [] 

4289 # The nodes the caller named for a command, by its position 

4290 named_targets: Dict[int, Any] = {} 

4291 # Routing does not suspend either, so a large batch yields to the event loop 

4292 # while it is routed, as the reply loops do. A cancellation at the yield comes 

4293 # before anything is sent, and execute() resets the pipeline. 

4294 may_yield = len(todo) >= _PIPELINE_YIELD_MIN_COMMANDS 

4295 for i, cmd in enumerate(todo): 

4296 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS: 

4297 await asyncio.sleep(0) 

4298 passed_targets = cmd.kwargs.pop("target_nodes", cmd.target_nodes) 

4299 target_nodes_specified = bool(passed_targets) and not client._is_node_flag( 

4300 passed_targets 

4301 ) 

4302 # A nodes flag picks the targets too, in ``_determine_nodes`` below, and the 

4303 # command's own aggregation must not apply to the replies either 

4304 command, command_policies, slot = await client._resolve_command_policies( 

4305 *cmd.args, target_nodes_specified=bool(passed_targets) 

4306 ) 

4307 

4308 splits = None 

4309 if target_nodes_specified: 

4310 target_nodes = client._parse_target_nodes(passed_targets) 

4311 named_targets[cmd.position] = passed_targets 

4312 else: 

4313 request_policy = command_policies.request_policy 

4314 if request_policy == RequestPolicy.MULTI_SHARD: 

4315 splits = client._split_multi_shard_command(*cmd.args) 

4316 

4317 if splits is not None and len(splits) < 2: 

4318 # One slot: sent as it is, to the node of the slot the split 

4319 # already computed 

4320 target_nodes = [ 

4321 await client._get_node_from_slot(command, splits[0][0]) 

4322 ] 

4323 splits = None 

4324 elif splits is None: 

4325 target_nodes = await client._determine_nodes( 

4326 *cmd.args, 

4327 request_policy=request_policy, 

4328 node_flag=passed_targets, 

4329 slot=slot, 

4330 ) 

4331 if not target_nodes: 

4332 raise RedisClusterException( 

4333 "No targets were found to execute " 

4334 f"{truncate_text(command_text(cmd.args))} command on" 

4335 ) 

4336 cmd.command_policies = command_policies 

4337 # Kept for a retry, which would otherwise route the command by its own policy: 

4338 # a nodes flag is resolved again, and a command sent to several named nodes is 

4339 # sent to them again. A single named node is not kept, so a retry routes a keyed 

4340 # command by its keys - which the per-slot commands of ``mget_nonatomic``, 

4341 # ``delete`` and the other multi-key helpers rely on after a failover. 

4342 if passed_targets and (not target_nodes_specified or len(target_nodes) > 1): 

4343 cmd.target_nodes = passed_targets 

4344 

4345 # A command sent to several nodes - or split into one command per slot of its 

4346 # keys - is queued as copies that each carry one reply, and the replies are 

4347 # folded back into ``cmd`` once they are read, so the pipeline still answers 

4348 # with one result per queued command. 

4349 if splits is not None: 

4350 # A slot that succeeded on an earlier attempt is not sent again. 

4351 if cmd.replies is None: 

4352 cmd.replies = {} 

4353 copies: Dict[Any, PipelineCommand] = {} 

4354 fanned_out.append((cmd, command, copies, splits)) 

4355 queued = [] 

4356 replica_safe = ( 

4357 client.read_from_replicas 

4358 or client.load_balancing_strategy is not None 

4359 ) and await client._is_replica_safe(command) 

4360 load_balancing_strategy = ( 

4361 client.load_balancing_strategy if replica_safe else None 

4362 ) 

4363 for slot, slot_args, _, keys in splits: 

4364 if slot in cmd.replies: 

4365 continue 

4366 copies[slot] = PipelineCommand( 

4367 cmd.position, *slot_args, **_with_keys(cmd.kwargs, keys) 

4368 ) 

4369 queued.append( 

4370 ( 

4371 client.nodes_manager.get_node_from_slot( 

4372 slot, replica_safe, load_balancing_strategy 

4373 ), 

4374 copies[slot], 

4375 ) 

4376 ) 

4377 elif len(target_nodes) > 1: 

4378 # A node that answered on an earlier attempt is not asked again. One the 

4379 # topology refresh dropped from the targets is dropped from the replies 

4380 # too, as on the main path. 

4381 if cmd.replies is None: 

4382 cmd.replies = {} 

4383 else: 

4384 _keep_target_replies(cmd.replies, target_nodes) 

4385 copies = {} 

4386 fanned_out.append((cmd, command, copies, None)) 

4387 queued = [] 

4388 for node in target_nodes: 

4389 if node.name in cmd.replies: 

4390 continue 

4391 copies[node.name] = PipelineCommand( 

4392 cmd.position, *cmd.args, **cmd.kwargs 

4393 ) 

4394 queued.append((node, copies[node.name])) 

4395 else: 

4396 queued = [(target_nodes[0], cmd)] 

4397 

4398 for node, queued_command in queued: 

4399 if node.name not in nodes: 

4400 nodes[node.name] = (node, []) 

4401 nodes[node.name][1].append(queued_command) 

4402 

4403 # Start timing for observability 

4404 start_time = time.monotonic() 

4405 

4406 tasks = [ 

4407 asyncio.create_task(node[0].execute_pipeline(node[1])) 

4408 for node in nodes.values() 

4409 ] 

4410 # Let every node task settle before raising, so a retry never resends 

4411 # commands that a sibling task is still executing 

4412 errors = await asyncio.gather(*tasks, return_exceptions=True) 

4413 # A primary that answered READONLY was demoted: ask for a topology refresh, run 

4414 # by the next attempt once due. Marked before the replies are merged and before 

4415 # a node error is raised below, so a retry resends the command either way. 

4416 demoted = False 

4417 for (node, commands), failed in zip(nodes.values(), errors): 

4418 if failed is not True: 

4419 # Only a node whose replies hold an error can hold a READONLY 

4420 continue 

4421 node_demoted = False 

4422 for cmd in commands: 

4423 if _is_demoted_primary(cmd.result, node): 

4424 node_demoted = True 

4425 named = named_targets.get(cmd.position) 

4426 if named is None: 

4427 cmd.result.demoted_primary = True 

4428 else: 

4429 # Not retried, as RedisCluster does not retry a command with 

4430 # target nodes, and resent to them if the attempt is retried 

4431 # for another command 

4432 cmd.target_nodes = named 

4433 if node_demoted: 

4434 demoted = True 

4435 if node == client.get_default_node(): 

4436 # Replace it now, as a command does: the refresh runs 

4437 # only once due 

4438 client.replace_default_node() 

4439 if demoted: 

4440 client._request_refresh() 

4441 

4442 if fanned_out: 

4443 # A node whose task raised answered none of its commands, so its copies are 

4444 # not taken for successes when they are merged - and the slots of a split 

4445 # command that did succeed are kept for the attempt the error leads to. 

4446 # A command the merge answered with a success keeps it, as ONE_SUCCEEDED 

4447 # asks, even though one of its nodes failed. 

4448 for (_, commands), e in zip(nodes.values(), errors): 

4449 if isinstance(e, BaseException): 

4450 for queued_command in commands: 

4451 queued_command.result = e 

4452 for cmd, command, copies, splits in fanned_out: 

4453 cmd.result = self._merge_node_results( 

4454 client, cmd, command, copies, splits 

4455 ) 

4456 # The first node error that fails a command is raised, but only after every 

4457 # node whose error fails nothing has been tried last, so the raise skips none 

4458 # of them and the node it came from is still the one tried last. 

4459 raised: tuple["ClusterNode", BaseException] | None = None 

4460 for (node, commands), e in zip(nodes.values(), errors): 

4461 if not isinstance(e, BaseException): 

4462 continue 

4463 # A copy shares the position of the command it was made from, which is 

4464 # that command's index in the stack. When every command the node held is 

4465 # a copy of a command that merged to a success, the error fails nothing, 

4466 # so it is not raised. 

4467 if not fanned_out or not all( 

4468 c is not stack[c.position] 

4469 and not isinstance(stack[c.position].result, BaseException) 

4470 for c in commands 

4471 ): 

4472 if raised is None: 

4473 raised = (node, e) 

4474 # The write failed (the connection connects lazily on it): the error 

4475 # carries no node, so take it from the task that raised it 

4476 elif isinstance(e, (ConnectionError, TimeoutError)) and not isinstance( 

4477 e, RedisCluster.NOT_NODE_FAILURE_ERRORS 

4478 ): 

4479 self._try_failed_node_last(client, node) 

4480 if raised is not None: 

4481 node, e = raised 

4482 if isinstance(e, (ConnectionError, TimeoutError)) and not isinstance( 

4483 e, RedisCluster.NOT_NODE_FAILURE_ERRORS 

4484 ): 

4485 self._try_failed_node_last(client, node) 

4486 raise e 

4487 

4488 # Record operation duration for each node 

4489 for (node, commands), failed in zip(nodes.values(), errors): 

4490 # Find the first error in this node's commands, if any 

4491 node_error = None 

4492 for cmd in commands: 

4493 if isinstance(cmd.result, Exception): 

4494 node_error = cmd.result 

4495 break 

4496 

4497 # A node task that raised was tried last above 

4498 if failed is True: 

4499 # A read failed. Commands before it may have been redirected, 

4500 # so look past the first error for a connection error 

4501 for cmd in commands: 

4502 if isinstance( 

4503 cmd.result, (ConnectionError, TimeoutError) 

4504 ) and not isinstance( 

4505 cmd.result, RedisCluster.NOT_NODE_FAILURE_ERRORS 

4506 ): 

4507 self._try_failed_node_last(client, node) 

4508 break 

4509 

4510 db = node.connection_kwargs.get("db", 0) 

4511 await record_operation_duration( 

4512 command_name="PIPELINE", 

4513 duration_seconds=time.monotonic() - start_time, 

4514 server_address=node.host, 

4515 server_port=node.port, 

4516 db_namespace=str(db) if db is not None else None, 

4517 error=node_error, 

4518 ) 

4519 

4520 if any(errors): 

4521 if allow_redirections: 

4522 # A split MULTI_SHARD command resends only the slots that failed, and a 

4523 # command sent to several nodes asks only the nodes that have not 

4524 # answered 

4525 fanned_out_by_position = { 

4526 cmd.position: (command, copies, splits) 

4527 for cmd, command, copies, splits in fanned_out 

4528 } 

4529 # send each errored command individually 

4530 for cmd in todo: 

4531 if isinstance(cmd.result, (TryAgainError, MovedError, AskError)): 

4532 fan_out = fanned_out_by_position.get(cmd.position) 

4533 if fan_out is not None: 

4534 command, copies, splits = fan_out 

4535 if splits is not None: 

4536 cmd.result = await self._retry_failed_slots( 

4537 client, cmd, copies, splits 

4538 ) 

4539 else: 

4540 cmd.result = await self._retry_failed_nodes( 

4541 client, cmd, command 

4542 ) 

4543 continue 

4544 try: 

4545 if cmd.target_nodes is None: 

4546 cmd.result = await client.execute_command( 

4547 *cmd.args, **cmd.kwargs 

4548 ) 

4549 else: 

4550 cmd.result = await client.execute_command( 

4551 *cmd.args, 

4552 target_nodes=cmd.target_nodes, 

4553 **cmd.kwargs, 

4554 ) 

4555 except Exception as e: 

4556 cmd.result = e 

4557 

4558 if raise_on_error: 

4559 for cmd in todo: 

4560 result = cmd.result 

4561 if isinstance(result, Exception): 

4562 command = command_text(cmd.args) 

4563 # Errors from the redirect retry may carry no args, 

4564 # e.g. MaxConnectionsError() from acquire_connection(). 

4565 error = result.args[0] if result.args else type(result).__name__ 

4566 msg = ( 

4567 f"Command # {cmd.position + 1} " 

4568 f"({truncate_text(command)}) " 

4569 f"of pipeline caused error: {error}" 

4570 ) 

4571 result.args = (msg,) + result.args[1:] 

4572 raise result 

4573 

4574 default_cluster_node = client.get_default_node() 

4575 

4576 # Check whether the default node was used. In some cases, 

4577 # 'client.get_default_node()' may return None. The check below 

4578 # prevents a potential AttributeError. 

4579 if default_cluster_node is not None: 

4580 default_node = nodes.get(default_cluster_node.name) 

4581 if default_node is not None: 

4582 # This pipeline execution used the default node, check if we need 

4583 # to replace it. 

4584 # Note: when the error is raised we'll reset the default node in the 

4585 # caller function. 

4586 for cmd in default_node[1]: 

4587 # Check if it has a command that failed with a relevant 

4588 # exception 

4589 if type(cmd.result) in RedisCluster.ERRORS_ALLOW_RETRY: 

4590 client.replace_default_node() 

4591 break 

4592 

4593 return [cmd.result for cmd in stack] 

4594 

4595 @staticmethod 

4596 def _try_failed_node_last(client: "RedisCluster", node: "ClusterNode") -> None: 

4597 # As on the command path: move the failed node to the end of the cached 

4598 # nodes, so the refresh does not pick it as the default node while it 

4599 # is still a primary, and ask for a refresh that tries it last 

4600 client.nodes_manager.move_node_to_end_of_cached_nodes(node.name) 

4601 client._request_refresh(last_failed_node_name=node.name) 

4602 

4603 @staticmethod 

4604 def _merge_node_results( 

4605 client: "RedisCluster", 

4606 cmd: PipelineCommand, 

4607 command: str, 

4608 copies: Dict[Any, PipelineCommand], 

4609 splits: Optional[List[_MultiShardSplit]] = None, 

4610 ) -> Any: 

4611 """ 

4612 Fold the per-node replies of a command the pipeline sent to several nodes into the 

4613 one result the command answers with, the way the main client does: an error fails 

4614 the command unless its response policy expects one, and the replies are then merged 

4615 by the command's result callback or folded by its response policy. The replies of a 

4616 split MULTI_SHARD command are merged per slot instead - see 

4617 ``redis.cluster._merge_multi_shard_replies`` - once every slot has succeeded, and 

4618 the slots that did are kept on ``cmd`` so a retry resends only the ones that failed. 

4619 """ 

4620 response_policy = cmd.command_policies.response_policy 

4621 if splits is not None: 

4622 error = _record_replies( 

4623 cmd.replies, ((slot, c.result) for slot, c in copies.items()) 

4624 ) 

4625 if error is not None: 

4626 return error 

4627 return _merge_multi_shard_replies(cmd.replies, splits, response_policy) 

4628 

4629 # The nodes that answered on an earlier attempt are merged with this one's 

4630 res = {node_name: c.result for node_name, c in copies.items()} 

4631 _record_replies(cmd.replies, res.items()) 

4632 res, error = _split_successes_and_failure( 

4633 {**cmd.replies, **res}, response_policy 

4634 ) 

4635 if error is not None: 

4636 return error 

4637 

4638 # Remove keys entry, it needs only for cache. 

4639 options = {key: value for key, value in cmd.kwargs.items() if key != "keys"} 

4640 return client._process_result( 

4641 command, res, response_policy=response_policy, **options 

4642 ) 

4643 

4644 @staticmethod 

4645 async def _retry_failed_nodes( 

4646 client: "RedisCluster", cmd: PipelineCommand, command: str 

4647 ) -> Any: 

4648 """ 

4649 Ask each node of a command sent to several nodes that has not answered, one node 

4650 at a time, like the main client does, and merge the replies once every node has 

4651 answered. A node that already answered is not asked again - see 

4652 ``redis.cluster._record_replies``. 

4653 

4654 The targets are resolved again, the way the first attempt resolved them, so a 

4655 node the topology refresh replaced is asked in its place. 

4656 """ 

4657 if cmd.target_nodes is not None and not client._is_node_flag(cmd.target_nodes): 

4658 target_nodes = client._parse_target_nodes(cmd.target_nodes) 

4659 else: 

4660 target_nodes = await client._determine_nodes( 

4661 *cmd.args, 

4662 request_policy=cmd.command_policies.request_policy, 

4663 node_flag=cmd.target_nodes, 

4664 ) 

4665 

4666 _keep_target_replies(cmd.replies, target_nodes) 

4667 res = dict(cmd.replies) 

4668 for node in target_nodes: 

4669 if node.name in cmd.replies: 

4670 continue 

4671 try: 

4672 reply = await client.execute_command( 

4673 *cmd.args, target_nodes=[node], **cmd.kwargs 

4674 ) 

4675 except Exception as e: 

4676 res[node.name] = e 

4677 continue 

4678 cmd.replies[node.name] = reply 

4679 res[node.name] = reply 

4680 

4681 response_policy = cmd.command_policies.response_policy 

4682 res, error = _split_successes_and_failure(res, response_policy) 

4683 if error is not None: 

4684 return error 

4685 # Remove keys entry, it needs only for cache. 

4686 options = {key: value for key, value in cmd.kwargs.items() if key != "keys"} 

4687 return client._process_result( 

4688 command, res, response_policy=response_policy, **options 

4689 ) 

4690 

4691 @staticmethod 

4692 async def _retry_failed_slots( 

4693 client: "RedisCluster", 

4694 cmd: PipelineCommand, 

4695 copies: Dict[Any, PipelineCommand], 

4696 splits: List[_MultiShardSplit], 

4697 ) -> Any: 

4698 """ 

4699 Send each slot of a split MULTI_SHARD command that failed individually, like the 

4700 main client does, and merge the replies once every slot has succeeded. A slot that 

4701 already succeeded is not sent again - see ``redis.cluster._record_replies``. 

4702 

4703 The slots are sent one at a time. Sending them in parallel would take one 

4704 connection per slot, and raise ``MaxConnectionsError`` once a node holds more of 

4705 the failed slots than its ``max_connections``. 

4706 """ 

4707 for slot, slot_command in copies.items(): 

4708 if slot in cmd.replies: 

4709 continue 

4710 try: 

4711 cmd.replies[slot] = await client.execute_command( 

4712 *slot_command.args, **slot_command.kwargs 

4713 ) 

4714 except RedisError as e: 

4715 return e 

4716 

4717 return _merge_multi_shard_replies( 

4718 cmd.replies, splits, cmd.command_policies.response_policy 

4719 ) 

4720 

4721 async def reset(self): 

4722 """ 

4723 Reset back to empty pipeline. 

4724 """ 

4725 self._command_queue = [] 

4726 

4727 def multi(self): 

4728 raise RedisClusterException( 

4729 "method multi() is not supported outside of transactional context" 

4730 ) 

4731 

4732 async def watch(self, *names): 

4733 raise RedisClusterException( 

4734 "method watch() is not supported outside of transactional context" 

4735 ) 

4736 

4737 async def unwatch(self): 

4738 raise RedisClusterException( 

4739 "method unwatch() is not supported outside of transactional context" 

4740 ) 

4741 

4742 async def discard(self): 

4743 raise RedisClusterException( 

4744 "method discard() is not supported outside of transactional context" 

4745 ) 

4746 

4747 async def unlink(self, *names): 

4748 if len(names) != 1: 

4749 raise RedisClusterException( 

4750 "unlinking multiple keys is not implemented in pipeline command" 

4751 ) 

4752 

4753 return self.execute_command("UNLINK", names[0]) 

4754 

4755 

4756class TransactionStrategy(AbstractStrategy): 

4757 NO_SLOTS_COMMANDS = {"UNWATCH"} 

4758 IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"} 

4759 UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"} 

4760 SLOT_REDIRECT_ERRORS = (AskError, MovedError) 

4761 CONNECTION_ERRORS = ( 

4762 ConnectionError, 

4763 TimeoutError, 

4764 OSError, 

4765 ClusterDownError, 

4766 SlotNotCoveredError, 

4767 ) 

4768 

4769 def __init__(self, pipe: ClusterPipeline) -> None: 

4770 super().__init__(pipe) 

4771 self._explicit_transaction = False 

4772 self._watching = False 

4773 self._watch_acknowledged = False 

4774 self._pipeline_slots: Set[int] = set() 

4775 # True once a keyed (non-slot-agnostic) command has fixed the slot 

4776 self._transaction_has_keyed_slot = False 

4777 self._transaction_node: Optional[ClusterNode] = None 

4778 self._transaction_connection: Optional[Connection] = None 

4779 self._executing = False 

4780 # The error the running retry is retrying, and when the last refresh 

4781 # had ended by then: a refresh since that reached no node ends the 

4782 # retries (see NodesManager._error_instead_of_retry) 

4783 self._retrying: Optional[Tuple[Exception, Optional[float]]] = None 

4784 self._retry = copy(self._pipe.cluster_client.retry) 

4785 self._retry.update_supported_errors( 

4786 RedisCluster.ERRORS_ALLOW_RETRY + self.SLOT_REDIRECT_ERRORS 

4787 ) 

4788 

4789 async def _resolve_transaction_slot(self, *args) -> Optional[int]: 

4790 """ 

4791 Pick a slot for a transactional pipeline command. 

4792 

4793 Zero-key EVAL/EVALSHA can run on any primary. Reuse an existing 

4794 transaction slot when present so multiple zero-key scripts (or a 

4795 mix with keyed commands) stay single-slot. 

4796 """ 

4797 if args[0] in self.NO_SLOTS_COMMANDS: 

4798 return None 

4799 

4800 if is_zero_key_eval_command(*args): 

4801 if self._pipeline_slots: 

4802 return next(iter(self._pipeline_slots)) 

4803 return await self._pipe.cluster_client._determine_slot(*args) 

4804 

4805 slot_number = await self._pipe.cluster_client._determine_slot(*args) 

4806 if ( 

4807 slot_number is not None 

4808 and self._pipeline_slots 

4809 and slot_number not in self._pipeline_slots 

4810 and not self._transaction_has_keyed_slot 

4811 ): 

4812 # Prior slots came only from zero-key scripts; retarget. 

4813 self._pipeline_slots.clear() 

4814 if slot_number is not None: 

4815 self._transaction_has_keyed_slot = True 

4816 return slot_number 

4817 

4818 def _get_client_and_connection_for_transaction( 

4819 self, 

4820 ) -> Tuple[ClusterNode, Connection]: 

4821 """ 

4822 Find a connection for a pipeline transaction. 

4823 

4824 For running an atomic transaction, watch keys ensure that contents have not been 

4825 altered as long as the watch commands for those keys were sent over the same 

4826 connection. So once we start watching a key, we fetch a connection to the 

4827 node that owns that slot and reuse it. 

4828 

4829 ``_transaction_node`` is only updated when a new connection is acquired, so 

4830 it always names the node that owns the held connection, even if the slot 

4831 map changes while the connection is held. 

4832 """ 

4833 if not self._pipeline_slots: 

4834 raise RedisClusterException( 

4835 "At least a command with a key is needed to identify a node" 

4836 ) 

4837 

4838 if not self._transaction_connection: 

4839 node: ClusterNode = ( 

4840 self._pipe.cluster_client.nodes_manager.get_node_from_slot( 

4841 list(self._pipeline_slots)[0], False 

4842 ) 

4843 ) 

4844 self._transaction_connection = node.acquire_connection() 

4845 self._transaction_node = node 

4846 

4847 return self._transaction_node, self._transaction_connection 

4848 

4849 def execute_command(self, *args: Union[KeyT, EncodableT], **kwargs: Any) -> "Any": 

4850 # Given the limitation of ClusterPipeline sync API, we have to run it in thread. 

4851 return _run_coroutine_in_thread(self._execute_command(*args, **kwargs)) 

4852 

4853 async def _execute_command( 

4854 self, *args: Union[KeyT, EncodableT], **kwargs: Any 

4855 ) -> Any: 

4856 cluster_client = self._pipe.cluster_client 

4857 # This runs on a private loop in a worker thread (execute_command), so 

4858 # a topology refresh asked for by an error is left to the next command 

4859 # on the caller's loop: running it here would do I/O on connections 

4860 # bound to that loop. Only a client that never initialized has no 

4861 # topology to queue against. 

4862 initialize_here = ( 

4863 cluster_client._initialize 

4864 and cluster_client.nodes_manager.default_node is None 

4865 ) 

4866 startup_nodes = ( 

4867 tuple(cluster_client.nodes_manager.startup_nodes.values()) 

4868 if initialize_here 

4869 else () 

4870 ) 

4871 parser_node = ( 

4872 None 

4873 if initialize_here or args[0] in self.NO_SLOTS_COMMANDS 

4874 else cluster_client.commands_parser.node 

4875 ) 

4876 if parser_node is not None: 

4877 # Parser I/O during slot resolution belongs to this private loop, 

4878 # not to the caller's node or its connection pool. 

4879 cluster_client.commands_parser.node = ClusterNode( 

4880 parser_node.host, 

4881 parser_node.port, 

4882 **cluster_client.nodes_manager.connection_kwargs, 

4883 ) 

4884 slot_number: Optional[int] = None 

4885 try: 

4886 if initialize_here: 

4887 await cluster_client.initialize() 

4888 if args[0] not in self.NO_SLOTS_COMMANDS: 

4889 slot_number = await self._resolve_transaction_slot(*args) 

4890 finally: 

4891 if initialize_here: 

4892 # Keep the discovered topology and metadata, but not sockets bound 

4893 # to the private loop that closes when this command is queued. 

4894 # Same-address nodes can have distinct pools; deduplicate by identity. 

4895 nodes = { 

4896 id(node): node 

4897 for node in chain(startup_nodes, cluster_client.get_nodes()) 

4898 } 

4899 await asyncio.gather( 

4900 *(node.disconnect() for node in nodes.values()), 

4901 return_exceptions=True, 

4902 ) 

4903 elif parser_node is not None: 

4904 temporary_node = cluster_client.commands_parser.node 

4905 cluster_client.commands_parser.node = parser_node 

4906 await asyncio.gather( 

4907 temporary_node.disconnect(), return_exceptions=True 

4908 ) 

4909 

4910 if ( 

4911 self._watching or args[0] in self.IMMEDIATE_EXECUTE_COMMANDS 

4912 ) and not self._explicit_transaction: 

4913 if args[0] == "WATCH": 

4914 self._validate_watch() 

4915 

4916 if slot_number is not None: 

4917 if self._pipeline_slots and slot_number not in self._pipeline_slots: 

4918 raise CrossSlotTransactionError( 

4919 "Cannot watch or send commands on different slots" 

4920 ) 

4921 

4922 self._pipeline_slots.add(slot_number) 

4923 elif args[0] not in self.NO_SLOTS_COMMANDS: 

4924 raise RedisClusterException( 

4925 f"Cannot identify slot number for command: {args[0]}," 

4926 "it cannot be triggered in a transaction" 

4927 ) 

4928 

4929 return self._immediate_execute_command(*args, **kwargs) 

4930 else: 

4931 if slot_number is not None: 

4932 self._pipeline_slots.add(slot_number) 

4933 

4934 return super().execute_command(*args, **kwargs) 

4935 

4936 def _validate_watch(self): 

4937 if self._explicit_transaction: 

4938 raise RedisError("Cannot issue a WATCH after a MULTI") 

4939 

4940 self._watching = True 

4941 

4942 async def _immediate_execute_command(self, *args, **options): 

4943 try: 

4944 return await self._retry.call_with_retry( 

4945 lambda: self._get_connection_and_send_command(*args, **options), 

4946 self._reinitialize_on_error, 

4947 is_retryable=RedisCluster._is_retryable_cluster_error, 

4948 with_failure_count=True, 

4949 ) 

4950 except (ConnectionError, TimeoutError) as e: 

4951 nodes_manager = self._pipe.cluster_client.nodes_manager 

4952 raise _error_to_raise(nodes_manager._last_refresh_unreachable_args, e) 

4953 finally: 

4954 # The error of a retried attempt serves the run's next attempt only 

4955 self._retrying = None 

4956 

4957 def _raise_instead_of_retry(self) -> None: 

4958 """ 

4959 Give up the running retry when a refresh that ended since its error 

4960 reached no node (see NodesManager._error_instead_of_retry). 

4961 """ 

4962 if self._retrying is not None: 

4963 nodes_manager = self._pipe.cluster_client.nodes_manager 

4964 outage_error = nodes_manager._error_instead_of_retry(*self._retrying) 

4965 if outage_error is not None: 

4966 raise outage_error 

4967 

4968 async def _get_connection_and_send_command(self, *args, **options): 

4969 # Run a topology refresh an earlier error asked for, once due. This runs 

4970 # on the caller's loop, before every attempt: execute_command returns 

4971 # this coroutine from its private loop unawaited. 

4972 if self._pipe.cluster_client._initialize_due(): 

4973 await self._pipe.cluster_client.initialize() 

4974 self._raise_instead_of_retry() 

4975 held_connection = self._transaction_connection 

4976 redis_node, connection = self._get_client_and_connection_for_transaction() 

4977 # A connection acquired just now holds no WATCH state yet, so it is 

4978 # reconnected if it is marked, dead or dirty. A held one is only 

4979 # disconnected if not watching - disconnecting would lose WATCH state. 

4980 if connection is not held_connection: 

4981 await redis_node._prepare_acquired_connection(connection) 

4982 elif not self._watching: 

4983 await redis_node.disconnect_if_needed(connection) 

4984 

4985 # Start timing for observability 

4986 start_time = time.monotonic() 

4987 

4988 try: 

4989 response = await self._send_command_parse_response( 

4990 connection, redis_node, args[0], *args, **options 

4991 ) 

4992 

4993 await record_operation_duration( 

4994 command_name=args[0], 

4995 duration_seconds=time.monotonic() - start_time, 

4996 server_address=connection.host, 

4997 server_port=connection.port, 

4998 db_namespace=str(connection.db), 

4999 ) 

5000 

5001 return response 

5002 except Exception as e: 

5003 e.connection = connection 

5004 await record_operation_duration( 

5005 command_name=args[0], 

5006 duration_seconds=time.monotonic() - start_time, 

5007 server_address=connection.host, 

5008 server_port=connection.port, 

5009 db_namespace=str(connection.db), 

5010 error=e, 

5011 ) 

5012 raise 

5013 

5014 async def _send_command_parse_response( 

5015 self, 

5016 connection: Connection, 

5017 redis_node: ClusterNode, 

5018 command_name, 

5019 *args, 

5020 **options, 

5021 ): 

5022 """ 

5023 Send a command and parse the response 

5024 """ 

5025 

5026 # HIMPORT SET's wire form depends on per-connection state: the fieldset 

5027 # must be PREPAREd on this connection first, and any fieldset discarded 

5028 # since this connection last reconciled must be dropped. The 

5029 # immediate/watched path (commands issued after WATCH, before MULTI) 

5030 # would otherwise send a bare HIMPORT SET and fail with "no such 

5031 # fieldset". Route it through the node's HIMPORT executor, the same way 

5032 # the normal cluster path, the batched MULTI/EXEC path, and standalone 

5033 # watched pipelines all do. 

5034 himport_set = parse_himport_set_args(args) 

5035 if himport_set is not None: 

5036 # HIMPORT SET in the joined or split raw form; operands at the right 

5037 # offsets. Too few operands returns None and falls through to the bare 

5038 # send so the server returns its arity error. 

5039 key, fieldset_name, values = himport_set 

5040 output = await redis_node._himport_execute_set( 

5041 connection, key, fieldset_name, values 

5042 ) 

5043 else: 

5044 await connection.send_command(*args) 

5045 output = await redis_node.parse_response( 

5046 connection, command_name, **options 

5047 ) 

5048 

5049 if command_name == "WATCH": 

5050 self._watch_acknowledged = True 

5051 elif command_name in self.UNWATCH_COMMANDS: 

5052 self._watching = False 

5053 self._watch_acknowledged = False 

5054 return output 

5055 

5056 async def _reinitialize_on_error(self, error, failure_count): 

5057 self._retrying = ( 

5058 error, 

5059 self._pipe.cluster_client.nodes_manager._last_refresh_at, 

5060 ) 

5061 if hasattr(error, "connection"): 

5062 await record_error_count( 

5063 server_address=error.connection.host, 

5064 server_port=error.connection.port, 

5065 network_peer_address=error.connection.host, 

5066 network_peer_port=error.connection.port, 

5067 error_type=error, 

5068 retry_attempts=failure_count, 

5069 is_internal=True, 

5070 ) 

5071 

5072 # WATCH is requested before the first attempt, but only a reply 

5073 # establishes the protection that a retry must not silently discard. 

5074 if self._watch_acknowledged or isinstance( 

5075 error, self.SLOT_REDIRECT_ERRORS + self.CONNECTION_ERRORS 

5076 ): 

5077 if self._transaction_connection and self._transaction_node: 

5078 # Disconnect and release back to pool. The socket is discarded, 

5079 # so the close is not waited for: a close that times out must 

5080 # not replace the error and stop the retry. 

5081 await self._transaction_connection.disconnect(nowait=True) 

5082 self._transaction_node.release(self._transaction_connection) 

5083 self._transaction_connection = None 

5084 

5085 self._pipe.cluster_client.reinitialize_counter += 1 

5086 should_request_refresh = _should_request_refresh( 

5087 self._pipe.cluster_client.reinitialize_steps, 

5088 self._pipe.cluster_client.reinitialize_counter, 

5089 ) 

5090 if isinstance(error, AskError): 

5091 # MovedError is an AskError, so a MOVED slot is patched too, and 

5092 # the retry goes to the node that owns it now. The refresh is 

5093 # only asked for, run by the next command once due. 

5094 if self._transaction_node is not None: 

5095 _fill_missing_redirect_host(error, self._transaction_node.host) 

5096 await self._pipe.cluster_client.nodes_manager.move_slot(error) 

5097 if should_request_refresh: 

5098 self._pipe.cluster_client._request_refresh() 

5099 self._pipe.cluster_client.reinitialize_counter = 0 

5100 elif should_request_refresh: 

5101 # A connection error: ask for a refresh that tries the failed 

5102 # node last. The next attempt runs it once due, through 

5103 # initialize(), which keeps the current topology if the refresh 

5104 # fails. 

5105 cluster_client = self._pipe.cluster_client 

5106 failed_node_name = None 

5107 if self._transaction_node is not None: 

5108 failed_node_name = self._transaction_node.name 

5109 cluster_client.nodes_manager.move_node_to_end_of_cached_nodes( 

5110 failed_node_name 

5111 ) 

5112 cluster_client._request_refresh(last_failed_node_name=failed_node_name) 

5113 cluster_client.reinitialize_counter = 0 

5114 

5115 self._executing = False 

5116 if self._watch_acknowledged: 

5117 await self.reset() 

5118 if isinstance(error, self.SLOT_REDIRECT_ERRORS): 

5119 raise WatchError( 

5120 "Slot rebalancing occurred while watching keys" 

5121 ) from error 

5122 raise WatchError("An error occurred while watching keys") from error 

5123 

5124 async def _raise_first_error(self, responses, stack, start_time): 

5125 """ 

5126 Raise the first exception on the stack 

5127 """ 

5128 for r, cmd in zip(responses, stack): 

5129 if isinstance(r, Exception): 

5130 self._annotate_exception(r, cmd.position + 1, cmd.args) 

5131 

5132 await record_operation_duration( 

5133 command_name="TRANSACTION", 

5134 duration_seconds=time.monotonic() - start_time, 

5135 server_address=self._transaction_connection.host, 

5136 server_port=self._transaction_connection.port, 

5137 db_namespace=str(self._transaction_connection.db), 

5138 error=r, 

5139 ) 

5140 

5141 raise r 

5142 

5143 def mset_nonatomic( 

5144 self, mapping: Mapping[AnyKeyT, EncodableT] 

5145 ) -> "ClusterPipeline": 

5146 raise NotImplementedError("Method is not supported in transactional context.") 

5147 

5148 async def execute( 

5149 self, raise_on_error: bool = True, allow_redirections: bool = True 

5150 ) -> List[Any]: 

5151 stack = self._command_queue 

5152 if not stack and (not self._watching or not self._pipeline_slots): 

5153 return [] 

5154 

5155 return await self._execute_transaction_with_retries(stack, raise_on_error) 

5156 

5157 async def _execute_transaction_with_retries( 

5158 self, stack: List["PipelineCommand"], raise_on_error: bool 

5159 ): 

5160 try: 

5161 return await self._retry.call_with_retry( 

5162 lambda: self._execute_transaction(stack, raise_on_error), 

5163 lambda error, failure_count: self._reinitialize_on_error( 

5164 error, failure_count 

5165 ), 

5166 is_retryable=RedisCluster._is_retryable_cluster_error, 

5167 with_failure_count=True, 

5168 ) 

5169 except (ConnectionError, TimeoutError) as e: 

5170 nodes_manager = self._pipe.cluster_client.nodes_manager 

5171 raise _error_to_raise(nodes_manager._last_refresh_unreachable_args, e) 

5172 finally: 

5173 # The error of a retried attempt serves the run's next attempt only 

5174 self._retrying = None 

5175 

5176 async def _execute_transaction( 

5177 self, stack: List["PipelineCommand"], raise_on_error: bool 

5178 ): 

5179 if len(self._pipeline_slots) > 1: 

5180 raise CrossSlotTransactionError( 

5181 "All keys involved in a cluster transaction must map to the same slot" 

5182 ) 

5183 

5184 # Run a topology refresh an earlier error asked for, once due. This runs 

5185 # on the caller's loop, before every attempt. 

5186 if self._pipe.cluster_client._initialize_due(): 

5187 await self._pipe.cluster_client.initialize() 

5188 self._raise_instead_of_retry() 

5189 

5190 self._executing = True 

5191 

5192 held_connection = self._transaction_connection 

5193 redis_node, connection = self._get_client_and_connection_for_transaction() 

5194 # A connection acquired just now holds no WATCH state yet, so it is 

5195 # reconnected if it is marked, dead or dirty. A held one is only 

5196 # disconnected if not watching - disconnecting would lose WATCH state. 

5197 if connection is not held_connection: 

5198 await redis_node._prepare_acquired_connection(connection) 

5199 elif not self._watching: 

5200 await redis_node.disconnect_if_needed(connection) 

5201 

5202 # Ensure fieldsets referenced by buffered HIMPORT SETs are prepared on this 

5203 # node's connection before the MULTI/EXEC block (session state, not 

5204 # transactional). All keys share one slot here, so it is a single node. 

5205 await redis_node._himport_prepare_pipeline(connection, stack) 

5206 

5207 stack = chain( 

5208 [PipelineCommand(0, "MULTI")], 

5209 stack, 

5210 [PipelineCommand(0, "EXEC")], 

5211 ) 

5212 commands = [c.args for c in stack if EMPTY_RESPONSE not in c.kwargs] 

5213 packed_commands = await _pack_pipeline_commands(connection, commands) 

5214 

5215 # Start timing for observability 

5216 start_time = time.monotonic() 

5217 

5218 await connection.send_packed_command(packed_commands) 

5219 errors = [] 

5220 may_yield = len(self._command_queue) >= _PIPELINE_YIELD_MIN_COMMANDS 

5221 

5222 # parse off the response for MULTI 

5223 # NOTE: we need to handle ResponseErrors here and continue 

5224 # so that we read all the additional command messages from 

5225 # the socket 

5226 try: 

5227 await redis_node.parse_response(connection, "MULTI") 

5228 except ResponseError as e: 

5229 self._annotate_exception(e, 0, "MULTI") 

5230 errors.append(e) 

5231 except self.CONNECTION_ERRORS as cluster_error: 

5232 self._annotate_exception(cluster_error, 0, "MULTI") 

5233 cluster_error.connection = connection 

5234 raise 

5235 

5236 # and all the other commands 

5237 for i, command in enumerate(self._command_queue): 

5238 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS: 

5239 await _yield_in_read_loop(connection) 

5240 if EMPTY_RESPONSE in command.kwargs: 

5241 errors.append((i, command.kwargs[EMPTY_RESPONSE])) 

5242 else: 

5243 try: 

5244 _ = await redis_node.parse_response(connection, "_") 

5245 except self.SLOT_REDIRECT_ERRORS as slot_error: 

5246 self._annotate_exception(slot_error, i + 1, command.args) 

5247 errors.append(slot_error) 

5248 except self.CONNECTION_ERRORS as cluster_error: 

5249 self._annotate_exception(cluster_error, i + 1, command.args) 

5250 cluster_error.connection = connection 

5251 raise 

5252 except ResponseError as e: 

5253 self._annotate_exception(e, i + 1, command.args) 

5254 errors.append(e) 

5255 

5256 response = None 

5257 # parse the EXEC. 

5258 try: 

5259 response = await redis_node.parse_response(connection, "EXEC") 

5260 except ExecAbortError: 

5261 if errors: 

5262 raise errors[0] 

5263 raise 

5264 

5265 self._executing = False 

5266 

5267 # EXEC clears any watched keys 

5268 self._watching = False 

5269 self._watch_acknowledged = False 

5270 

5271 if response is None: 

5272 raise WatchError("Watched variable changed.") 

5273 

5274 # put any parse errors into the response 

5275 for i, e in errors: 

5276 response.insert(i, e) 

5277 

5278 if len(response) != len(self._command_queue): 

5279 raise InvalidPipelineStack( 

5280 "Unexpected response length for cluster pipeline EXEC." 

5281 " Command stack was {} but response had length {}".format( 

5282 [c.args[0] for c in self._command_queue], len(response) 

5283 ) 

5284 ) 

5285 

5286 # find any errors in the response and raise if necessary 

5287 if raise_on_error or len(errors) > 0: 

5288 await self._raise_first_error( 

5289 response, 

5290 self._command_queue, 

5291 start_time, 

5292 ) 

5293 

5294 # We have to run response callbacks manually 

5295 data = [] 

5296 for i, (r, cmd) in enumerate(zip(response, self._command_queue)): 

5297 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS: 

5298 await asyncio.sleep(0) 

5299 if not isinstance(r, Exception): 

5300 command_name = cmd.args[0] 

5301 if connection._resp2_fallback: 

5302 callback = _get_response_callback( 

5303 self._pipe.cluster_client.response_callbacks, 

5304 command_name, 

5305 connection, 

5306 ) 

5307 else: 

5308 callback = self._pipe.cluster_client.response_callbacks.get( 

5309 command_name 

5310 ) 

5311 if callback is not None: 

5312 # The keys option is only for the client cache and is 

5313 # not an option of the callbacks 

5314 cmd.kwargs.pop("keys", None) 

5315 r = callback(r, **cmd.kwargs) 

5316 data.append(r) 

5317 

5318 await record_operation_duration( 

5319 command_name="TRANSACTION", 

5320 duration_seconds=time.monotonic() - start_time, 

5321 server_address=connection.host, 

5322 server_port=connection.port, 

5323 db_namespace=str(connection.db), 

5324 ) 

5325 

5326 return data 

5327 

5328 async def reset(self): 

5329 self._command_queue = [] 

5330 

5331 try: 

5332 # make sure to reset the connection state in the event that we 

5333 # were watching something 

5334 if self._transaction_connection: 

5335 try: 

5336 # A dropped connection has already lost its WATCHes, so 

5337 # skip the UNWATCH instead of reconnecting to send it. 

5338 if self._watching and self._transaction_connection.is_connected: 

5339 # call this manually since our unwatch or 

5340 # immediate_execute_command methods can call reset() 

5341 await self._transaction_connection.send_command("UNWATCH") 

5342 await self._transaction_connection.read_response() 

5343 except self.CONNECTION_ERRORS: 

5344 # disconnect will also remove any previous WATCHes 

5345 if self._transaction_connection: 

5346 await self._transaction_connection.disconnect() 

5347 except asyncio.CancelledError: 

5348 # Disconnect so any unread UNWATCH reply does not get 

5349 # served to the next caller that takes the connection. 

5350 if self._transaction_connection: 

5351 await self._transaction_connection.disconnect() 

5352 raise 

5353 else: 

5354 # On the happy path, honor lazy reconnect before release. 

5355 await self._transaction_node.disconnect_if_needed( 

5356 self._transaction_connection 

5357 ) 

5358 finally: 

5359 # Always return the connection to the node's free queue, even on 

5360 # cancellation, so cancelled resets do not leak pooled 

5361 # connections. Detach the reference before releasing so the 

5362 # strategy never holds a pointer to a returned connection. 

5363 # ClusterNode.release is synchronous, so no shield is required. 

5364 if self._transaction_connection and self._transaction_node: 

5365 connection, self._transaction_connection = ( 

5366 self._transaction_connection, 

5367 None, 

5368 ) 

5369 self._transaction_node.release(connection) 

5370 # clean up the other instance attributes 

5371 self._transaction_connection = None 

5372 self._transaction_node = None 

5373 self._watching = False 

5374 self._watch_acknowledged = False 

5375 self._explicit_transaction = False 

5376 self._pipeline_slots = set() 

5377 self._transaction_has_keyed_slot = False 

5378 self._executing = False 

5379 self._retrying = None 

5380 

5381 def multi(self): 

5382 if self._explicit_transaction: 

5383 raise RedisError("Cannot issue nested calls to MULTI") 

5384 if self._command_queue: 

5385 raise RedisError( 

5386 "Commands without an initial WATCH have already been issued" 

5387 ) 

5388 self._explicit_transaction = True 

5389 

5390 async def watch(self, *names): 

5391 if self._explicit_transaction: 

5392 raise RedisError("Cannot issue a WATCH after a MULTI") 

5393 

5394 return await self.execute_command("WATCH", *names) 

5395 

5396 async def unwatch(self): 

5397 if self._watching: 

5398 return await self.execute_command("UNWATCH") 

5399 

5400 return True 

5401 

5402 async def discard(self): 

5403 await self.reset() 

5404 

5405 async def unlink(self, *names): 

5406 return self.execute_command("UNLINK", *names) 

5407 

5408 

5409class _ClusterNodePoolAdapter(ConnectionPoolInterface): 

5410 """Thin adapter exposing the :class:`ConnectionPoolInterface` that 

5411 :class:`PubSub` requires, backed by a :class:`ClusterNode`'s own 

5412 connection pool. 

5413 

5414 Connections are acquired from the node via 

5415 :meth:`ClusterNode.acquire_connection` and returned via 

5416 :meth:`ClusterNode.release`. :meth:`PubSub.aclose` already 

5417 disconnects the connection *before* calling :meth:`release`, so the 

5418 connection is returned to the node's free-queue in a disconnected 

5419 state — guaranteeing that a subscribed socket is never silently 

5420 reused for regular commands. 

5421 

5422 Methods that do not apply to this adapter (the underlying node's 

5423 lifecycle is managed by the cluster, not by individual PubSub 

5424 instances) are implemented as no-ops so the adapter remains a valid 

5425 :class:`ConnectionPoolInterface`. 

5426 """ 

5427 

5428 def __init__(self, node: "ClusterNode") -> None: 

5429 self._node = node 

5430 self.connection_kwargs = node.connection_kwargs 

5431 

5432 # -- methods used by PubSub ------------------------------------------------ 

5433 

5434 def get_encoder(self) -> Encoder: 

5435 return self._node.get_encoder() 

5436 

5437 async def get_connection( 

5438 self, command_name: Optional[str] = None, *keys: Any, **options: Any 

5439 ) -> AbstractConnection: 

5440 connection = self._node.acquire_connection() 

5441 try: 

5442 await self._node._prepare_acquired_connection(connection) 

5443 await connection.connect() 

5444 except BaseException: 

5445 # connect() may fail mid-handshake (e.g. after the TCP socket 

5446 # is established but before AUTH/HELLO completes) leaving the 

5447 # connection in a partially-connected state. Disconnect before 

5448 # returning it to the node's free queue so it is not reused. 

5449 await connection.disconnect() 

5450 self._node.release(connection) 

5451 raise 

5452 return connection 

5453 

5454 async def release(self, connection: AbstractConnection) -> None: 

5455 # PubSub.aclose() disconnects the connection before calling 

5456 # release(), so it is safe to put it back in the node's free 

5457 # queue – it will reconnect lazily on next use. 

5458 await self._node.disconnect_if_needed(connection) 

5459 self._node.release(connection) 

5460 

5461 # -- no-op stubs for the rest of ConnectionPoolInterface ------------------- 

5462 # The node's connections are shared with regular cluster traffic and its 

5463 # lifecycle is managed by RedisCluster / NodesManager, so the adapter must 

5464 # not reset, disconnect, retry-configure or re-auth them on behalf of a 

5465 # single PubSub instance. 

5466 

5467 def get_protocol(self): 

5468 return self.connection_kwargs.get("protocol", None) 

5469 

5470 def reset(self) -> None: 

5471 pass 

5472 

5473 async def disconnect(self, inuse_connections: bool = True) -> None: 

5474 pass 

5475 

5476 async def aclose(self) -> None: 

5477 pass 

5478 

5479 def set_retry(self, retry: "Retry") -> None: 

5480 pass 

5481 

5482 async def re_auth_callback(self, token: TokenInterface) -> None: 

5483 pass 

5484 

5485 def get_connection_count(self) -> List[Tuple[int, dict]]: 

5486 return [] 

5487 

5488 

5489def _unregister_slots_cache_listener( 

5490 dispatcher_ref: "weakref.ref[EventDispatcher]", 

5491 listener: AsyncEventListenerInterface, 

5492 event_type: Type[object], 

5493) -> None: 

5494 # Module-level finalizer callback. Kept free of strong references to the 

5495 # owning ClusterPubSub so attaching it via weakref.finalize does not 

5496 # extend the pubsub's lifetime. 

5497 dispatcher = dispatcher_ref() 

5498 if dispatcher is not None: 

5499 dispatcher.unregister_listeners({event_type: [listener]}) 

5500 

5501 

5502class ClusterPubSubSlotsCacheListener(AsyncEventListenerInterface): 

5503 """ 

5504 Async listener that forwards AsyncAfterSlotsCacheRefreshEvent to a 

5505 ClusterPubSub. 

5506 

5507 Holds a weak reference to the pubsub so it does not keep the instance 

5508 alive. Deterministic cleanup of the dispatcher's strong reference to this 

5509 listener is performed by a ``weakref.finalize`` attached to the owning 

5510 ClusterPubSub in ``ClusterPubSub.__init__``. 

5511 """ 

5512 

5513 def __init__(self, pubsub: "ClusterPubSub") -> None: 

5514 self._pubsub_ref: "weakref.ref[ClusterPubSub]" = weakref.ref(pubsub) 

5515 

5516 async def listen(self, event: object) -> None: 

5517 pubsub = self._pubsub_ref() 

5518 if pubsub is None: 

5519 # Race window between pubsub GC and the finalizer running; safe 

5520 # no-op, finalizer will remove this listener shortly. 

5521 return 

5522 try: 

5523 await pubsub.on_slots_changed() 

5524 except Exception as e: 

5525 # Listeners must not break slots-cache refresh; log and continue so 

5526 # a single buggy pubsub cannot starve the rest. 

5527 logger.exception( 

5528 "pubsub %r raised during slots-cache change: %s: %s", 

5529 pubsub, 

5530 type(e).__name__, 

5531 e, 

5532 ) 

5533 

5534 

5535# How long a per-node sharded-pubsub connection is skipped by the round robin 

5536# after a failed poll. PubSub._execute reconnects and retries through the 

5537# connection's own Retry, so one poll on an unreachable node can cost its whole 

5538# retry budget rather than the timeout the caller asked for; a cool-off keeps 

5539# the single reader from spending every pass on that node while its healthy 

5540# siblings hold undelivered messages. 

5541SHARD_POLL_COOL_OFF_SECONDS = 1.0 

5542 

5543# Returned by _poll_node_pubsub when a handler consumed the message it read. 

5544_DISPATCHED = object() 

5545 

5546# How often a failed sharded-pubsub poll may trigger a slots-cache refresh. 

5547# Reconciliation is otherwise purely event-driven, and a node that has left the 

5548# deployment answers ECONNREFUSED rather than MOVED - so without this the reader 

5549# would cool off against the departed node forever and the shard channels pinned 

5550# to it would never move to their new owner. Throttled because the refresh costs 

5551# a CLUSTER SLOTS round trip and a failing node fails every poll. 

5552SHARD_TOPOLOGY_REPAIR_INTERVAL_SECONDS = 5.0 

5553 

5554 

5555class ClusterPubSub(PubSub): 

5556 """ 

5557 Async cluster implementation for pub/sub. 

5558 

5559 IMPORTANT: before using ClusterPubSub, read about the known limitations 

5560 with pubsub in Cluster mode and learn how to workaround them: 

5561 https://redis.readthedocs.io/en/stable/clustering.html#known-pubsub-limitations 

5562 """ 

5563 

5564 def __init__( 

5565 self, 

5566 redis_cluster: "RedisCluster", 

5567 node: Optional["ClusterNode"] = None, 

5568 host: Optional[str] = None, 

5569 port: Optional[int] = None, 

5570 push_handler_func: Optional[Callable] = None, 

5571 event_dispatcher: Optional[EventDispatcher] = None, 

5572 **kwargs: Any, 

5573 ) -> None: 

5574 """ 

5575 When a pubsub instance is created without specifying a node, a single 

5576 node will be transparently chosen for the pubsub connection on the 

5577 first command execution. The node will be determined by: 

5578 1. Hashing the channel name in the request to find its keyslot 

5579 2. Selecting a node that handles the keyslot: If read_from_replicas is 

5580 set to true or load_balancing_strategy is set, a replica can be selected. 

5581 

5582 :param redis_cluster: RedisCluster instance 

5583 :param node: ClusterNode to connect to 

5584 :param host: Host of the node to connect to 

5585 :param port: Port of the node to connect to 

5586 :param push_handler_func: Optional push handler function 

5587 :param event_dispatcher: Optional event dispatcher 

5588 :param kwargs: Additional keyword arguments 

5589 """ 

5590 self.node = None 

5591 self.set_pubsub_node(redis_cluster, node, host, port) 

5592 

5593 # Borrow the node's own connection pool via an adapter rather than 

5594 # creating a second, detached ConnectionPool for pubsub. 

5595 if self.node is not None: 

5596 connection_pool = _ClusterNodePoolAdapter(self.node) 

5597 else: 

5598 connection_pool = None 

5599 

5600 self.cluster = redis_cluster 

5601 self.node_pubsub_mapping: Dict[str, PubSub] = {} 

5602 # Reverse index: shard channel (normalized) -> owning node.name. Used to 

5603 # route sunsubscribe calls and reconcile subscriptions after slot 

5604 # migration / failover. 

5605 self._shard_channel_to_node: Dict[Any, str] = {} 

5606 # Per-node poll cool-off deadlines (monotonic). Weak-keyed so a 

5607 # per-node pubsub dropped from node_pubsub_mapping takes its entry with 

5608 # it instead of leaking one per migration. 

5609 self._poll_cool_off: "weakref.WeakKeyDictionary[PubSub, float]" = ( 

5610 weakref.WeakKeyDictionary() 

5611 ) 

5612 # Node names whose last poll failed to connect. Read by 

5613 # _migrate_shard_channel to skip a wire SUNSUBSCRIBE that cannot 

5614 # succeed, and cleared as soon as a poll on that node works again. 

5615 self._unreachable_nodes: Set[str] = set() 

5616 # Monotonic deadline before which a failed poll must not trigger 

5617 # another slots-cache refresh. 0.0 means "never refreshed". 

5618 self._next_topology_repair: float = 0.0 

5619 # Dedicated lock for shard-subscription bookkeeping. Distinct from 

5620 # PubSub.self._lock (which serializes wire I/O on the cluster-level 

5621 # connection used by aclose / send_command / regular subscribe) so 

5622 # that reconciliation cannot starve those unrelated coroutines 

5623 # during long per-channel migrations. 

5624 self._shard_state_lock: asyncio.Lock = asyncio.Lock() 

5625 # Background tasks created by on_slots_changed; kept to prevent GC. 

5626 self._reconcile_tasks: Set[asyncio.Task] = set() 

5627 # Background NodesManager.initialize() tasks created by 

5628 # _schedule_topology_repair; kept to prevent GC, and kept apart from 

5629 # _reconcile_tasks because aclose() cancels that set and this work is 

5630 # not ours to cancel - see _schedule_topology_repair. 

5631 self._topology_repair_tasks: Set[asyncio.Task] = set() 

5632 self._pubsubs_generator = self._pubsubs_generator() 

5633 if event_dispatcher is None: 

5634 self._event_dispatcher = EventDispatcher() 

5635 else: 

5636 self._event_dispatcher = event_dispatcher 

5637 super().__init__( 

5638 connection_pool=connection_pool, 

5639 encoder=redis_cluster.encoder, 

5640 push_handler_func=push_handler_func, 

5641 event_dispatcher=self._event_dispatcher, 

5642 **kwargs, 

5643 ) 

5644 # Subscribe to slots-cache change notifications so shard subscriptions 

5645 # can be reconciled automatically after topology refreshes. 

5646 nm_dispatcher = redis_cluster.nodes_manager._event_dispatcher 

5647 self._slots_cache_listener = ClusterPubSubSlotsCacheListener(self) 

5648 nm_dispatcher.register_listeners( 

5649 {AsyncAfterSlotsCacheRefreshEvent: [self._slots_cache_listener]} 

5650 ) 

5651 # Deterministic GC-time cleanup so short-lived pubsubs do not leak 

5652 # listeners in the dispatcher when no slots-refresh event ever fires. 

5653 weakref.finalize( 

5654 self, 

5655 _unregister_slots_cache_listener, 

5656 weakref.ref(nm_dispatcher), 

5657 self._slots_cache_listener, 

5658 AsyncAfterSlotsCacheRefreshEvent, 

5659 ) 

5660 

5661 async def _ensure_cluster_initialized(self) -> None: 

5662 if self.cluster._initialize: 

5663 await self.cluster.initialize() 

5664 

5665 def set_pubsub_node( 

5666 self, 

5667 cluster: "RedisCluster", 

5668 node: Optional["ClusterNode"] = None, 

5669 host: Optional[str] = None, 

5670 port: Optional[int] = None, 

5671 ) -> None: 

5672 """ 

5673 The pubsub node will be set according to the passed node, host and port 

5674 When none of the node, host, or port are specified - the node is set 

5675 to None and will be determined by the keyslot of the channel in the 

5676 first command to be executed. 

5677 RedisClusterException will be thrown if the passed node does not exist 

5678 in the cluster. 

5679 If host is passed without port, or vice versa, a DataError will be 

5680 thrown. 

5681 """ 

5682 if node is not None: 

5683 # node is passed by the user 

5684 self._raise_on_invalid_node(cluster, node, node.host, node.port) 

5685 pubsub_node = node 

5686 elif host is not None and port is not None: 

5687 # host and port passed by the user 

5688 node = cluster.get_node(host=host, port=port) 

5689 self._raise_on_invalid_node(cluster, node, host, port) 

5690 pubsub_node = node 

5691 elif host is not None or port is not None: 

5692 # only one of host and port is specified 

5693 raise DataError("Specify both host and port") 

5694 else: 

5695 # nothing specified by the user 

5696 pubsub_node = None 

5697 self.node = pubsub_node 

5698 

5699 def get_pubsub_node(self) -> Optional["ClusterNode"]: 

5700 """ 

5701 Get the node that is being used as the pubsub connection. 

5702 

5703 :return: The ClusterNode being used for pubsub, or None if not yet determined 

5704 """ 

5705 return self.node 

5706 

5707 async def _resubscribe_shard_channels(self) -> None: 

5708 # A single node can own multiple slot ranges, so a batched 

5709 # ``SSUBSCRIBE`` covering every tracked channel would be rejected by 

5710 # Redis with a ``CROSSSLOT`` error. Group by hash slot and emit one 

5711 # ``SSUBSCRIBE`` per slot. 

5712 by_slot: defaultdict[int, dict] = defaultdict(dict) 

5713 for k, v in self.shard_channels.items(): 

5714 by_slot[key_slot(self.encoder.encode(k))][k] = v 

5715 for subscriptions in by_slot.values(): 

5716 await self._resubscribe(subscriptions, self.ssubscribe) 

5717 

5718 def _get_node_pubsub(self, node: "ClusterNode") -> PubSub: 

5719 """Get or create a PubSub instance for the given node.""" 

5720 try: 

5721 return self.node_pubsub_mapping[node.name] 

5722 except KeyError: 

5723 pubsub = PubSub( 

5724 connection_pool=_ClusterNodePoolAdapter(node), 

5725 encoder=self.cluster.encoder, 

5726 push_handler_func=self.push_handler_func, 

5727 event_dispatcher=self._event_dispatcher, 

5728 ) 

5729 # Replay shard subscriptions on reconnect with slot-aware grouping 

5730 # so that channels spanning multiple slots owned by this node do 

5731 # not trigger a CROSSSLOT error. 

5732 pubsub._resubscribe_shard_channels = MethodType( 

5733 ClusterPubSub._resubscribe_shard_channels, pubsub 

5734 ) 

5735 self._pubsub_io_lock(pubsub) 

5736 self.node_pubsub_mapping[node.name] = pubsub 

5737 return pubsub 

5738 

5739 def _find_node_name_for_pubsub(self, pubsub: PubSub) -> Optional[str]: 

5740 for name, candidate in self.node_pubsub_mapping.items(): 

5741 if candidate is pubsub: 

5742 return name 

5743 return None 

5744 

5745 @staticmethod 

5746 def _pubsub_io_lock(pubsub: PubSub) -> asyncio.Lock: 

5747 """Return the per-node pubsub's wire I/O lock, creating it on first use. 

5748 

5749 A per-node ``PubSub`` is read by whichever task polls 

5750 ``get_sharded_message`` and written by the reconciliation task 

5751 (``_migrate_shard_channel``) and by any caller of ``ssubscribe`` / 

5752 ``sunsubscribe``. ``PubSub`` guards writes with its own ``_lock`` 

5753 (``PubSub.execute_command``) but reads take no lock at all, so without 

5754 this the reader can be awaiting ``read_response`` while another task's 

5755 ``_execute`` disconnects and reconnects the same socket underneath it - 

5756 which loses the reply to the handshake and surfaces as a read timeout 

5757 followed by a broken connection. 

5758 

5759 Kept on the pubsub rather than in a dict keyed by node name so it 

5760 travels with the object through ``node_pubsub_mapping`` and cannot go 

5761 stale when a per-node pubsub is dropped and recreated. 

5762 """ 

5763 lock = getattr(pubsub, "_shard_io_lock", None) 

5764 if lock is None: 

5765 lock = asyncio.Lock() 

5766 pubsub._shard_io_lock = lock 

5767 return lock 

5768 

5769 @staticmethod 

5770 def _detach_shard_channel(pubsub: PubSub, channel: Any) -> None: 

5771 """Forget a shard channel on a per-node pubsub without a wire round trip. 

5772 

5773 ``PubSub.sunsubscribe`` only records the intent in 

5774 ``pending_unsubscribe_shard_channels``; the channel leaves 

5775 ``shard_channels`` when the server confirmation is read. So if the 

5776 ``SUNSUBSCRIBE`` never reaches the server, ``on_connect`` clears the 

5777 pending set and replays ``SSUBSCRIBE`` for the channel - on the node it 

5778 is being migrated away from, on every reconnect. Once the caller has 

5779 decided the channel belongs to a different node, the local intent is 

5780 the only truth left, so drop it here. 

5781 

5782 Unlike the sync counterpart there is no ``subscribed_event`` to clear 

5783 once the last subscription is gone: the async ``PubSub`` has no such 

5784 event, and its ``subscribed`` is a plain property derived from the 

5785 subscription dicts - including the ``shard_channels`` entry just 

5786 dropped here. 

5787 

5788 Nor is the per-node I/O lock taken, as in the sync counterpart - and 

5789 here it is not even needed for correctness: this runs to completion 

5790 without an ``await``, so the event loop already makes it atomic against 

5791 ``handle_message``'s unsubscribe bookkeeping. Should an ``await`` ever 

5792 land in this body, that bookkeeping still discards rather than removes 

5793 (see ``PubSub.handle_message``), so a racing detach cannot make it raise 

5794 ``KeyError`` into a poll no caller catches. 

5795 """ 

5796 pubsub.shard_channels.pop(channel, None) 

5797 pubsub.pending_unsubscribe_shard_channels.discard(channel) 

5798 

5799 async def _drop_node_pubsub(self, name: str, pubsub: PubSub) -> None: 

5800 """Retire a per-node pubsub and drop it from ``node_pubsub_mapping``. 

5801 

5802 Callers hold ``_shard_state_lock``, the lock that every mutation of 

5803 that mapping observes. ``aclose()`` runs under the per-node I/O lock so 

5804 the socket is not torn down beneath a concurrent bounded poll parked in 

5805 ``parse_response``, and its errors are swallowed: retiring one node's 

5806 pubsub must not abort the caller's pass. 

5807 

5808 Every caller must leave nothing subscribed on ``pubsub`` (or have lost 

5809 the node itself). An empty per-node pubsub left in the mapping keeps a 

5810 live connection with nothing subscribed on it, so ``_poll_node_pubsub`` 

5811 passes its ``connection is None`` guard and blocks reading a socket no 

5812 message can arrive on - for the whole timeout of every pass, and until 

5813 the connection is torn down when the caller passed ``timeout=None``. 

5814 

5815 Popping it from the mapping is not enough to keep it out of a poll; the 

5816 rebind below is what stops the round robin from handing it out. 

5817 """ 

5818 try: 

5819 async with self._pubsub_io_lock(pubsub): 

5820 await pubsub.aclose() 

5821 except Exception: 

5822 pass 

5823 self.node_pubsub_mapping.pop(name, None) 

5824 self._unreachable_nodes.discard(name) 

5825 # Same snapshot reason ``aclose()`` recreates this: ``_pubsubs_generator`` 

5826 # captures node_pubsub_mapping.values() into a local list inside 

5827 # ``yield from``, which the pop above does not reach - so a generator 

5828 # suspended mid-yield-from would still hand the object we just retired 

5829 # to the next poll. That cannot stall the reader the way it can in the 

5830 # sync stack (there is no subscription wait to park on, and 

5831 # ``_poll_node_pubsub``'s ``connection is None`` guard skips it), but it 

5832 # still spends one of the pass's ``range(len(node_pubsub_mapping))`` 

5833 # slots on a dead entry - so a healthy sibling loses its turn until the 

5834 # captured snapshot drains. ``type(self)`` bypasses the instance-level 

5835 # self-shadow established at __init__. Costs nothing: constructing a 

5836 # generator runs no frame, so the per-node collection loop in 

5837 # reinitialize_shard_subscriptions can rebind once per dropped node. 

5838 self._pubsubs_generator = type(self)._pubsubs_generator( # type: ignore[method-assign] 

5839 self 

5840 ) 

5841 

5842 async def _sharded_message_generator( 

5843 self, timeout: float = 0.0 

5844 ) -> Tuple[Optional[PubSub], Optional[Dict[str, Any]]]: 

5845 """Generate messages from shard channels across all nodes.""" 

5846 if timeout and len(self.node_pubsub_mapping) > 1: 

5847 # Block only when no node has data, so a busy shard does not wait 

5848 # out the slices of its idle siblings. 

5849 deadline = time.monotonic() + timeout 

5850 pubsub, message = await self._sharded_pass(0.0) 

5851 while message is None: 

5852 # A node that returns early leaves time the nodes before it 

5853 # did not get; pass again until the deadline. 

5854 start = time.monotonic() 

5855 if start >= deadline: 

5856 break 

5857 pubsub, message = await self._sharded_pass(deadline - start) 

5858 if not any(ps.connection for ps in self.node_pubsub_mapping.values()): 

5859 # A pass with no connection to read has only waited, so 

5860 # passing again before the deadline would read nothing. 

5861 break 

5862 if message is None: 

5863 # A message can reach a node after its slice ran out. 

5864 pubsub, message = await self._sharded_pass(0.0) 

5865 else: 

5866 pubsub, message = await self._sharded_pass(timeout) 

5867 if message is _DISPATCHED: 

5868 return None, None 

5869 return pubsub, message 

5870 

5871 async def _sharded_pass(self, timeout: float) -> Tuple[Optional[PubSub], Any]: 

5872 """Poll each node once; ``message`` may be ``_DISPATCHED``.""" 

5873 first_error: Optional[BaseException] = None 

5874 polled = 0 

5875 failed = 0 

5876 unconnected = 0 

5877 next_ready: Optional[float] = None 

5878 nodes = len(self.node_pubsub_mapping) 

5879 # Split the wait across the pass, otherwise every idle node ahead of the 

5880 # one with a message adds a full timeout. Each poll gets an equal share 

5881 # of what is left, so a skipped or fast-failing node passes its share on. 

5882 split = bool(timeout) and nodes > 1 

5883 node_timeout = timeout 

5884 if split: 

5885 pass_deadline = time.monotonic() + timeout 

5886 now = time.monotonic() 

5887 left = sum( 

5888 1 

5889 for ps in list(self.node_pubsub_mapping.values()) 

5890 if ps.connection is not None and self._poll_cool_off.get(ps, 0.0) <= now 

5891 ) 

5892 for _ in range(nodes): 

5893 pubsub = next(self._pubsubs_generator) 

5894 if pubsub is None: 

5895 # node_pubsub_mapping was emptied between the len() above and 

5896 # here; nothing left to poll in this pass. 

5897 break 

5898 if self._poll_cool_off: 

5899 deadline = self._poll_cool_off.get(pubsub, 0.0) 

5900 if time.monotonic() < deadline: 

5901 # In cool-off after a failed poll: skip it so the reader 

5902 # spends this pass on the nodes that can still deliver. 

5903 if next_ready is None or deadline < next_ready: 

5904 next_ready = deadline 

5905 continue 

5906 if pubsub.connection is None: 

5907 # Nothing to read and no wait: not a poll, so a pass whose 

5908 # other nodes are cooling off still sleeps below. 

5909 unconnected += 1 

5910 continue 

5911 polled += 1 

5912 if split: 

5913 node_timeout = max(pass_deadline - time.monotonic(), 0.0) / max(left, 1) 

5914 left -= 1 

5915 try: 

5916 message = await self._poll_node_pubsub(pubsub, node_timeout) 

5917 except MovedError as e: 

5918 # Handled, not failed: _handle_moved_on_read re-routes the 

5919 # offending channels and schedules reconciliation, so the next 

5920 # pass recovers. Re-raising a MovedError out of a pubsub read 

5921 # would only hand the caller an error it cannot act on. Still 

5922 # cool off: if the slots cache cannot be corrected the repair 

5923 # would otherwise re-run on every poll. 

5924 self._poll_cool_off[pubsub] = ( 

5925 time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS 

5926 ) 

5927 await self._handle_moved_on_read(pubsub, e) 

5928 continue 

5929 except (ConnectionError, TimeoutError, OSError) as e: 

5930 # One unhealthy node must not starve its healthy siblings. A 

5931 # single reader serves every per-node pubsub, so aborting the 

5932 # pass here stops delivery cluster-wide for as long as this one 

5933 # node stays unreachable - even though the slots it no longer 

5934 # serves are the only ones affected. Keep polling the rest and 

5935 # surface an error only if nothing in the pass worked, the same 

5936 # made-progress rule reinitialize_shard_subscriptions applies. 

5937 failed += 1 

5938 if first_error is None: 

5939 first_error = e 

5940 # Cool off before polling this one again. PubSub._execute 

5941 # reconnects and then retries through the connection's own 

5942 # Retry, so a single "bounded" poll on an unreachable node can 

5943 # cost its whole retry budget - far longer than the timeout the 

5944 # caller asked for. Without a cool-off the reader goes straight 

5945 # back to that node on the next pass and pays it again, which 

5946 # is what turns one sick node into a cluster-wide delivery 

5947 # stall. 

5948 self._poll_cool_off[pubsub] = ( 

5949 time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS 

5950 ) 

5951 # Mutated without _shard_state_lock, mirroring the sync stack: 

5952 # this is an advisory hint for _migrate_shard_channel's fast 

5953 # path, and both misread directions are handled there and 

5954 # self-heal - a stale entry only skips a SUNSUBSCRIBE to a dead 

5955 # node, a missing one only pays a reconnect before the same 

5956 # local forget. 

5957 node_name = self._find_node_name_for_pubsub(pubsub) 

5958 if node_name is not None: 

5959 self._unreachable_nodes.add(node_name) 

5960 if logger.isEnabledFor(logging.DEBUG): 

5961 logger.debug( 

5962 "sharded pubsub poll failed on %s: %s: %s", 

5963 node_name, 

5964 type(e).__name__, 

5965 e, 

5966 ) 

5967 # A node that has left the deployment never answers MOVED, so 

5968 # this branch is the only signal that its shard channels may 

5969 # need a new owner. Ask for a slots-cache refresh; its dispatch 

5970 # reaches on_slots_changed and reconciles. 

5971 self._schedule_topology_repair() 

5972 continue 

5973 # Emptiness check first: this is the per-message hot path, and the 

5974 # weakref lookup a WeakKeyDictionary pop needs is pure overhead 

5975 # while no node is in cool-off, which is the normal case. 

5976 if self._poll_cool_off: 

5977 self._poll_cool_off.pop(pubsub, None) 

5978 if self._unreachable_nodes: 

5979 node_name = self._find_node_name_for_pubsub(pubsub) 

5980 if node_name is not None: 

5981 self._unreachable_nodes.discard(node_name) 

5982 if message is not None: 

5983 return pubsub, message 

5984 # An unconnected node is not down, so it keeps the error from surfacing. 

5985 if first_error is not None and failed == polled + unconnected: 

5986 raise first_error 

5987 if polled == 0: 

5988 if next_ready is None: 

5989 # No node to read and none cooling off: node_pubsub_mapping is 

5990 # empty or no per-node pubsub has a connection. A reconciliation 

5991 # pass whose every attach failed leaves it that way - the GC 

5992 # drops the per-node pubsubs that hold nothing - and its shard 

5993 # channels only retry on the next slots-cache change, which a 

5994 # settled topology never sends. Ask for one, and wait as for a 

5995 # cool-off: a pass without a single await never suspends, so a 

5996 # reader loop on get_sharded_message would hold the event loop. 

5997 self._schedule_topology_repair() 

5998 next_ready = time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS 

5999 await self._wait_out_cool_off(next_ready, timeout) 

6000 return None, None 

6001 

6002 @staticmethod 

6003 async def _wait_out_cool_off(next_ready: float, timeout: Optional[float]) -> None: 

6004 """Wait out a pass in which every node was skipped for cool-off. 

6005 

6006 Such a pass does no wire read at all, so returning straight away 

6007 ignores the timeout the caller asked to block for - and a reader loop 

6008 on ``get_sharded_message`` polls back immediately, spinning until the 

6009 cool-off expires instead of blocking. Sleep instead: until the 

6010 earliest cool-off is over, never longer than the caller's timeout, and 

6011 not at all for a non-blocking poll. 

6012 """ 

6013 if timeout is not None and timeout <= 0: 

6014 return 

6015 delay = next_ready - time.monotonic() 

6016 if delay <= 0: 

6017 return 

6018 if timeout is not None: 

6019 delay = min(delay, timeout) 

6020 await asyncio.sleep(delay) 

6021 

6022 def _poll_io_lock(self, pubsub: PubSub, timeout: Optional[float]): 

6023 """Guard a per-node poll against concurrent writers on the same socket. 

6024 

6025 ``timeout=None`` makes ``_poll_node_pubsub``'s read wait indefinitely, 

6026 so holding the lock across it would block reconciliation for as long as 

6027 no message arrives. Such a caller drives the pubsub itself and gets the 

6028 pre-existing unguarded behavior; every bounded poll - which is what 

6029 ``ClusterPubSub``'s own callers use - is serialized. 

6030 """ 

6031 if timeout is None: 

6032 return nullcontext() 

6033 return self._pubsub_io_lock(pubsub) 

6034 

6035 async def _poll_node_pubsub(self, pubsub: PubSub, timeout: Optional[float]) -> Any: 

6036 """Read one message from a per-node pubsub, dispatching outside the lock. 

6037 

6038 Splits ``PubSub.get_message`` so the per-node I/O lock covers the wire 

6039 read only. ``handle_message`` awaits a subscribed channel's user 

6040 handler inline, and a handler is free to await ``ssubscribe`` / 

6041 ``sunsubscribe`` on this ``ClusterPubSub`` - which takes 

6042 ``_shard_state_lock`` and then the same I/O lock. ``asyncio.Lock`` is 

6043 not reentrant, so holding the I/O lock across the handler hangs the 

6044 reader task permanently and silently on the re-acquire; even a 

6045 task-reentrant lock would still deadlock against the reconciliation 

6046 task, which holds ``_shard_state_lock`` and awaits that I/O lock. 

6047 

6048 The two halves of ``handle_message`` are mutually exclusive: 

6049 ``UNSUBSCRIBE_MESSAGE_TYPES`` does subscription bookkeeping and never 

6050 reaches a handler, ``PUBLISH_MESSAGE_TYPES`` only dispatches. So 

6051 bookkeeping stays inside the lock - it mutates the very 

6052 ``shard_channels`` / ``pending_unsubscribe_shard_channels`` that 

6053 ``ssubscribe`` / ``sunsubscribe`` mutate under this lock - and only the 

6054 dispatch moves out. The cost is a narrow race: a reconciliation pass 

6055 that detaches the channel between the read and the dispatch makes the 

6056 handler lookup miss, so the message is returned to the caller instead 

6057 of dispatched. That is the same in-flight-during-unsubscribe race 

6058 ``PubSub`` itself has, and closing it would mean duplicating 

6059 ``handle_message``'s dispatch here. 

6060 

6061 The async ``PubSub`` has no ``subscribed_event`` for the sync 

6062 counterpart's subscription wait to mirror, but the connectionless state 

6063 that wait guards against still has to be handled: a per-node pubsub 

6064 enters ``node_pubsub_mapping`` before its first ``SSUBSCRIBE`` 

6065 (``_get_node_pubsub``) and is left connectionless by ``aclose()`` (the 

6066 GC in ``reinitialize_shard_subscriptions``), while ``parse_response`` 

6067 raises ``RuntimeError`` on a ``None`` connection - which neither poll 

6068 site catches. ``_pubsubs_generator`` yields from a snapshot of the 

6069 mapping, so it can hand out a pubsub the GC has just dropped. Checking 

6070 under the I/O lock rather than before it closes that window for every 

6071 bounded poll, because the GC ``aclose()``s under the same lock. 

6072 """ 

6073 async with self._poll_io_lock(pubsub, timeout): 

6074 if pubsub.connection is None: 

6075 # Not connected yet, or closed by a concurrent teardown. 

6076 # Reading would raise RuntimeError; skip this node instead. 

6077 return None 

6078 response = await pubsub.parse_response( 

6079 block=(timeout is None), timeout=timeout 

6080 ) 

6081 # get_message's truthiness test, not "is None": a health check 

6082 # reply filtered out by parse_response, or an empty bulk, is "no 

6083 # message" rather than a message to parse. 

6084 if not response: 

6085 return None 

6086 if not self._is_publish_response(response): 

6087 # Don't pass ignore_subscribe_messages here - let 

6088 # get_sharded_message handle the filtering after processing 

6089 # subscription state changes 

6090 return await pubsub.handle_message( 

6091 response, ignore_subscribe_messages=False 

6092 ) 

6093 message = await pubsub.handle_message(response, ignore_subscribe_messages=False) 

6094 # None here means a handler took it, which is not an empty poll. 

6095 return _DISPATCHED if message is None else message 

6096 

6097 @staticmethod 

6098 def _is_publish_response(response: Any) -> bool: 

6099 """Whether a raw pubsub reply can make ``handle_message`` dispatch. 

6100 

6101 ``handle_message`` awaits a user handler only for 

6102 ``PUBLISH_MESSAGE_TYPES``; every other reply either does subscription 

6103 bookkeeping (``UNSUBSCRIBE_MESSAGE_TYPES``) or is a pong, and the two 

6104 branches are mutually exclusive. A non-sequence reply is the bare-PING 

6105 shape ``handle_message`` rewrites into a pong, so it cannot dispatch 

6106 either. 

6107 """ 

6108 if not isinstance(response, (list, tuple)): 

6109 return False 

6110 return str_if_bytes(response[0]) in PubSub.PUBLISH_MESSAGE_TYPES 

6111 

6112 def _schedule_topology_repair(self) -> None: 

6113 """Ask for a slots-cache refresh after a poll could not reach a node. 

6114 

6115 ``reinitialize_shard_subscriptions`` only ever runs from a slots-cache 

6116 change notification, and a node that has been rebooted or taken out of 

6117 the deployment answers ``ECONNREFUSED`` rather than ``MOVED`` - so the 

6118 read path itself has to ask, or the shard channels pinned to that node 

6119 stay there for the lifetime of the pubsub. 

6120 

6121 The refresh is asked for on the cluster client like every other 

6122 error-triggered one, and ``RedisCluster.initialize`` runs it once due: 

6123 it serializes concurrent callers, keeps the request when the refresh 

6124 fails, and clears it when it succeeds. ``NodesManager.initialize`` drops 

6125 nodes that have left the topology and dispatches 

6126 ``AsyncAfterSlotsCacheRefreshEvent``, which reaches 

6127 ``on_slots_changed``. Run it as a task so a bounded poll does not pay 

6128 for a ``CLUSTER SLOTS`` round trip, and throttle it because a node that 

6129 is down fails every poll. 

6130 """ 

6131 if not self.shard_channels: 

6132 return 

6133 now = time.monotonic() 

6134 if now < self._next_topology_repair: 

6135 return 

6136 self._next_topology_repair = now + SHARD_TOPOLOGY_REPAIR_INTERVAL_SECONDS 

6137 # Not tracked in _reconcile_tasks: that set is cancelled by aclose(), 

6138 # and ``initialize`` refreshes the slots cache of the whole cluster 

6139 # client, which every other command on it reads - closing one pubsub 

6140 # must not abort a refresh in flight, leaving the shared cache stale 

6141 # until some later MOVED or failed poll asks again. The sync 

6142 # counterpart has the same property for free: ``reset()`` retires the 

6143 # reconciliation executor with ``cancel_futures=True``, which drops 

6144 # queued work but lets a running ``initialize`` finish. 

6145 # Ask for the refresh on the cluster client: a refresh that fails 

6146 # leaves the request for the next command or repair, as on sync, and 

6147 # one that succeeds answers it, so no command repeats it 

6148 self.cluster._request_refresh() 

6149 if not self.cluster.nodes_manager._refresh_due(self.cluster.retry): 

6150 # Subject to the topology refresh minimum interval like every other 

6151 # error-triggered refresh: the next command, or the next repair, 

6152 # runs it once it is due 

6153 return 

6154 task = asyncio.create_task(self.cluster.initialize()) 

6155 self._topology_repair_tasks.add(task) 

6156 task.add_done_callback(self._topology_repair_tasks.discard) 

6157 task.add_done_callback(self._log_reconcile_task_exception) 

6158 

6159 async def _handle_moved_on_read(self, pubsub: PubSub, error: MovedError) -> None: 

6160 """Re-route shard channels pinned to a node that lost their slot. 

6161 

6162 ``PubSub.on_connect`` replays ``SSUBSCRIBE`` to the node its connection 

6163 is bound to, so after a slot migration that node answers ``MOVED``. 

6164 ``MovedError`` is not in ``Retry.supported_errors`` and no other code on 

6165 the read path refreshes the slots cache, so a shard channel left on a 

6166 former owner could never recover. Drop the offending channels from this 

6167 pubsub so the replay stops, forget their recorded owner so 

6168 ``reinitialize_shard_subscriptions`` does not short-circuit on an 

6169 already-advanced reverse index, then apply the redirect and reconcile. 

6170 """ 

6171 node_name = self._find_node_name_for_pubsub(pubsub) 

6172 logger.debug( 

6173 "sharded pubsub: %s no longer owns slot %s; re-routing its shard channels", 

6174 node_name, 

6175 error.slot_id, 

6176 ) 

6177 async with self._shard_state_lock: 

6178 for channel in list(pubsub.shard_channels): 

6179 if key_slot(self.encoder.encode(channel)) != error.slot_id: 

6180 continue 

6181 self._detach_shard_channel(pubsub, channel) 

6182 if self._shard_channel_to_node.get(channel) == node_name: 

6183 del self._shard_channel_to_node[channel] 

6184 # The detach above can leave this pubsub with nothing subscribed - 

6185 # a node that lost its only slot answers MOVED for every channel it 

6186 # held. Retire it here rather than leave it in the mapping for a 

6187 # collector elsewhere: no SUNSUBSCRIBE confirmation will arrive for 

6188 # a channel forgotten locally, so get_sharded_message's collector 

6189 # cannot reach it, and the reconciliation pass scheduled below only 

6190 # GCs it once its task gets to run - a whole poll cool-off later, 

6191 # at best, while a poll that reaches the empty pubsub first blocks 

6192 # on a socket no message can arrive on (see _drop_node_pubsub). 

6193 if node_name is not None and not pubsub.subscribed: 

6194 await self._drop_node_pubsub(node_name, pubsub) 

6195 # move_slot applies the redirect to the slots cache and dispatches 

6196 # AsyncAfterSlotsCacheRefreshEvent, which reaches on_slots_changed. Call 

6197 # on_slots_changed unconditionally too: move_slot skips the dispatch on 

6198 # a circular MOVED, and a duplicate reconciliation pass is a no-op. 

6199 # move_slot indexes slots_cache by the redirected slot, so an 

6200 # as-yet-uncovered slot raises: log and still reconcile rather than let 

6201 # a repair attempt break a pubsub read. 

6202 if node_name is not None: 

6203 # A redirect without a host is relative to the node that sent it, 

6204 # and a node's name is its host and port 

6205 _fill_missing_redirect_host(error, node_name.rsplit(":", 1)[0]) 

6206 try: 

6207 await self.cluster.nodes_manager.move_slot(error) 

6208 except Exception as exc: 

6209 logger.debug( 

6210 "sharded pubsub: could not apply the redirect for slot %s: %s: %s", 

6211 error.slot_id, 

6212 type(exc).__name__, 

6213 exc, 

6214 ) 

6215 await self.on_slots_changed() 

6216 

6217 def _pubsubs_generator(self) -> Generator[Optional[PubSub], None, None]: 

6218 """Generator that yields PubSub instances in round-robin fashion. 

6219 

6220 Never returns: a generator that returns is exhausted for good and only 

6221 ``reset`` recreates this one, so a momentarily empty 

6222 ``node_pubsub_mapping`` - reconciliation drops a per-node pubsub before 

6223 creating its replacement - would stop the round robin permanently. 

6224 Yields ``None`` for an empty mapping instead, which lets the caller skip 

6225 the slot without this loop spinning on an empty list. 

6226 """ 

6227 while True: 

6228 current_nodes = list(self.node_pubsub_mapping.values()) 

6229 if not current_nodes: 

6230 yield None 

6231 else: 

6232 yield from current_nodes 

6233 

6234 async def get_sharded_message( 

6235 self, 

6236 ignore_subscribe_messages: bool = False, 

6237 timeout: float = 0.0, 

6238 target_node: Optional["ClusterNode"] = None, 

6239 ) -> Optional[Dict[str, Any]]: 

6240 """ 

6241 Get the next sharded pubsub message, or ``None`` if none is available. 

6242 

6243 Polls the per-node connections in round robin unless ``target_node`` is 

6244 given, and keeps shard channels attached to the node that currently 

6245 owns their slot: a failed poll cools that node off and asks for a 

6246 slots-cache refresh, and a ``MOVED`` reply re-routes the affected 

6247 channels to their new owner. Neither reaches the caller. A connection 

6248 failure is surfaced only when every node polled in the pass failed, so 

6249 one unreachable node does not stop delivery from its healthy siblings. 

6250 

6251 ``target_node`` opts out of that shielding: a caller that names a 

6252 single node has no sibling to protect, so connection errors propagate. 

6253 A ``MOVED`` reply is still handled rather than raised. 

6254 

6255 :param ignore_subscribe_messages: Whether to ignore subscribe messages 

6256 :param timeout: Timeout for message retrieval 

6257 :param target_node: Specific node to get message from 

6258 :return: Message dictionary or None 

6259 """ 

6260 pubsub: Optional[PubSub] 

6261 if target_node: 

6262 pubsub = self.node_pubsub_mapping.get(target_node.name) 

6263 if pubsub: 

6264 try: 

6265 message = await self._poll_node_pubsub(pubsub, timeout) 

6266 if message is _DISPATCHED: 

6267 message = None 

6268 except MovedError as e: 

6269 # Same handling as the round-robin path: the caller cannot 

6270 # act on a MovedError raised out of a pubsub read, and the 

6271 # channels this node no longer owns have to be re-routed or 

6272 # they never recover. Cool off too, so a slots cache that 

6273 # cannot be corrected does not re-run the repair on every 

6274 # poll. Unlike that path, connectivity errors still 

6275 # propagate: they are swallowed there only to keep one sick 

6276 # node from starving its healthy siblings, and a caller that 

6277 # named a single node has no sibling to protect. 

6278 self._poll_cool_off[pubsub] = ( 

6279 time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS 

6280 ) 

6281 await self._handle_moved_on_read(pubsub, e) 

6282 message = None 

6283 else: 

6284 message = None 

6285 else: 

6286 pubsub, message = await self._sharded_message_generator(timeout=timeout) 

6287 

6288 if message is None: 

6289 return None 

6290 # Only sunsubscribe mutates cluster-level shard state; bypassing the 

6291 # lock on the data-message hot path keeps smessage delivery from 

6292 # competing with the reconciliation task for _shard_state_lock. 

6293 if str_if_bytes(message["type"]) == "sunsubscribe": 

6294 # Serialize state mutation against reinitialize_shard_subscriptions 

6295 # (background task). The blocking _poll_node_pubsub above 

6296 # intentionally runs outside the lock so reconciliation is not 

6297 # stalled by long polls. 

6298 async with self._shard_state_lock: 

6299 if ( 

6300 message["channel"] in self.pending_unsubscribe_shard_channels 

6301 and message["channel"] not in pubsub.shard_channels 

6302 ): 

6303 # User-initiated sunsubscribe: drop from cluster-level tracking. 

6304 self.pending_unsubscribe_shard_channels.remove(message["channel"]) 

6305 self.shard_channels.pop(message["channel"], None) 

6306 self._shard_channel_to_node.pop(message["channel"], None) 

6307 # Drop the per-node pubsub that delivered the confirmation once 

6308 # it no longer holds any shard subscriptions, regardless of 

6309 # whether the sunsubscribe was user-initiated or driven by 

6310 # slot-migration reconciliation (_migrate_shard_channel, which 

6311 # intentionally does not add the channel to 

6312 # pending_unsubscribe_shard_channels). This releases the 

6313 # dedicated connection that would otherwise linger. 

6314 # Identifying the receiving pubsub directly (rather than via 

6315 # the cluster's current slot map) is required after slot 

6316 # migration, where the channel's owner is no longer the node 

6317 # that received our original SSUBSCRIBE. 

6318 if pubsub is not None and not pubsub.subscribed: 

6319 name = self._find_node_name_for_pubsub(pubsub) 

6320 if name is not None: 

6321 await self._drop_node_pubsub(name, pubsub) 

6322 

6323 # Only suppress subscribe/unsubscribe messages, not data messages (smessage) 

6324 if str_if_bytes(message["type"]) in ("ssubscribe", "sunsubscribe"): 

6325 if self.ignore_subscribe_messages or ignore_subscribe_messages: 

6326 return None 

6327 return message 

6328 

6329 async def ssubscribe( 

6330 self, *args: ChannelT | Subscription, **kwargs: PubSubHandler 

6331 ) -> None: 

6332 """ 

6333 Subscribe to shard channels. 

6334 

6335 :param args: Channel names or ``Subscription`` objects 

6336 :param kwargs: Channel names with handlers 

6337 """ 

6338 s_channels = parse_pubsub_subscriptions(args, kwargs) 

6339 

6340 if not s_channels: 

6341 return 

6342 await self._ensure_cluster_initialized() 

6343 

6344 # Serialize against reinitialize_shard_subscriptions (background 

6345 # task) so the reverse index, shard_channels, and node_pubsub_mapping 

6346 # are not mutated concurrently. _migrate_shard_channel below does not 

6347 # re-acquire this lock (asyncio.Lock is non-reentrant). 

6348 async with self._shard_state_lock: 

6349 for s_channel, handler in s_channels.items(): 

6350 node = self.cluster.get_node_from_key(s_channel) 

6351 if not node: 

6352 continue 

6353 # Lazy re-route: if this channel is already tracked against a 

6354 # different node (e.g. after a slot migration), migrate it now 

6355 # so the caller's intent is applied on the current owner. 

6356 normalized_key = next(iter(self._normalize_keys({s_channel: None}))) 

6357 old_name = self._shard_channel_to_node.get(normalized_key) 

6358 if old_name and old_name != node.name: 

6359 # Match PubSub.ssubscribe() dict.update() semantics: the 

6360 # caller's newly supplied handler (including None) always 

6361 # overrides any previously registered handler. 

6362 await self._migrate_shard_channel( 

6363 normalized_key, 

6364 handler, 

6365 old_name, 

6366 node, 

6367 ) 

6368 continue 

6369 pubsub = self._get_node_pubsub(node) 

6370 async with self._pubsub_io_lock(pubsub): 

6371 if handler: 

6372 await pubsub.ssubscribe(Subscription(s_channel, handler)) 

6373 else: 

6374 await pubsub.ssubscribe(s_channel) 

6375 self.shard_channels.update(pubsub.shard_channels) 

6376 self._shard_channel_to_node[normalized_key] = node.name 

6377 self.pending_unsubscribe_shard_channels.difference_update( 

6378 self._normalize_keys({s_channel: None}) 

6379 ) 

6380 

6381 async def sunsubscribe(self, *args: Any) -> None: 

6382 """ 

6383 Unsubscribe from shard channels. 

6384 

6385 :param args: Channel names to unsubscribe from. If empty, unsubscribe from all. 

6386 """ 

6387 if args: 

6388 args = list_or_args(args[0], args[1:]) 

6389 else: 

6390 args = list(self.shard_channels.keys()) 

6391 

6392 if not self.node_pubsub_mapping: 

6393 return 

6394 # Keep initialization outside the shard-state lock: it can dispatch a 

6395 # topology refresh whose reconciler must remain able to make progress. 

6396 await self._ensure_cluster_initialized() 

6397 

6398 # Serialize against reinitialize_shard_subscriptions: the reverse 

6399 # index and node_pubsub_mapping must not change between the lookup 

6400 # and the per-node sunsubscribe call below. 

6401 async with self._shard_state_lock: 

6402 for s_channel in args: 

6403 normalized_key = next(iter(self._normalize_keys({s_channel: None}))) 

6404 # Route via the reverse index so we unsubscribe on the node 

6405 # that actually holds the subscription. After a slot migration 

6406 # the cluster's current owner may no longer be that node. 

6407 name = self._shard_channel_to_node.get(normalized_key) 

6408 if name and name in self.node_pubsub_mapping: 

6409 pubsub = self.node_pubsub_mapping[name] 

6410 else: 

6411 node = self.cluster.get_node_from_key(s_channel) 

6412 if not node or node.name not in self.node_pubsub_mapping: 

6413 continue 

6414 pubsub = self.node_pubsub_mapping[node.name] 

6415 async with self._pubsub_io_lock(pubsub): 

6416 await pubsub.sunsubscribe(s_channel) 

6417 self.pending_unsubscribe_shard_channels.update( 

6418 pubsub.pending_unsubscribe_shard_channels 

6419 ) 

6420 

6421 async def reinitialize_shard_subscriptions(self) -> None: 

6422 """ 

6423 Reconcile per-node shard subscriptions against the cluster's current 

6424 slot ownership map. For each tracked shard channel whose owning node 

6425 has changed (e.g. after CLUSTER SETSLOT / failover), sunsubscribe on 

6426 the old node's pubsub and ssubscribe on the new owner's pubsub, 

6427 preserving any registered handler. 

6428 """ 

6429 uncovered: list = [] 

6430 made_progress = False 

6431 first_migrate_error: Optional[BaseException] = None 

6432 async with self._shard_state_lock: 

6433 for channel, handler in list(self.shard_channels.items()): 

6434 old_name = self._shard_channel_to_node.get(channel) 

6435 if channel in self.pending_unsubscribe_shard_channels: 

6436 # A reconnect clears the per-node pending set and replays 

6437 # SSUBSCRIBE, so a channel the node still holds without a 

6438 # pending unsubscribe is subscribed again, not leaving, and 

6439 # its cluster-level entry is stale. Check the pending set 

6440 # first: handle_message drops the channel before its 

6441 # pending entry. 

6442 old_pubsub = self.node_pubsub_mapping.get(old_name) 

6443 if ( 

6444 old_pubsub is None 

6445 or channel in old_pubsub.pending_unsubscribe_shard_channels 

6446 or channel not in old_pubsub.shard_channels 

6447 ): 

6448 continue 

6449 self.pending_unsubscribe_shard_channels.discard(channel) 

6450 try: 

6451 new_node = self.cluster.get_node_from_key(channel) 

6452 except SlotNotCoveredError: 

6453 # Slot is transiently uncovered (mid-migration / partial 

6454 # topology refresh). Defer this channel so coverable 

6455 # siblings still reconcile this pass; we surface the 

6456 # error below so the caller (and logs) know not every 

6457 # channel was reconciled. Retry happens on the next 

6458 # slots-cache change notification. 

6459 uncovered.append(channel) 

6460 continue 

6461 if old_name == new_node.name: 

6462 owner = self.node_pubsub_mapping.get(new_node.name) 

6463 if owner is not None and channel in owner.shard_channels: 

6464 continue 

6465 # The reverse index names this node but the subscription is 

6466 # not there. _migrate_shard_channel detaches from the old 

6467 # owner before it advances the index, so a pass that failed 

6468 # to attach leaves the channel subscribed nowhere - and once 

6469 # ownership moves back, this short-circuit would skip it for 

6470 # the lifetime of the pubsub. Re-attach instead of trusting 

6471 # the index; there is nothing to sunsubscribe from. 

6472 old_name = None 

6473 try: 

6474 await self._migrate_shard_channel( 

6475 channel, handler, old_name, new_node 

6476 ) 

6477 made_progress = True 

6478 except (ConnectionError, TimeoutError, OSError) as e: 

6479 # Transient connectivity error while subscribing on the 

6480 # new owner (or unsubscribing on the old owner if its 

6481 # handler chose to re-raise). Do not abort reconciliation 

6482 # for sibling channels: _shard_channel_to_node was not 

6483 # advanced for this channel, so the next slots-cache 

6484 # change notification will retry it. 

6485 logger.warning( 

6486 "shard channel %r migration deferred: %s: %s", 

6487 channel, 

6488 type(e).__name__, 

6489 e, 

6490 ) 

6491 if first_migrate_error is None: 

6492 first_migrate_error = e 

6493 continue 

6494 # Garbage-collect per-node pubsubs that no longer hold any 

6495 # subscription so their connections are released. 

6496 for name, pubsub in list(self.node_pubsub_mapping.items()): 

6497 if not pubsub.subscribed: 

6498 await self._drop_node_pubsub(name, pubsub) 

6499 if uncovered: 

6500 # Surface the uncovered channels so the caller (and observer 

6501 # notification path) knows reconciliation was incomplete. All 

6502 # coverable siblings have already been migrated above. 

6503 raise SlotNotCoveredError( 

6504 f"{len(uncovered)} shard channel(s) left unreconciled; " 

6505 f"slot(s) not covered by the cluster: {uncovered!r}" 

6506 ) 

6507 if first_migrate_error is not None and not made_progress: 

6508 # Every migration attempted in this pass failed transiently and 

6509 # nothing else made progress. Re-raise the first caught error 

6510 # (typically the root cause; later failures are often downstream 

6511 # symptoms of the same unreachable node) so the task's done- 

6512 # callback surfaces a single representative failure through the 

6513 # same logger channel used for SlotNotCoveredError. Per-channel 

6514 # WARNINGs above preserve the full forensic detail. 

6515 raise first_migrate_error 

6516 

6517 async def _forget_shard_channel_on_old_node( 

6518 self, old_pubsub: PubSub, channel: Any, old_name: str 

6519 ) -> None: 

6520 """Drop a migrating shard channel from a node we could not tell about it. 

6521 

6522 Forget the channel locally: the caller advances the reverse index to the 

6523 new owner, so reconciliation will never revisit this channel, while 

6524 ``on_connect`` would keep replaying ``SSUBSCRIBE`` for it to this very 

6525 node on every reconnect - the server would answer ``MOVED`` and the 

6526 subscription would never work again. 

6527 """ 

6528 self._detach_shard_channel(old_pubsub, channel) 

6529 # Drop the per-node pubsub when either the old node has left the cluster 

6530 # topology - no reconnect target, so the round-robin generator must stop 

6531 # yielding a dead one, and any sibling subscription it still holds 

6532 # recovers through ``PubSub._execute``'s reconnect and ``on_connect`` 

6533 # replay - or the detach above left it with nothing subscribed. 

6534 # 

6535 # The empty case cannot be deferred to a collector elsewhere, because 

6536 # neither of the other two can reach it. ``get_sharded_message``'s 

6537 # unsubscribe branch needs a ``SUNSUBSCRIBE`` confirmation, and none will 

6538 # arrive for a channel this method forgot locally - that is the whole 

6539 # reason it is forgotten. ``reinitialize_shard_subscriptions``'s 

6540 # end-of-pass GC only runs for the reconciliation caller, while 

6541 # ``ssubscribe``'s lazy re-route reaches here without it. An empty pubsub 

6542 # left in the mapping keeps a live connection with nothing subscribed on 

6543 # it, so ``_poll_node_pubsub`` passes its ``connection is None`` guard and 

6544 # blocks reading a socket no message can arrive on: forever when the 

6545 # caller passed ``timeout=None``, and for the whole timeout of every pass 

6546 # otherwise, before a single healthy node is read. 

6547 if ( 

6548 self.cluster.get_node(node_name=old_name) is None 

6549 or not old_pubsub.subscribed 

6550 ): 

6551 await self._drop_node_pubsub(old_name, old_pubsub) 

6552 

6553 async def _migrate_shard_channel( 

6554 self, 

6555 channel: Any, 

6556 handler: Optional[Callable], 

6557 old_name: Optional[str], 

6558 new_node: "ClusterNode", 

6559 ) -> None: 

6560 # Detach from the old per-node pubsub, best-effort: the old node may 

6561 # already be unreachable during migration / failover. 

6562 if old_name and old_name in self.node_pubsub_mapping: 

6563 old_pubsub = self.node_pubsub_mapping[old_name] 

6564 if old_name in self._unreachable_nodes: 

6565 # The reader has just failed to reach this node, so a 

6566 # ``SUNSUBSCRIBE`` cannot arrive. Skip it: the attempt would pay 

6567 # a full reconnect (and the client's whole retry budget) behind 

6568 # the reader on the same per-node io lock, all while this pass 

6569 # holds ``_shard_state_lock`` - which is what turns one departed 

6570 # node into a migration slow enough to look like a permanent 

6571 # delivery stall. 

6572 await self._forget_shard_channel_on_old_node( 

6573 old_pubsub, channel, old_name 

6574 ) 

6575 else: 

6576 try: 

6577 async with self._pubsub_io_lock(old_pubsub): 

6578 await old_pubsub.sunsubscribe(channel) 

6579 except (ConnectionError, TimeoutError, OSError): 

6580 # redis-py's Connection has already called ``disconnect()`` 

6581 # before raising (see Connection.read_response / 

6582 # send_packed_command with ``disconnect_on_error=True``), so 

6583 # ``old_pubsub``'s dedicated socket is gone and the 

6584 # ``SUNSUBSCRIBE`` never reached the server. 

6585 await self._forget_shard_channel_on_old_node( 

6586 old_pubsub, channel, old_name 

6587 ) 

6588 # Attach to the new per-node pubsub, preserving the handler. Decode to 

6589 # a text key only when we must pass it as a kwarg (handler present). 

6590 new_pubsub = self._get_node_pubsub(new_node) 

6591 async with self._pubsub_io_lock(new_pubsub): 

6592 if handler: 

6593 await new_pubsub.ssubscribe(Subscription(channel, handler)) 

6594 else: 

6595 await new_pubsub.ssubscribe(channel) 

6596 self.shard_channels.update(new_pubsub.shard_channels) 

6597 normalized_key = next(iter(self._normalize_keys({channel: None}))) 

6598 self._shard_channel_to_node[normalized_key] = new_node.name 

6599 self.pending_unsubscribe_shard_channels.difference_update( 

6600 self._normalize_keys({channel: None}) 

6601 ) 

6602 

6603 async def on_slots_changed(self) -> None: 

6604 # Observer hook invoked by NodesManager after a slots-cache refresh. 

6605 # Schedule reconciliation as a separate task so the caller's code 

6606 # path (typically MovedError handling in _execute_command) is not 

6607 # blocked on the network I/O performed by reinitialize_shard_ 

6608 # subscriptions. No-op when there are no shard subscriptions to 

6609 # reconcile. 

6610 if not self.shard_channels: 

6611 return 

6612 task = asyncio.create_task(self.reinitialize_shard_subscriptions()) 

6613 self._reconcile_tasks.add(task) 

6614 task.add_done_callback(self._reconcile_tasks.discard) 

6615 # Consume the task's exception (if any) so Python does not emit a 

6616 # "Task exception was never retrieved" warning. reinitialize_shard_ 

6617 # subscriptions surfaces SlotNotCoveredError when a slot is still 

6618 # transiently uncovered; route it through the same logger channel 

6619 # as sync ClusterPubSubSlotsCacheListener for consistent observability. 

6620 task.add_done_callback(self._log_reconcile_task_exception) 

6621 

6622 @staticmethod 

6623 def _log_reconcile_task_exception(task: "asyncio.Task") -> None: 

6624 if task.cancelled(): 

6625 return 

6626 exc = task.exception() 

6627 if exc is not None: 

6628 logger.error( 

6629 "shard subscription reconciliation failed: %r", exc, exc_info=exc 

6630 ) 

6631 

6632 def get_redis_connection(self) -> Optional["AbstractConnection"]: 

6633 """ 

6634 Get the Redis connection of the pubsub connected node. 

6635 

6636 Returns the pubsub's dedicated connection (acquired from its own 

6637 connection pool), not from the ClusterNode's connection pool. 

6638 This avoids the connection pool resource leak that would occur 

6639 if we called node.acquire_connection() without releasing. 

6640 """ 

6641 # Return the pubsub's own dedicated connection, which is acquired 

6642 # from self.connection_pool when executing pubsub commands. 

6643 # This is safe because it's the connection dedicated to this pubsub 

6644 # instance, not a shared pool connection from the ClusterNode. 

6645 return self.connection 

6646 

6647 async def aclose(self) -> None: 

6648 """ 

6649 Disconnect the pubsub connection. 

6650 """ 

6651 # Cancel and gather in-flight reconciliation tasks BEFORE acquiring 

6652 # _shard_state_lock. The tasks themselves take that lock inside 

6653 # reinitialize_shard_subscriptions; since asyncio.Lock is non- 

6654 # reentrant, gathering while holding it would deadlock. Awaiting 

6655 # each task with suppressed CancelledError also avoids unhandled- 

6656 # exception warnings if the task was created but not yet scheduled. 

6657 # _topology_repair_tasks is deliberately left alone: it holds 

6658 # NodesManager.initialize() calls that refresh the whole client's 

6659 # slots cache, which is not this pubsub's to abort (see 

6660 # _schedule_topology_repair). The set keeps them referenced until 

6661 # they finish and discard themselves. 

6662 if self._reconcile_tasks: 

6663 tasks = list(self._reconcile_tasks) 

6664 for task in tasks: 

6665 task.cancel() 

6666 await asyncio.gather(*tasks, return_exceptions=True) 

6667 # Hold _shard_state_lock across the rest of the teardown so it 

6668 # observes the same mutual-exclusion discipline as ssubscribe / 

6669 # sunsubscribe / get_sharded_message / reinitialize_shard_ 

6670 # subscriptions, which all mutate shard_channels, 

6671 # _shard_channel_to_node, and node_pubsub_mapping under this lock. 

6672 # Without it, super().aclose() rebinds shard_channels and 

6673 # pending_unsubscribe_shard_channels in parallel with a concurrent 

6674 # user-coroutine mutation that resumes during one of the awaits 

6675 # below, silently dropping subscription intent. 

6676 async with self._shard_state_lock: 

6677 self._reconcile_tasks.clear() 

6678 # Close all shard pubsub instances first, under the per-node I/O 

6679 # lock so the socket is not torn down beneath a concurrent bounded 

6680 # poll parked in parse_response. A bounded poll holds the lock only 

6681 # for its timeout, and an unbounded one holds nullcontext() (see 

6682 # _poll_io_lock), so teardown never waits indefinitely here. 

6683 for pubsub in self.node_pubsub_mapping.values(): 

6684 async with self._pubsub_io_lock(pubsub): 

6685 await pubsub.aclose() 

6686 # Drop the now-dead per-node pubsubs from the mapping so the 

6687 # round-robin in _pubsubs_generator / _sharded_message_generator 

6688 # cannot yield them between teardown and re-subscription. 

6689 self.node_pubsub_mapping.clear() 

6690 self._unreachable_nodes.clear() 

6691 # Drop the throttle window too: a reused pubsub that keeps a 

6692 # deadline armed before the teardown would skip the first repair 

6693 # after resubscribing, delaying the move of its shard channels 

6694 # off a node that is already gone. 

6695 self._next_topology_repair = 0.0 

6696 # _pubsubs_generator captures node_pubsub_mapping.values() into 

6697 # a local list inside ``yield from``; clearing the mapping does 

6698 # not reach references already held by that captured snapshot, 

6699 # so a generator suspended mid-yield-from would still surface 

6700 # the now-aclose()'d per-node pubsubs after re-subscription. 

6701 # Recreate it to drop the captured list. type(self) bypasses 

6702 # the instance-level self-shadow established at __init__ 

6703 # (self._pubsubs_generator = self._pubsubs_generator()). 

6704 self._pubsubs_generator = type(self)._pubsubs_generator( # type: ignore[method-assign] 

6705 self 

6706 ) 

6707 # Let parent handle self.connection disconnect under the lock 

6708 # (includes disconnect, release to pool, and clearing 

6709 # self.connection) 

6710 await super().aclose() 

6711 # Clear the reverse index so a reused instance doesn't route 

6712 # against stale mappings. super().aclose() has already cleared 

6713 # shard_channels. 

6714 self._shard_channel_to_node.clear() 

6715 

6716 def _raise_on_invalid_node( 

6717 self, 

6718 redis_cluster: "RedisCluster", 

6719 node: Optional["ClusterNode"], 

6720 host: Optional[str], 

6721 port: Optional[int], 

6722 ) -> None: 

6723 """ 

6724 Raise a RedisClusterException if the node is None or doesn't exist in 

6725 the cluster. 

6726 """ 

6727 if node is None or redis_cluster.get_node(node_name=node.name) is None: 

6728 raise RedisClusterException( 

6729 f"Node {host}:{port} doesn't exist in the cluster" 

6730 ) 

6731 

6732 async def execute_command(self, *args: Any, **kwargs: Any) -> Any: 

6733 """ 

6734 Execute a command on the appropriate cluster node. 

6735 

6736 Taken code from redis-py and tweaked to make it work within a cluster. 

6737 """ 

6738 # NOTE: don't parse the response in this function -- it could pull a 

6739 # legitimate message off the stack if the connection is already 

6740 # subscribed to one or more channels 

6741 

6742 await self._ensure_cluster_initialized() 

6743 

6744 # For shard commands, route to appropriate node 

6745 command = args[0].upper() if args else "" 

6746 if command in ("SSUBSCRIBE", "SUNSUBSCRIBE", "SPUBLISH"): 

6747 if len(args) > 1: 

6748 # ssubscribe / sunsubscribe own both the per-node I/O lock and 

6749 # the shard_channels / _shard_channel_to_node bookkeeping, so 

6750 # delegate to them instead of dispatching raw. A raw dispatch 

6751 # writes the socket unguarded against a concurrent poll and 

6752 # records nothing, leaving the channel invisible to the reader 

6753 # loop and to on_connect's replay. 

6754 if command == "SSUBSCRIBE": 

6755 return await self.ssubscribe(*args[1:]) 

6756 if command == "SUNSUBSCRIBE": 

6757 return await self.sunsubscribe(*args[1:]) 

6758 channel = args[1] 

6759 node = self.cluster.get_node_from_key(channel) 

6760 if node: 

6761 pubsub = self._get_node_pubsub(node) 

6762 async with self._pubsub_io_lock(pubsub): 

6763 return await pubsub.execute_command(*args, **kwargs) 

6764 

6765 # For other commands, use the set node or lazily discover one 

6766 if self.connection is None: 

6767 if self.connection_pool is None: 

6768 if len(args) > 1: 

6769 # Hash the first channel and get one of the nodes holding 

6770 # this slot 

6771 channel = args[1] 

6772 slot = self.cluster.keyslot(channel) 

6773 node = self.cluster.nodes_manager.get_node_from_slot( 

6774 slot, 

6775 self.cluster.read_from_replicas, 

6776 self.cluster.load_balancing_strategy, 

6777 ) 

6778 else: 

6779 # Get a random node 

6780 node = self.cluster.get_random_node() 

6781 self.node = node 

6782 self.connection_pool = _ClusterNodePoolAdapter(node) 

6783 

6784 # Now we have a connection_pool, use parent's execute_command 

6785 return await super().execute_command(*args, **kwargs)