1import asyncio
2import copy
3import inspect
4import logging
5import math
6import socket
7import sys
8import time
9import warnings
10import weakref
11from abc import ABC, abstractmethod
12from itertools import chain
13from types import MappingProxyType
14from typing import (
15 Any,
16 Awaitable,
17 Callable,
18 Iterable,
19 List,
20 Literal,
21 Mapping,
22 Optional,
23 Protocol,
24 Set,
25 Tuple,
26 Type,
27 TypedDict,
28 TypeVar,
29 Union,
30)
31from urllib.parse import ParseResult, parse_qs, unquote, urlparse
32
33from ..observability.attributes import (
34 DB_CLIENT_CONNECTION_POOL_NAME,
35 DB_CLIENT_CONNECTION_STATE,
36 AttributeBuilder,
37 ConnectionState,
38 get_pool_name,
39)
40from ..utils import SSL_AVAILABLE, deprecated_function
41
42if SSL_AVAILABLE:
43 import ssl
44 from ssl import SSLContext, TLSVersion, VerifyFlags
45else:
46 ssl = None
47 TLSVersion = None
48 SSLContext = None
49 VerifyFlags = None
50
51from ..auth.token import TokenInterface
52from ..driver_info import DriverInfo, resolve_driver_info
53from ..event import AsyncAfterConnectionReleasedEvent, EventDispatcher
54from ..utils import (
55 deprecated_args,
56 format_error_message,
57 is_os_level_timeout,
58 warn_deprecated,
59)
60
61# the functionality is available in 3.11.x but has a major issue before
62# 3.11.3. See https://github.com/redis/redis-py/issues/2633
63if sys.version_info >= (3, 11, 3):
64 from asyncio import timeout as async_timeout
65else:
66 from async_timeout import timeout as async_timeout
67
68from redis import exceptions as redis_exceptions
69from redis.asyncio.maint_notifications import (
70 AsyncMaintNotificationsConnectionHandler,
71 AsyncMaintNotificationsPoolHandler,
72 AsyncOSSMaintNotificationsHandler,
73)
74from redis.asyncio.observability.recorder import (
75 record_connection_closed,
76 record_connection_count,
77 record_connection_create_time,
78 record_connection_timeout,
79 record_connection_wait_time,
80 record_error_count,
81)
82from redis.asyncio.retry import Retry, _to_async_retry
83from redis.backoff import NoBackoff
84from redis.connection import HiredisRespSerializer
85from redis.credentials import CredentialProvider, UsernamePasswordCredentialProvider
86from redis.event import MaintenanceCompletedEvent
87from redis.exceptions import (
88 AuthenticationError,
89 AuthenticationWrongNumberOfArgsError,
90 ConnectionError,
91 DataError,
92 MaxConnectionsError,
93 RedisError,
94 ResponseError,
95 TimeoutError,
96)
97from redis.himport import HImportRegistry
98from redis.maint_notifications import (
99 PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT,
100 MaintenanceState,
101 MaintNotificationsConfig,
102 NodeMovingNotification,
103 _build_moving_cleanup_connection_kwargs,
104 _build_moving_connection_kwargs,
105 _dispatch_maintenance_event,
106)
107from redis.observability.metrics import CloseReason
108from redis.typing import EncodableT
109from redis.utils import (
110 DEFAULT_RESP_VERSION,
111 HIREDIS_AVAILABLE,
112 SENTINEL,
113 check_protocol_version,
114 get_shared_ssl_context,
115 str_if_bytes,
116)
117
118from .._defaults import (
119 DEFAULT_SOCKET_CONNECT_TIMEOUT,
120 DEFAULT_SOCKET_READ_SIZE,
121 DEFAULT_SOCKET_TIMEOUT,
122 get_default_socket_keepalive_options,
123)
124from .._parsers import (
125 UNRECOVERABLE_PARSE_ERRORS,
126 AsyncPushNotificationsParser,
127 BaseParser,
128 Encoder,
129 _AsyncHiredisParser,
130 _AsyncRESP2Parser,
131 _AsyncRESP3Parser,
132)
133
134# ``SYM_STAR`` and ``SYM_DOLLAR`` are deprecated: nothing in this library uses them any
135# more. They are bound to private names and served through the module ``__getattr__``
136# below, so that reading them warns. The annotations let linters and type checkers see the
137# names without binding them, which would bypass the warning.
138SYM_STAR: bytes
139SYM_DOLLAR: bytes
140_DEPRECATED_SYM_STAR = b"*"
141_DEPRECATED_SYM_DOLLAR = b"$"
142SYM_CRLF = b"\r\n"
143SYM_LF = b"\n"
144SYM_EMPTY = b""
145
146DefaultParser: Type[Union[_AsyncRESP2Parser, _AsyncRESP3Parser, _AsyncHiredisParser]]
147if HIREDIS_AVAILABLE:
148 DefaultParser = _AsyncHiredisParser
149else:
150 DefaultParser = _AsyncRESP3Parser
151
152logger = logging.getLogger(__name__)
153
154
155def add_debug_log_for_connection_failure(
156 connection: "AbstractConnection",
157 error: BaseException,
158 operation: str,
159) -> None:
160 """
161 Render the connection's live state on a failure that is about to close it.
162
163 Must be called *before* ``disconnect()``. ``extract_connection_details()``
164 reads the local port and the in-flight read deadline off the transport, so
165 once it is gone it can only report ``not connected`` - which hides exactly
166 the state needed to explain the failure. In particular it is what tells
167 apart a read that ran under the original timeout from one that ran under a
168 relaxed maintenance timeout.
169 """
170 if logger.isEnabledFor(logging.DEBUG):
171 logger.debug(
172 f"{type(error).__name__} while {operation}, "
173 f"with connection: {connection}, "
174 f"details: {connection.extract_connection_details()}, "
175 f"error: {error}",
176 )
177
178
179class ConnectCallbackProtocol(Protocol):
180 def __call__(self, connection: "AbstractConnection"): ...
181
182
183class AsyncConnectCallbackProtocol(Protocol):
184 async def __call__(self, connection: "AbstractConnection"): ...
185
186
187ConnectCallbackT = Union[ConnectCallbackProtocol, AsyncConnectCallbackProtocol]
188
189
190class AsyncMaintNotificationsAbstractConnection:
191 """
192 Internal mixin for async maintenance notification state and parser handlers.
193
194 The sync implementation uses the same mixin-style structure. The async
195 version keeps the notification state and parser handler installation close
196 to the connection without sending the server-side handshake; that is wired
197 in a later step.
198 """
199
200 __slots__ = ()
201
202 def __init__(
203 self,
204 maint_notifications_config: MaintNotificationsConfig | None,
205 maint_notifications_pool_handler: (
206 AsyncMaintNotificationsPoolHandler | None
207 ) = None,
208 maintenance_state: MaintenanceState = MaintenanceState.NONE,
209 maintenance_notification_hash: int | None = None,
210 orig_host_address: str | None = None,
211 orig_socket_timeout: float | None = None,
212 orig_socket_connect_timeout: float | None = None,
213 oss_cluster_maint_notifications_handler: (
214 AsyncOSSMaintNotificationsHandler | None
215 ) = None,
216 parser: BaseParser | None = None,
217 ) -> None:
218 self.maint_notifications_config = maint_notifications_config
219 self.maintenance_state = maintenance_state
220 self.maintenance_notification_hash = maintenance_notification_hash
221 self._processed_start_maint_notifications: set[int] = set()
222 self._skipped_end_maint_notifications: set[int] = set()
223 self._configure_maintenance_notifications(
224 maint_notifications_pool_handler,
225 orig_host_address,
226 orig_socket_timeout,
227 orig_socket_connect_timeout,
228 oss_cluster_maint_notifications_handler,
229 parser,
230 )
231
232 @abstractmethod
233 def _get_parser(self) -> BaseParser:
234 pass
235
236 def _get_push_notifications_parser(self) -> AsyncPushNotificationsParser:
237 parser = self._get_parser()
238 if not isinstance(parser, (_AsyncHiredisParser, _AsyncRESP3Parser)):
239 raise RedisError(
240 "Maintenance notifications are only supported with hiredis and RESP3 parsers!"
241 )
242 return parser
243
244 def _complete_maintenance_on_disconnect(self) -> None:
245 """
246 Restore the settings a maintenance relaxed on this connection when it is
247 closed, and report the relaxation as completed - the same way the
248 completion notification would have been reported. The MOVING state is
249 left alone: it is owned by the pool-level TTL cleanup.
250 """
251 if self.maintenance_state != MaintenanceState.MAINTENANCE:
252 return
253 self.reset_tmp_settings(reset_relaxed_timeout=True)
254 self.maintenance_state = MaintenanceState.NONE
255 # reset the sets that keep track of received start maint
256 # notifications and skipped end maint notifications
257 self.reset_received_notifications()
258 if self.maint_notifications_config is not None:
259 pool_handler = self._maint_notifications_pool_handler
260 _dispatch_maintenance_event(
261 self.maint_notifications_config,
262 MaintenanceCompletedEvent(
263 connection_pool=(
264 pool_handler.pool if pool_handler is not None else None
265 ),
266 connection=self,
267 state=MaintenanceState.MAINTENANCE,
268 notification=None,
269 config=self.maint_notifications_config,
270 ),
271 )
272
273 async def handle_pending_push_notifications(self) -> None:
274 """
275 Process the push notifications buffered on this idle connection if it
276 is still alive, and report a connection that has to be reconnected.
277
278 A pooled connection that has readable data while idle either has push
279 notifications waiting, or has been closed by the server - or both, when
280 the notifications announced the maintenance that closed it. The socket
281 state cannot be told apart from the pending data without reading it, so
282 the notifications are collected first and handed to their handlers only
283 once the drain has shown the socket to be alive: the server closes the
284 connections of a moved endpoint when the MOVING time-to-live expires,
285 so an alive socket means the maintenance is still in progress and the
286 announced address current. A notification buffered on a socket the
287 server has since closed describes a maintenance that is over, after
288 which the configured address is what to connect to again: it is
289 discarded, and the ``ConnectionError`` raised here makes the pool
290 reconnect before any command is sent.
291
292 Anything read that is not a maintenance notification or a client-side
293 cache invalidation - a reply, a null or an error reply left unread by an
294 earlier command - means the connection is dirty and is reported the same
295 way, as is a drain that does not complete within
296 ``PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT``.
297 """
298 if self._resp2_fallback:
299 raise ConnectionError("Connection has data")
300 parser = self._get_push_notifications_parser()
301 deferred: list = []
302
303 def defer(handler):
304 async def deferred_handler(notification):
305 deferred.append((handler, notification))
306
307 return deferred_handler
308
309 handlers = (
310 (parser.node_moving_push_handler_func, parser.set_node_moving_push_handler),
311 (parser.maintenance_push_handler_func, parser.set_maintenance_push_handler),
312 (
313 parser.oss_cluster_maint_push_handler_func,
314 parser.set_oss_cluster_maint_push_handler,
315 ),
316 # Client-side cache invalidations are pushes too; the ones on a
317 # connection that has to be reconnected are covered by the cache
318 # flush its disconnect performs
319 (
320 parser.invalidation_push_handler_func,
321 parser.set_invalidation_push_handler,
322 ),
323 )
324 for handler, set_handler in handlers:
325 if handler is not None:
326 set_handler(defer(handler))
327
328 alive = False
329 deadline = time.monotonic() + PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT
330 try:
331 while await self.can_read():
332 remaining = deadline - time.monotonic()
333 if remaining <= 0:
334 raise ConnectionError(
335 "Timed out reading pending push notifications"
336 )
337 read = len(deferred)
338 # The pool disconnects the connection it handed out on the error
339 try:
340 await asyncio.wait_for(
341 self.read_response(
342 push_request=True, disconnect_on_error=False
343 ),
344 remaining,
345 )
346 except asyncio.TimeoutError:
347 raise ConnectionError(
348 "Timed out reading pending push notifications"
349 ) from None
350 # Only a push reaches a deferred handler; anything else is a
351 # reply left unread by an earlier command
352 if len(deferred) == read:
353 raise ConnectionError("Connection has data")
354 alive = True
355 except ResponseError as e:
356 raise ConnectionError("Connection has data") from e
357 finally:
358 for handler, set_handler in handlers:
359 set_handler(handler)
360 if not alive and deferred and logger.isEnabledFor(logging.DEBUG):
361 logger.debug(
362 f"Discarding {len(deferred)} push notification(s) buffered on "
363 f"a connection that is closed or dirty, reconnecting: {self}"
364 )
365
366 for handler, notification in deferred:
367 try:
368 await handler(notification)
369 except Exception as e:
370 logger.error(f"Error handling {notification}: {e}")
371
372 @abstractmethod
373 def get_protocol(self):
374 pass
375
376 @abstractmethod
377 async def send_command(self, *args: Any, **kwargs: Any) -> None:
378 pass
379
380 @abstractmethod
381 async def read_response(
382 self,
383 disable_decoding: bool = False,
384 timeout: float | None = None,
385 *,
386 disconnect_on_error: bool = True,
387 push_request: bool | None = False,
388 ) -> Any:
389 pass
390
391 @abstractmethod
392 def getpeername(self) -> str | None:
393 pass
394
395 @abstractmethod
396 def extract_connection_details(self) -> str:
397 pass
398
399 def _configure_maintenance_notifications(
400 self,
401 maint_notifications_pool_handler: (
402 AsyncMaintNotificationsPoolHandler | None
403 ) = None,
404 orig_host_address: str | None = None,
405 orig_socket_timeout: float | None = None,
406 orig_socket_connect_timeout: float | None = None,
407 oss_cluster_maint_notifications_handler: (
408 AsyncOSSMaintNotificationsHandler | None
409 ) = None,
410 parser: BaseParser | None = None,
411 ) -> None:
412 if (
413 not self.maint_notifications_config
414 or not self.maint_notifications_config.enabled
415 ):
416 self._maint_notifications_pool_handler = None
417 self._maint_notifications_connection_handler = None
418 self._oss_cluster_maint_notifications_handler = None
419 return
420
421 if not parser:
422 raise RedisError(
423 "To configure maintenance notifications, a parser must be provided!"
424 )
425
426 if not isinstance(parser, _AsyncHiredisParser) and not isinstance(
427 parser, _AsyncRESP3Parser
428 ):
429 raise RedisError(
430 "Maintenance notifications are only supported with hiredis and RESP3 parsers!"
431 )
432
433 if maint_notifications_pool_handler:
434 # Extract a reference to a new pool handler that copies all properties
435 # of the original one and has a different connection reference
436 # This is needed because when we attach the handler to the parser
437 # we need to make sure that the handler has a reference to the
438 # connection that the parser is attached to.
439 self._maint_notifications_pool_handler = (
440 maint_notifications_pool_handler.get_handler_for_connection()
441 )
442 self._maint_notifications_pool_handler.set_connection(self)
443 else:
444 self._maint_notifications_pool_handler = None
445
446 self._maint_notifications_connection_handler = (
447 AsyncMaintNotificationsConnectionHandler(
448 self, self.maint_notifications_config
449 )
450 )
451
452 if oss_cluster_maint_notifications_handler:
453 self._oss_cluster_maint_notifications_handler = (
454 oss_cluster_maint_notifications_handler
455 )
456 parser.set_oss_cluster_maint_push_handler(
457 oss_cluster_maint_notifications_handler.handle_notification
458 )
459 else:
460 self._oss_cluster_maint_notifications_handler = None
461
462 # Set up pool handler to parser if available
463 if self._maint_notifications_pool_handler:
464 parser.set_node_moving_push_handler(
465 self._maint_notifications_pool_handler.handle_notification
466 )
467
468 # Set up connection handler
469 parser.set_maintenance_push_handler(
470 self._maint_notifications_connection_handler.handle_notification
471 )
472
473 self.orig_host_address = orig_host_address if orig_host_address else self.host
474 self.orig_socket_timeout = (
475 orig_socket_timeout if orig_socket_timeout else self.socket_timeout
476 )
477 self.orig_socket_connect_timeout = (
478 orig_socket_connect_timeout
479 if orig_socket_connect_timeout
480 else self.socket_connect_timeout
481 )
482
483 def set_maint_notifications_pool_handler_for_connection(
484 self, maint_notifications_pool_handler: AsyncMaintNotificationsPoolHandler
485 ) -> None:
486 if self._resp2_fallback:
487 return
488 # Deep copy the pool handler to avoid sharing the same pool handler
489 # between multiple connections, because otherwise each connection will override
490 # the connection reference and the pool handler will only hold a reference
491 # to the last connection that was set.
492 maint_notifications_pool_handler_copy = (
493 maint_notifications_pool_handler.get_handler_for_connection()
494 )
495 maint_notifications_pool_handler_copy.set_connection(self)
496 parser = self._get_push_notifications_parser()
497 parser.set_node_moving_push_handler(
498 maint_notifications_pool_handler_copy.handle_notification
499 )
500 self._maint_notifications_pool_handler = maint_notifications_pool_handler_copy
501
502 # Update maintenance notification connection handler if it doesn't exist
503 if not self._maint_notifications_connection_handler:
504 self._maint_notifications_connection_handler = (
505 AsyncMaintNotificationsConnectionHandler(
506 self, maint_notifications_pool_handler.config
507 )
508 )
509 parser.set_maintenance_push_handler(
510 self._maint_notifications_connection_handler.handle_notification
511 )
512 else:
513 self._maint_notifications_connection_handler.config = (
514 maint_notifications_pool_handler.config
515 )
516
517 def set_maint_notifications_cluster_handler_for_connection(
518 self,
519 oss_cluster_maint_notifications_handler: AsyncOSSMaintNotificationsHandler,
520 ) -> None:
521 if self._resp2_fallback:
522 return
523 parser = self._get_push_notifications_parser()
524 parser.set_oss_cluster_maint_push_handler(
525 oss_cluster_maint_notifications_handler.handle_notification
526 )
527 # OSS cluster mode and pool-handler mode are mutually exclusive. Clear
528 # any node-moving/pool handler a default (RESP3 "auto") pool wired in
529 # __init__ so this existing connection is not configured with both.
530 parser.set_node_moving_push_handler(None)
531 self._maint_notifications_pool_handler = None
532
533 self._oss_cluster_maint_notifications_handler = (
534 oss_cluster_maint_notifications_handler
535 )
536
537 # Update maintenance notification connection handler if it doesn't exist
538 if not self._maint_notifications_connection_handler:
539 self._maint_notifications_connection_handler = (
540 AsyncMaintNotificationsConnectionHandler(
541 self, oss_cluster_maint_notifications_handler.config
542 )
543 )
544 parser.set_maintenance_push_handler(
545 self._maint_notifications_connection_handler.handle_notification
546 )
547 else:
548 self._maint_notifications_connection_handler.config = (
549 oss_cluster_maint_notifications_handler.config
550 )
551
552 async def activate_maint_notifications_handling_if_enabled(
553 self, check_health: bool = True
554 ) -> None:
555 # Send maintenance notifications handshake if RESP3 is active
556 # and maintenance notifications are enabled
557 # and we have a host to determine the endpoint type from
558 # When the maint_notifications_config enabled mode is "auto",
559 # we just log a warning if the handshake fails
560 # When the mode is enabled=True, we raise an exception in case of failure
561 host = getattr(self, "host", None)
562 if (
563 check_protocol_version(self.get_protocol(), 3)
564 and self.maint_notifications_config
565 and self.maint_notifications_config.enabled
566 and self._maint_notifications_connection_handler
567 and host is not None
568 ):
569 await self._enable_maintenance_notifications(
570 maint_notifications_config=self.maint_notifications_config,
571 check_health=check_health,
572 )
573
574 async def _enable_maintenance_notifications(
575 self,
576 maint_notifications_config: MaintNotificationsConfig,
577 check_health: bool = True,
578 ) -> None:
579 try:
580 host = getattr(self, "host", None)
581 if host is None:
582 raise ValueError(
583 "Cannot enable maintenance notifications for connection"
584 " object that doesn't have a host attribute."
585 )
586
587 endpoint_type = maint_notifications_config.get_endpoint_type(host, self)
588 await self.send_command(
589 "CLIENT",
590 "MAINT_NOTIFICATIONS",
591 "ON",
592 "moving-endpoint-type",
593 endpoint_type.value,
594 check_health=check_health,
595 )
596 response = await self.read_response()
597 if not response or str_if_bytes(response) != "OK":
598 raise ResponseError(
599 "The server doesn't support maintenance notifications"
600 )
601 except Exception as e:
602 if (
603 isinstance(e, ResponseError)
604 and maint_notifications_config.enabled == "auto"
605 ):
606 # Log warning but don't fail the connection
607 logger.debug(f"Failed to enable maintenance notifications: {e}")
608 else:
609 raise
610
611 def get_resolved_ip(self) -> str | None:
612 """
613 Extract the resolved IP address from an established connection or host.
614
615 First tries to get the actual peer IP from the async stream writer, then
616 falls back to DNS resolution if needed.
617
618 Returns:
619 The resolved IP address, or None if it cannot be determined.
620 """
621
622 # Method 1: Try to get the actual IP from the established stream.
623 # This is most accurate as it shows the exact IP being used.
624 try:
625 peer_addr = self.getpeername()
626 if peer_addr:
627 return peer_addr
628 except (AttributeError, OSError):
629 # Stream might not be connected or peer address lookup might fail.
630 pass
631
632 # Method 2: Fall back to the configured host (which may be an IP or an
633 # FQDN). Unlike the sync client we intentionally do NOT call
634 # socket.getaddrinfo() here: this method runs on the event loop, so a
635 # blocking DNS resolution would stall it. On the endpoint-type handshake
636 # path (get_endpoint_type) getpeername() above always succeeds because the
637 # writer was just connected, so this fallback is only reached by the
638 # debug-log call sites during reconnects — where returning the host is
639 # fine. A blocking getaddrinfo on an FQDN host there can freeze the loop
640 # for seconds and trip unrelated connect timeouts.
641 return getattr(self, "host", None)
642
643 @property
644 def maintenance_state(self) -> MaintenanceState:
645 return self._maintenance_state
646
647 @maintenance_state.setter
648 def maintenance_state(self, state: MaintenanceState) -> None:
649 self._maintenance_state = state
650
651 def add_maint_start_notification(self, id: int) -> None:
652 self._processed_start_maint_notifications.add(id)
653
654 def get_processed_start_notifications(self) -> set[int]:
655 return self._processed_start_maint_notifications
656
657 def add_skipped_end_notification(self, id: int) -> None:
658 self._skipped_end_maint_notifications.add(id)
659
660 def get_skipped_end_notifications(self) -> set[int]:
661 return self._skipped_end_maint_notifications
662
663 def reset_received_notifications(self) -> None:
664 self._processed_start_maint_notifications.clear()
665 self._skipped_end_maint_notifications.clear()
666
667 def update_current_socket_timeout(
668 self, relaxed_timeout: float | None = None
669 ) -> None:
670 timeout = relaxed_timeout if relaxed_timeout != -1 else self.socket_timeout
671 self._reschedule_active_read_timeout(timeout)
672
673 def _reschedule_active_read_timeout(self, timeout: float | None) -> None:
674 timeout_context = getattr(self, "_active_read_timeout", None)
675 if timeout_context is None:
676 # No read_response call is currently inside its socket timeout
677 # context, so there is no in-flight deadline to relax or restore.
678 return
679
680 if timeout is None:
681 # A None socket timeout means the active read should become blocking.
682 # Python 3.11's timeout context supports clearing the deadline.
683 if hasattr(timeout_context, "reschedule"):
684 timeout_context.reschedule(None)
685 # Older async-timeout contexts cannot clear a deadline, so reject the
686 # current timeout instead of leaving a stale relaxed deadline active.
687 elif hasattr(timeout_context, "reject"):
688 timeout_context.reject()
689 return
690
691 # Active read timeouts are stored as loop-time deadlines, not durations.
692 deadline = asyncio.get_running_loop().time() + timeout
693 if hasattr(timeout_context, "reschedule"):
694 # Python 3.11 asyncio.timeout exposes reschedule().
695 timeout_context.reschedule(deadline)
696 elif hasattr(timeout_context, "update"):
697 # async-timeout exposes update() for the same deadline adjustment.
698 timeout_context.update(deadline)
699
700 def set_tmp_settings(
701 self,
702 tmp_host_address: str | object | None = SENTINEL,
703 tmp_relaxed_timeout: float | None = -1,
704 ) -> None:
705 """
706 SENTINEL keeps the host unchanged. -1 keeps the relaxed timeout unchanged.
707 """
708 if tmp_host_address and tmp_host_address != SENTINEL:
709 self.host = str(tmp_host_address)
710 if tmp_relaxed_timeout != -1:
711 self.socket_timeout = tmp_relaxed_timeout
712 self.socket_connect_timeout = tmp_relaxed_timeout
713
714 def reset_tmp_settings(
715 self,
716 reset_host_address: bool = False,
717 reset_relaxed_timeout: bool = False,
718 ) -> None:
719 if reset_host_address:
720 self.host = self.orig_host_address
721 if reset_relaxed_timeout:
722 self.socket_timeout = self.orig_socket_timeout
723 self.socket_connect_timeout = self.orig_socket_connect_timeout
724
725
726class AbstractConnection(AsyncMaintNotificationsAbstractConnection):
727 """Manages communication to and from a Redis server"""
728
729 __slots__ = (
730 "db",
731 "username",
732 "client_name",
733 "lib_name",
734 "lib_version",
735 "credential_provider",
736 "password",
737 "socket_timeout",
738 "socket_connect_timeout",
739 "redis_connect_func",
740 "retry_on_timeout",
741 "retry_on_error",
742 "health_check_interval",
743 "next_health_check",
744 "last_active_at",
745 "encoder",
746 "ssl_context",
747 "protocol",
748 "_reader",
749 "_writer",
750 "_parser",
751 "_active_read_timeout",
752 "_connect_callbacks",
753 "_buffer_cutoff",
754 "_lock",
755 "_socket_read_size",
756 "__dict__",
757 )
758
759 @deprecated_args(
760 args_to_warn=["lib_name", "lib_version"],
761 reason="Use 'driver_info' parameter instead. "
762 "lib_name and lib_version will be removed in a future version.",
763 )
764 def __init__(
765 self,
766 *,
767 db: str | int = 0,
768 password: str | None = None,
769 socket_timeout: float | None = DEFAULT_SOCKET_TIMEOUT,
770 socket_connect_timeout: float | None = DEFAULT_SOCKET_CONNECT_TIMEOUT,
771 retry_on_timeout: bool = False,
772 retry_on_error: Iterable[Type[Exception]] | object = SENTINEL,
773 encoding: str = "utf-8",
774 encoding_errors: str = "strict",
775 decode_responses: bool = False,
776 parser_class: Type[BaseParser] = DefaultParser,
777 socket_read_size: int = DEFAULT_SOCKET_READ_SIZE,
778 health_check_interval: float = 0,
779 client_name: str | None = None,
780 lib_name: str | object | None = SENTINEL,
781 lib_version: str | object | None = SENTINEL,
782 driver_info: DriverInfo | object | None = SENTINEL,
783 username: str | None = None,
784 retry: Retry | None = None,
785 redis_connect_func: ConnectCallbackT | None = None,
786 encoder_class: Type[Encoder] = Encoder,
787 credential_provider: CredentialProvider | None = None,
788 protocol: int | None = None,
789 legacy_responses: bool = True,
790 event_dispatcher: EventDispatcher | None = None,
791 maint_notifications_config: MaintNotificationsConfig | None = None,
792 maint_notifications_pool_handler: (
793 AsyncMaintNotificationsPoolHandler | None
794 ) = None,
795 maintenance_state: MaintenanceState = MaintenanceState.NONE,
796 maintenance_notification_hash: int | None = None,
797 orig_host_address: str | None = None,
798 orig_socket_timeout: float | None = None,
799 orig_socket_connect_timeout: float | None = None,
800 oss_cluster_maint_notifications_handler: (
801 AsyncOSSMaintNotificationsHandler | None
802 ) = None,
803 himport_registry: HImportRegistry | None = None,
804 ):
805 """
806 Initialize a new async Connection.
807
808 Parameters
809 ----------
810 driver_info : DriverInfo, optional
811 Driver metadata for CLIENT SETINFO. If provided, lib_name and lib_version
812 are ignored. If not provided, a DriverInfo will be created from lib_name
813 and lib_version. Explicit None disables CLIENT SETINFO.
814 lib_name : str, optional
815 **Deprecated.** Use driver_info instead. Library name for CLIENT SETINFO.
816 lib_version : str, optional
817 **Deprecated.** Use driver_info instead. Library version for CLIENT SETINFO.
818 """
819 if (username or password) and credential_provider is not None:
820 raise DataError(
821 "'username' and 'password' cannot be passed along with 'credential_"
822 "provider'. Please provide only one of the following arguments: \n"
823 "1. 'password' and (optional) 'username'\n"
824 "2. 'credential_provider'"
825 )
826 if event_dispatcher is None:
827 self._event_dispatcher = EventDispatcher()
828 else:
829 self._event_dispatcher = event_dispatcher
830 self.db = db
831 self.client_name = client_name
832
833 # Handle driver_info: if provided, use it; otherwise create from lib_name/lib_version.
834 self.driver_info = resolve_driver_info(driver_info, lib_name, lib_version)
835
836 self.credential_provider = credential_provider
837 self.password = password
838 self.username = username
839 self.socket_timeout = socket_timeout
840 if socket_connect_timeout is None:
841 socket_connect_timeout = socket_timeout
842 self.socket_connect_timeout = socket_connect_timeout
843 self.retry_on_timeout = retry_on_timeout
844 if retry_on_error is SENTINEL:
845 retry_on_error = []
846 else:
847 # Copy so we never mutate the caller-supplied list (parity with sync).
848 retry_on_error = list(retry_on_error)
849 if retry_on_timeout:
850 retry_on_error.append(TimeoutError)
851 retry_on_error.append(socket.timeout)
852 retry_on_error.append(asyncio.TimeoutError)
853 self.retry_on_error = retry_on_error
854 if retry or retry_on_error:
855 if not retry:
856 self.retry = Retry(NoBackoff(), 1)
857 else:
858 # deep-copy the Retry object as it is mutable
859 self.retry = copy.deepcopy(_to_async_retry(retry))
860 # Update the retry's supported errors with the specified errors
861 self.retry.update_supported_errors(retry_on_error)
862 else:
863 self.retry = Retry(NoBackoff(), 0)
864 self.health_check_interval = health_check_interval
865 self.next_health_check: float = -1
866 self.encoder = encoder_class(encoding, encoding_errors, decode_responses)
867 self.redis_connect_func = redis_connect_func
868 self._reader: Optional[asyncio.StreamReader] = None
869 self._writer: Optional[asyncio.StreamWriter] = None
870 self._socket_read_size = socket_read_size
871 self._active_read_timeout = None
872 self._connect_callbacks: List[weakref.WeakMethod[ConnectCallbackT]] = []
873 self._buffer_cutoff = 6000
874 self._re_auth_token: Optional[TokenInterface] = None
875 self._command_packer = (
876 HiredisRespSerializer(self._pack_command_python, self.encoder.encode)
877 if HIREDIS_AVAILABLE
878 else None
879 )
880 self._should_reconnect = False
881
882 try:
883 p = int(protocol)
884 self._protocol_specified_explicitly = True
885 except TypeError:
886 p = DEFAULT_RESP_VERSION
887 self._protocol_specified_explicitly = False
888 except ValueError:
889 raise ConnectionError("protocol must be an integer")
890 else:
891 if p < 2 or p > 3:
892 raise ConnectionError("protocol must be either 2 or 3")
893 self.protocol = p
894 self.handshake_metadata = None
895 self._resp2_fallback = False
896 self.legacy_responses = legacy_responses
897 if parser_class != _AsyncHiredisParser:
898 # The Python parsers are protocol-specific; hiredis supports both.
899 if self.protocol == 3 and parser_class == _AsyncRESP2Parser:
900 parser_class = _AsyncRESP3Parser
901 elif self.protocol == 2 and parser_class == _AsyncRESP3Parser:
902 parser_class = _AsyncRESP2Parser
903 self.set_parser(parser_class)
904
905 # HIMPORT client-side state. `himport_registry` is the shared client-level
906 # registry (empty if unconfigured) and persists across reconnects.
907 self.himport_registry = himport_registry
908 self._reset_himport_state()
909
910 AsyncMaintNotificationsAbstractConnection.__init__(
911 self,
912 maint_notifications_config,
913 maint_notifications_pool_handler,
914 maintenance_state,
915 maintenance_notification_hash,
916 orig_host_address,
917 orig_socket_timeout,
918 orig_socket_connect_timeout,
919 oss_cluster_maint_notifications_handler,
920 self._parser,
921 )
922
923 def __del__(self, _warnings: Any = warnings):
924 # For some reason, the individual streams don't get properly garbage
925 # collected and therefore produce no resource warnings. We add one
926 # here, in the same style as those from the stdlib.
927 if getattr(self, "_writer", None):
928 _warnings.warn(
929 f"unclosed Connection {self!r}", ResourceWarning, source=self
930 )
931
932 try:
933 asyncio.get_running_loop()
934 self._close()
935 except RuntimeError:
936 # No actions been taken if pool already closed.
937 pass
938
939 def _close(self):
940 """
941 Internal method to silently close the connection without waiting
942 """
943 if self._writer:
944 self._writer.close()
945 self._writer = self._reader = None
946
947 def _force_disconnect(self) -> None:
948 """Disconnect synchronously, without waiting for the close to finish."""
949 # Same session cleanup as disconnect() does first; both are idempotent.
950 self._reset_himport_state()
951 self._complete_maintenance_on_disconnect()
952 self._parser.on_disconnect()
953 self.reset_should_reconnect()
954 self._close()
955
956 def __repr__(self):
957 repr_args = ",".join((f"{k}={v}" for k, v in self.repr_pieces()))
958 return f"<{self.__class__.__module__}.{self.__class__.__name__}({repr_args})>"
959
960 @abstractmethod
961 def repr_pieces(self):
962 pass
963
964 @property
965 def is_connected(self):
966 return self._reader is not None and self._writer is not None
967
968 def register_connect_callback(self, callback):
969 """
970 Register a callback to be called when the connection is established either
971 initially or reconnected. This allows listeners to issue commands that
972 are ephemeral to the connection, for example pub/sub subscription or
973 key tracking. The callback must be a _method_ and will be kept as
974 a weak reference.
975 """
976 wm = weakref.WeakMethod(callback)
977 if wm not in self._connect_callbacks:
978 self._connect_callbacks.append(wm)
979
980 def deregister_connect_callback(self, callback):
981 """
982 De-register a previously registered callback. It will no-longer receive
983 notifications on connection events. Calling this is not required when the
984 listener goes away, since the callbacks are kept as weak methods.
985 """
986 try:
987 self._connect_callbacks.remove(weakref.WeakMethod(callback))
988 except ValueError:
989 pass
990
991 def set_parser(self, parser_class: Type[BaseParser]) -> None:
992 """
993 Creates a new instance of parser_class with socket size:
994 _socket_read_size and assigns it to the parser for the connection
995 :param parser_class: The required parser class
996 """
997 self._parser = parser_class(socket_read_size=self._socket_read_size)
998
999 def _get_parser(self) -> BaseParser:
1000 return self._parser
1001
1002 def getpeername(self) -> str | None:
1003 """
1004 Returns the peer name of the connection.
1005 """
1006 writer = self._writer
1007 if writer is None:
1008 return None
1009 peername = writer.get_extra_info("peername")
1010 if isinstance(peername, tuple) and peername:
1011 return str(peername[0])
1012 return None
1013
1014 def extract_connection_details(self) -> str:
1015 """
1016 Render the connection's identity, maintenance state and effective timeouts.
1017
1018 This is what the debug logs use to explain a failed or timed out command:
1019
1020 - ``host`` vs ``orig host`` says whether the connection still points at the
1021 node being moved away from, or has already been repointed at the new one.
1022 - ``state`` says whether maintenance handling touched this connection at
1023 all, so an unaffected node's connections are distinguishable.
1024 - ``socket_timeout`` vs ``active read timeout`` says which timeout the read
1025 actually ran under. ``active read timeout`` is the remaining deadline of
1026 the in-flight ``read_response`` (``None`` when no read is in flight), so
1027 the two diverge for a command that was already reading when the relaxed
1028 timeout was applied.
1029 """
1030 writer = self._writer
1031 if writer is None:
1032 return "not connected"
1033
1034 socket_address = None
1035 try:
1036 socket_name = writer.get_extra_info("sockname")
1037 # AF_UNIX sockets report a path string rather than a (host, port) tuple
1038 if isinstance(socket_name, tuple) and len(socket_name) > 1:
1039 socket_address = socket_name[1]
1040 except (AttributeError, OSError):
1041 pass
1042
1043 # Unlike the sync client there is no timeout armed on the socket; the
1044 # deadline lives in the timeout context wrapping the in-flight read.
1045 active_read_timeout = None
1046 timeout_context = self._active_read_timeout
1047 if timeout_context is not None:
1048 try:
1049 when = timeout_context.when()
1050 if when is not None:
1051 active_read_timeout = round(
1052 when - asyncio.get_running_loop().time(), 3
1053 )
1054 except (AttributeError, RuntimeError):
1055 pass
1056
1057 state = getattr(self.maintenance_state, "value", self.maintenance_state)
1058 return (
1059 f"connected to ip {self.get_resolved_ip()}, "
1060 f"local socket port: {socket_address}, "
1061 f"host: {self._host_error()} "
1062 f"(orig: {getattr(self, 'orig_host_address', None)}), "
1063 f"state: {state}, "
1064 f"socket_timeout: {self.socket_timeout} "
1065 f"(orig: {getattr(self, 'orig_socket_timeout', None)}), "
1066 f"active read timeout: {active_read_timeout}, "
1067 f"should_reconnect: {self.should_reconnect()}, "
1068 f"notification_hash: {self.maintenance_notification_hash}"
1069 )
1070
1071 async def connect(self):
1072 """Connects to the Redis server if not already connected"""
1073 # try once the socket connect with the handshake, retry the whole
1074 # connect/handshake flow based on retry policy
1075 await self.retry.call_with_retry(
1076 lambda: self.connect_check_health(
1077 check_health=True, retry_socket_connect=False
1078 ),
1079 lambda error, failure_count: self.disconnect(
1080 error=error, failure_count=failure_count
1081 ),
1082 with_failure_count=True,
1083 )
1084
1085 async def connect_check_health(
1086 self, check_health: bool = True, retry_socket_connect: bool = True
1087 ):
1088 if self.is_connected:
1089 return
1090 # Track actual retry attempts for error reporting
1091 actual_retry_attempts = 0
1092
1093 def failure_callback(error, failure_count):
1094 nonlocal actual_retry_attempts
1095 actual_retry_attempts = failure_count
1096 return self.disconnect(error=error, failure_count=failure_count)
1097
1098 try:
1099 if retry_socket_connect:
1100 await self.retry.call_with_retry(
1101 lambda: self._connect(),
1102 failure_callback,
1103 with_failure_count=True,
1104 )
1105 else:
1106 await self._connect()
1107 except asyncio.CancelledError:
1108 raise # in 3.7 and earlier, this is an Exception, not BaseException
1109 except (socket.timeout, asyncio.TimeoutError):
1110 e = TimeoutError("Timeout connecting to server")
1111 await record_error_count(
1112 server_address=getattr(self, "host", None),
1113 server_port=getattr(self, "port", None),
1114 network_peer_address=getattr(self, "host", None),
1115 network_peer_port=getattr(self, "port", None),
1116 error_type=e,
1117 retry_attempts=actual_retry_attempts,
1118 is_internal=False,
1119 )
1120 raise e
1121 except OSError as e:
1122 conn_error = ConnectionError(self._error_message(e))
1123 await record_error_count(
1124 server_address=getattr(self, "host", None),
1125 server_port=getattr(self, "port", None),
1126 network_peer_address=getattr(self, "host", None),
1127 network_peer_port=getattr(self, "port", None),
1128 error_type=conn_error,
1129 retry_attempts=actual_retry_attempts,
1130 is_internal=False,
1131 )
1132 # Preserve the original OSError (with its errno) as the cause so
1133 # the retry policy can tell unrecoverable failures apart. Clear the
1134 # local afterwards so its traceback does not form a reference cycle
1135 # with this frame.
1136 try:
1137 raise conn_error from e
1138 finally:
1139 conn_error = None
1140 except Exception as exc:
1141 raise ConnectionError(exc) from exc
1142
1143 # A new socket authenticates in the handshake below with current
1144 # credentials, which replaces any AUTH deferred on the old one
1145 self._re_auth_token = None
1146 try:
1147 if not self.redis_connect_func:
1148 # Use the default on_connect function
1149 await self.on_connect_check_health(check_health=check_health)
1150 else:
1151 # Use the passed function redis_connect_func
1152 (
1153 await self.redis_connect_func(self)
1154 if asyncio.iscoroutinefunction(self.redis_connect_func)
1155 else self.redis_connect_func(self)
1156 )
1157 except RedisError:
1158 # Clean up after any error in on_connect. The socket is discarded,
1159 # so the close is not waited for: a close that times out must not
1160 # replace the error, for example a rejected AUTH with a retryable
1161 # TimeoutError.
1162 await self.disconnect(nowait=True)
1163 raise
1164 except BaseException:
1165 # Likewise for whatever a credential provider raises and for a
1166 # cancelled task. A socket left in place reads as connected, so the
1167 # next command would run without AUTH and SELECT.
1168 await self.disconnect(nowait=True)
1169 raise
1170
1171 # run any user callbacks. right now the only internal callback
1172 # is for pubsub channel/pattern resubscription
1173 # first, remove any dead weakrefs
1174 self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()]
1175 for ref in self._connect_callbacks:
1176 callback = ref()
1177 task = callback(self)
1178 if task and inspect.isawaitable(task):
1179 await task
1180
1181 def mark_for_reconnect(self):
1182 self._should_reconnect = True
1183
1184 def should_reconnect(self):
1185 return self._should_reconnect
1186
1187 def reset_should_reconnect(self):
1188 self._should_reconnect = False
1189
1190 @abstractmethod
1191 async def _connect(self):
1192 pass
1193
1194 @abstractmethod
1195 def _host_error(self) -> str:
1196 pass
1197
1198 def _error_message(self, exception: BaseException) -> str:
1199 return format_error_message(self._host_error(), exception)
1200
1201 def get_protocol(self):
1202 return self.protocol
1203
1204 def _reset_himport_state(self) -> None:
1205 # A fresh server session has no prepared HIMPORT fieldsets, so the next
1206 # himport_set must re-prepare on this connection. ``_himport_prepared`` maps
1207 # fieldset name -> the version prepared on the server; ``_himport_reconciled
1208 # _revision`` is the registry revision this connection last reconciled discards
1209 # against. Both are reset on connect/disconnect since the session is gone.
1210 self._himport_prepared: dict[str, int] = {}
1211 self._himport_reconciled_revision: int = 0
1212
1213 async def on_connect(self) -> None:
1214 """Initialize the connection, authenticate and select a database"""
1215 await self.on_connect_check_health(check_health=True)
1216
1217 async def _do_resp2_auth(self, auth_args) -> None:
1218 """Authenticate with the original credentials, retrying pre-6.0 AUTH."""
1219 # avoid checking health here -- PING will fail if we try
1220 # to check the health prior to the AUTH
1221 await self.send_command("AUTH", *auth_args, check_health=False)
1222 try:
1223 auth_response = await self.read_response()
1224 except AuthenticationWrongNumberOfArgsError:
1225 # a username and password were specified but the Redis
1226 # server seems to be < 6.0.0 which expects a single password
1227 # arg. retry auth with just the password.
1228 await self.send_command("AUTH", auth_args[-1], check_health=False)
1229 auth_response = await self.read_response()
1230
1231 if str_if_bytes(auth_response) != "OK":
1232 raise AuthenticationError("Invalid Username or Password")
1233
1234 async def _fallback_to_resp2(
1235 self, error: ResponseError, parser, auth_args=None
1236 ) -> None:
1237 """Handle HELLO failure by falling back to RESP2.
1238
1239 Validates the error is a recoverable "unknown command" or "NOPROTO",
1240 checks that fallback is allowed (not explicitly configured, no
1241 RESP3-dependent features active), downgrades parser and protocol,
1242 emits a warning, and optionally re-authenticates via standalone AUTH.
1243
1244 Args:
1245 error: The ResponseError from the failed HELLO command.
1246 parser: The original parser (for preserving EXCEPTION_CLASSES).
1247 auth_args: Original credentials to authenticate after downgrade.
1248
1249 Raises:
1250 ResponseError: If the error is not recoverable or fallback
1251 is not permitted.
1252 """
1253 err_msg = str(error).lower().removeprefix("err ")
1254 if not (
1255 err_msg in ("unknown command", "noproto")
1256 or err_msg.startswith(("unknown command ", "noproto "))
1257 ):
1258 raise error
1259 if self._protocol_specified_explicitly or (
1260 self.maint_notifications_config
1261 and self.maint_notifications_config.enabled is True
1262 ):
1263 raise error
1264 logger.warning(
1265 "Server/proxy at %s does not support HELLO (RESP%s). "
1266 "Falling back to RESP2. To silence this warning, "
1267 "set protocol=2 explicitly or upgrade your "
1268 "server/proxy. Module commands (JSON, Search, TimeSeries, Bloom, "
1269 "vector sets) do not adapt their response parsers after automatic "
1270 "fallback; set protocol=2 explicitly before using them.",
1271 self._host_error(),
1272 self.protocol,
1273 )
1274 if isinstance(self._parser, _AsyncRESP3Parser):
1275 self.set_parser(_AsyncRESP2Parser)
1276 self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
1277 self._parser.on_connect(self)
1278 self.protocol = 2
1279 self._resp2_fallback = True
1280 self.handshake_metadata = {}
1281 self._oss_cluster_maint_notifications_handler = None
1282 self._maint_notifications_pool_handler = None
1283 self._maint_notifications_connection_handler = None
1284 if auth_args:
1285 await self._do_resp2_auth(auth_args)
1286
1287 async def on_connect_check_health(self, check_health: bool = True) -> None:
1288 # A fresh socket is a new server session: no prepared HIMPORT fieldsets.
1289 self._reset_himport_state()
1290 self._parser.on_connect(self)
1291 parser = self._parser
1292
1293 auth_args = None
1294 # if credential provider or username and/or password are set, authenticate
1295 if self.credential_provider or (self.username or self.password):
1296 cred_provider = (
1297 self.credential_provider
1298 or UsernamePasswordCredentialProvider(self.username, self.password)
1299 )
1300 auth_args = await cred_provider.get_credentials_async()
1301
1302 # if resp version is specified and we have auth args,
1303 # we need to send them via HELLO
1304 if auth_args and check_protocol_version(self.protocol, 3):
1305 if isinstance(self._parser, _AsyncRESP2Parser):
1306 self.set_parser(_AsyncRESP3Parser)
1307 # update cluster exception classes
1308 self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
1309 self._parser.on_connect(self)
1310 hello_auth_args = auth_args
1311 if len(auth_args) == 1:
1312 hello_auth_args = ("default", auth_args[0])
1313 # avoid checking health here -- PING will fail if we try
1314 # to check the health prior to the AUTH
1315 await self.send_command(
1316 "HELLO", self.protocol, "AUTH", *hello_auth_args, check_health=False
1317 )
1318 try:
1319 self.handshake_metadata = await self.read_response()
1320 if self.handshake_metadata.get(b"proto") != int(
1321 self.protocol
1322 ) and self.handshake_metadata.get("proto") != int(self.protocol):
1323 raise ConnectionError("Invalid RESP version")
1324 except ResponseError as e:
1325 await self._fallback_to_resp2(e, parser, auth_args=auth_args)
1326 # avoid checking health here -- PING will fail if we try
1327 # to check the health prior to the AUTH
1328 elif auth_args:
1329 await self._do_resp2_auth(auth_args)
1330
1331 # if resp version is specified, switch to it
1332 elif check_protocol_version(self.protocol, 3):
1333 if isinstance(self._parser, _AsyncRESP2Parser):
1334 self.set_parser(_AsyncRESP3Parser)
1335 # update cluster exception classes
1336 self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
1337 self._parser.on_connect(self)
1338 await self.send_command("HELLO", self.protocol, check_health=check_health)
1339 try:
1340 self.handshake_metadata = await self.read_response()
1341 if (
1342 self.handshake_metadata.get(b"proto") != self.protocol
1343 and self.handshake_metadata.get("proto") != self.protocol
1344 ):
1345 raise ConnectionError("Invalid RESP version")
1346 except ResponseError as e:
1347 await self._fallback_to_resp2(e, parser)
1348
1349 # Activate maintenance notifications for this connection
1350 # if enabled in the configuration
1351 # This is a no-op if maintenance notifications are not enabled
1352 await self.activate_maint_notifications_handling_if_enabled(
1353 check_health=check_health
1354 )
1355
1356 # if a client_name is given, set it
1357 if self.client_name:
1358 await self.send_command(
1359 "CLIENT",
1360 "SETNAME",
1361 self.client_name,
1362 check_health=check_health,
1363 )
1364 if str_if_bytes(await self.read_response()) != "OK":
1365 raise ConnectionError("Error setting client name")
1366
1367 # Set the library name and version from driver_info, pipeline for lower startup latency
1368 lib_name_sent = False
1369 lib_version_sent = False
1370
1371 if self.driver_info and self.driver_info.formatted_name:
1372 await self.send_command(
1373 "CLIENT",
1374 "SETINFO",
1375 "LIB-NAME",
1376 self.driver_info.formatted_name,
1377 check_health=check_health,
1378 )
1379 lib_name_sent = True
1380
1381 if self.driver_info and self.driver_info.lib_version:
1382 await self.send_command(
1383 "CLIENT",
1384 "SETINFO",
1385 "LIB-VER",
1386 self.driver_info.lib_version,
1387 check_health=check_health,
1388 )
1389 lib_version_sent = True
1390
1391 # if a database is specified, switch to it. Also pipeline this
1392 if self.db:
1393 await self.send_command("SELECT", self.db, check_health=check_health)
1394
1395 # read responses from pipeline
1396 for _ in range(sum([lib_name_sent, lib_version_sent])):
1397 try:
1398 await self.read_response()
1399 except ResponseError:
1400 pass
1401
1402 if self.db:
1403 if str_if_bytes(await self.read_response()) != "OK":
1404 raise ConnectionError("Invalid Database")
1405
1406 async def disconnect(
1407 self,
1408 nowait: bool = False,
1409 error: Optional[Exception] = None,
1410 failure_count: Optional[int] = None,
1411 health_check_failed: bool = False,
1412 ) -> None:
1413 """Disconnects from the Redis server"""
1414 # The server session is gone, so any HIMPORT fieldsets prepared on this
1415 # socket no longer exist; reset the tracking.
1416 self._reset_himport_state()
1417 # Likewise the relaxation a maintenance applied to it: restored and
1418 # reported here, ahead of a close that may time out or be skipped
1419 self._complete_maintenance_on_disconnect()
1420 self._parser.on_disconnect()
1421 # Reset the reconnect flag
1422 self.reset_should_reconnect()
1423 if not self.is_connected:
1424 return
1425 try:
1426 # On Python 3.13+, asyncio.timeout() raises RuntimeError when called
1427 # outside a running Task (e.g. during GC finalization or event-loop
1428 # callbacks). In that context we fall back to a synchronous close.
1429 # See https://github.com/redis/redis-py/issues/3856
1430 if asyncio.current_task() is None:
1431 self._close()
1432 return
1433
1434 # Taken before the first await, as sync does, so a concurrent
1435 # disconnect() finds no socket to close and records nothing.
1436 writer = self._writer
1437 self._reader = None
1438 self._writer = None
1439 try:
1440 async with async_timeout(self.socket_connect_timeout):
1441 try:
1442 writer.close() # type: ignore[union-attr]
1443 # wait for close to finish, except when handling errors
1444 # and forcefully disconnecting.
1445 if not nowait:
1446 await writer.wait_closed() # type: ignore[union-attr]
1447 except OSError:
1448 pass
1449 except asyncio.TimeoutError:
1450 raise TimeoutError(
1451 f"Timed out closing connection after {self.socket_connect_timeout}"
1452 ) from None
1453 finally:
1454 # Reached on every close, including one that times out or is
1455 # cancelled. The recorders never suspend, so awaiting them here is
1456 # safe even while a cancellation propagates.
1457 if error:
1458 if health_check_failed:
1459 close_reason = CloseReason.HEALTHCHECK_FAILED
1460 else:
1461 close_reason = CloseReason.ERROR
1462
1463 if (
1464 failure_count is not None
1465 and failure_count > self.retry.get_retries()
1466 ):
1467 await record_error_count(
1468 server_address=getattr(self, "host", None),
1469 server_port=getattr(self, "port", None),
1470 network_peer_address=getattr(self, "host", None),
1471 network_peer_port=getattr(self, "port", None),
1472 error_type=error,
1473 retry_attempts=failure_count,
1474 )
1475
1476 await record_connection_closed(
1477 close_reason=close_reason,
1478 error_type=error,
1479 )
1480 else:
1481 await record_connection_closed(
1482 close_reason=CloseReason.APPLICATION_CLOSE,
1483 )
1484
1485 async def _send_ping(self):
1486 """Send PING, expect PONG in return"""
1487 await self.send_command("PING", check_health=False)
1488 if str_if_bytes(await self.read_response()) != "PONG":
1489 raise ConnectionError("Bad response from PING health check")
1490
1491 async def _ping_failed(self, error, failure_count):
1492 """Function to call when PING fails"""
1493 await self.disconnect(
1494 error=error, failure_count=failure_count, health_check_failed=True
1495 )
1496
1497 async def check_health(self):
1498 """Check the health of the connection with a PING/PONG"""
1499 if (
1500 self.health_check_interval
1501 and asyncio.get_running_loop().time() > self.next_health_check
1502 ):
1503 await self.retry.call_with_retry(
1504 self._send_ping, self._ping_failed, with_failure_count=True
1505 )
1506
1507 async def _send_packed_command(self, command: Iterable[bytes]) -> None:
1508 writer = self._writer
1509 if writer is None or writer.transport.is_closing():
1510 raise ConnectionError("Connection closed by the server before write")
1511 try:
1512 writer.writelines(command)
1513 await writer.drain()
1514 except (TypeError, AttributeError) as e:
1515 # CPython gh-136234 adds the missing connection-lost check in 3.13.10+
1516 # and 3.14.1+. Python 3.12, 3.13.0-3.13.9, and 3.14.0 can instead
1517 # leak TypeError or AttributeError from the transport (#4287).
1518 if writer.transport.is_closing():
1519 raise ConnectionError(
1520 "Connection closed by the server while writing"
1521 ) from e
1522 raise
1523
1524 async def send_packed_command(
1525 self, command: Union[bytes, str, Iterable[bytes]], check_health: bool = True
1526 ) -> None:
1527 if not self.is_connected:
1528 await self.connect_check_health(check_health=False)
1529 if check_health:
1530 await self.check_health()
1531
1532 try:
1533 if isinstance(command, str):
1534 command = command.encode()
1535 if isinstance(command, bytes):
1536 command = [command]
1537 if self.socket_timeout:
1538 await asyncio.wait_for(
1539 self._send_packed_command(command), self.socket_timeout
1540 )
1541 else:
1542 await self._send_packed_command(command)
1543 except asyncio.TimeoutError as e:
1544 add_debug_log_for_connection_failure(self, e, "writing command")
1545 await self.disconnect(nowait=True)
1546 if is_os_level_timeout(e):
1547 # ETIMEDOUT from the OS: the connection is dead, not slow.
1548 raise ConnectionError(
1549 f"Error {e.errno} while writing to socket. {e.strerror}."
1550 ) from e
1551 raise TimeoutError("Timeout writing to socket") from None
1552 except OSError as e:
1553 add_debug_log_for_connection_failure(self, e, "writing command")
1554 await self.disconnect(nowait=True)
1555 if len(e.args) == 1:
1556 err_no, errmsg = "UNKNOWN", e.args[0]
1557 else:
1558 err_no = e.args[0]
1559 errmsg = e.args[1]
1560 raise ConnectionError(
1561 f"Error {err_no} while writing to socket. {errmsg}."
1562 ) from e
1563 except BaseException as e:
1564 # BaseExceptions can be raised when a socket send operation is not
1565 # finished, e.g. due to a timeout. Ideally, a caller could then re-try
1566 # to send un-sent data. However, the send_packed_command() API
1567 # does not support it so there is no point in keeping the connection open.
1568 add_debug_log_for_connection_failure(self, e, "writing command")
1569 await self.disconnect(nowait=True)
1570 raise
1571
1572 async def send_command(self, *args: Any, **kwargs: Any) -> None:
1573 """Pack and send a command to the Redis server"""
1574 await self.send_packed_command(
1575 self.pack_command(*args), check_health=kwargs.get("check_health", True)
1576 )
1577
1578 @deprecated_function(
1579 version="8.0.0", reason="Use can_read() instead", name="can_read_destructive"
1580 )
1581 async def can_read_destructive(self) -> bool:
1582 """Check the socket to see if there's data loaded in the buffer."""
1583 try:
1584 return await self._parser.can_read()
1585 except OSError as e:
1586 await self.disconnect(nowait=True)
1587 host_error = self._host_error()
1588 raise ConnectionError(
1589 f"Error while reading from {host_error}: {e.args}"
1590 ) from e
1591
1592 async def can_read(self) -> bool:
1593 """Check the socket to see if there's data loaded in the buffer."""
1594 # TODO: Rename this API; it detects pending data or dirty/closed
1595 # connection state, not only whether application data can be read.
1596 try:
1597 return await self._parser.can_read()
1598 except OSError as e:
1599 await self.disconnect(nowait=True)
1600 host_error = self._host_error()
1601 raise ConnectionError(
1602 f"Error while reading from {host_error}: {e.args}"
1603 ) from e
1604
1605 async def read_response(
1606 self,
1607 disable_decoding: bool = False,
1608 timeout: float | None = None,
1609 *,
1610 disconnect_on_error: bool = True,
1611 push_request: bool | None = False,
1612 ):
1613 """Read the response from a previously sent command.
1614
1615 ``timeout`` semantics:
1616 - ``None`` (default): fall back to ``self.socket_timeout``.
1617 - ``math.inf``: block indefinitely with no timeout. Used by PubSub
1618 blocking reads (``listen()`` / ``get_message(timeout=None)`` /
1619 ``parse_response(block=True)``) where the configured
1620 ``socket_timeout`` must not abort the read.
1621 - ``float``: apply that timeout in seconds for this single read.
1622
1623 TODO(next-major): replace the ``math.inf`` opt-in with a SENTINEL
1624 default for ``timeout``. After that change, ``timeout=None`` will
1625 mean "no timeout, block until a response arrives" (matching the
1626 long-standing PubSub docstring contract) and the SENTINEL default
1627 will be the value that falls back to ``self.socket_timeout``.
1628 That swap is a breaking change, so it must wait for a major
1629 release. Until then, callers that need an indefinitely blocking
1630 read pass ``math.inf`` explicitly.
1631 """
1632 # TODO(next-major): drop the math.inf branch. Use SENTINEL as the
1633 # default for ``timeout`` and treat ``timeout is None`` as the
1634 # "no timeout" signal (matching the PubSub docstring contract).
1635 # Match only positive infinity here. ``-math.inf`` is not a valid
1636 # "block forever" signal and historically behaved as an already-
1637 # expired timeout; preserve that.
1638 if timeout == math.inf:
1639 read_timeout = None
1640 else:
1641 read_timeout = timeout if timeout is not None else self.socket_timeout
1642 host_error = self._host_error()
1643 try:
1644 if read_timeout is not None:
1645 timeout_context = async_timeout(read_timeout)
1646 if timeout is None:
1647 async with timeout_context as active_timeout:
1648 self._active_read_timeout = active_timeout
1649 try:
1650 response = await self._read_response_from_parser(
1651 disable_decoding=disable_decoding,
1652 push_request=push_request,
1653 )
1654 finally:
1655 self._active_read_timeout = None
1656 else:
1657 async with timeout_context:
1658 response = await self._read_response_from_parser(
1659 disable_decoding=disable_decoding,
1660 push_request=push_request,
1661 )
1662 else:
1663 response = await self._read_response_from_parser(
1664 disable_decoding=disable_decoding,
1665 push_request=push_request,
1666 )
1667 except asyncio.TimeoutError as e:
1668 if is_os_level_timeout(e):
1669 # The OS reported ETIMEDOUT on the socket (e.g. after a network
1670 # change): the connection is dead, not slow. Returning None here
1671 # made PubSub.listen() re-read the dead socket in a busy loop.
1672 if disconnect_on_error:
1673 add_debug_log_for_connection_failure(self, e, "reading response")
1674 await self.disconnect(nowait=True)
1675 raise ConnectionError(
1676 f"Error while reading from {host_error} : {e.args}"
1677 ) from e
1678 if timeout is not None:
1679 # user requested timeout, return None. Operation can be retried
1680 return None
1681 # it was a self.socket_timeout error.
1682 if disconnect_on_error:
1683 add_debug_log_for_connection_failure(self, e, "reading response")
1684 await self.disconnect(nowait=True)
1685 raise TimeoutError(f"Timeout reading from {host_error}")
1686 except OSError as e:
1687 if disconnect_on_error:
1688 add_debug_log_for_connection_failure(self, e, "reading response")
1689 await self.disconnect(nowait=True)
1690 raise ConnectionError(
1691 f"Error while reading from {host_error} : {e.args}"
1692 ) from e
1693 except UNRECOVERABLE_PARSE_ERRORS as e:
1694 # See the sync Connection.read_response and #4291. The async parser
1695 # re-parses from self._pos = 0 rather than rewinding a socket
1696 # buffer, but the consequence is the same: the bytes that already
1697 # failed to parse are still there, so the connection is not
1698 # reusable no matter what disconnect_on_error says.
1699 add_debug_log_for_connection_failure(self, e, "reading response")
1700 await self.disconnect(nowait=True)
1701 raise
1702 except BaseException as e:
1703 # Also by default close in case of BaseException. A lot of code
1704 # relies on this behaviour when doing Command/Response pairs.
1705 # See #1128.
1706 if disconnect_on_error:
1707 add_debug_log_for_connection_failure(self, e, "reading response")
1708 await self.disconnect(nowait=True)
1709 raise
1710
1711 if self.health_check_interval:
1712 next_time = asyncio.get_running_loop().time() + self.health_check_interval
1713 self.next_health_check = next_time
1714
1715 if isinstance(response, ResponseError):
1716 try:
1717 raise response from None
1718 finally:
1719 del response # avoid creating ref cycles
1720 return response
1721
1722 async def _read_response_from_parser(
1723 self, disable_decoding: bool = False, push_request: bool | None = False
1724 ):
1725 if check_protocol_version(self.protocol, 3):
1726 return await self._parser.read_response(
1727 disable_decoding=disable_decoding, push_request=push_request
1728 )
1729 return await self._parser.read_response(disable_decoding=disable_decoding)
1730
1731 def pack_command(self, *args: EncodableT) -> List[bytes]:
1732 if self._command_packer is not None:
1733 return self._command_packer.pack(*args)
1734 return self._pack_command_python(*args)
1735
1736 def _pack_command_python(self, *args: EncodableT) -> List[bytes]:
1737 """Pack a series of arguments into the Redis protocol"""
1738 output = []
1739 # the client might have included 1 or more literal arguments in
1740 # the command name, e.g., 'CONFIG GET'. The Redis server expects these
1741 # arguments to be sent separately, so split the first argument
1742 # manually. These arguments should be bytestrings so that they are
1743 # not encoded.
1744 assert not isinstance(args[0], float)
1745 if isinstance(args[0], str):
1746 args = tuple(args[0].encode().split()) + args[1:]
1747 elif b" " in args[0]:
1748 args = tuple(args[0].split()) + args[1:]
1749
1750 buff = b"*%d\r\n" % len(args)
1751
1752 buffer_cutoff = self._buffer_cutoff
1753 for arg in map(self.encoder.encode, args):
1754 # to avoid large string mallocs, chunk the command into the
1755 # output list if we're sending large values or memoryviews
1756 arg_length = len(arg)
1757 if (
1758 len(buff) > buffer_cutoff
1759 or arg_length > buffer_cutoff
1760 or isinstance(arg, memoryview)
1761 ):
1762 output.append(b"%s$%d\r\n" % (buff, arg_length))
1763 output.append(arg)
1764 buff = SYM_CRLF
1765 else:
1766 buff = b"%s$%d\r\n%s\r\n" % (buff, arg_length, arg)
1767 output.append(buff)
1768 return output
1769
1770 def pack_commands(self, commands: Iterable[Iterable[EncodableT]]) -> List[bytes]:
1771 """Pack multiple commands into the Redis protocol"""
1772 output: List[bytes] = []
1773 pieces: List[bytes] = []
1774 buffer_length = 0
1775 buffer_cutoff = self._buffer_cutoff
1776
1777 for cmd in commands:
1778 for chunk in self.pack_command(*cmd):
1779 chunklen = len(chunk)
1780 if (
1781 buffer_length > buffer_cutoff
1782 or chunklen > buffer_cutoff
1783 or isinstance(chunk, memoryview)
1784 ):
1785 if pieces:
1786 output.append(SYM_EMPTY.join(pieces))
1787 buffer_length = 0
1788 pieces = []
1789
1790 if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
1791 output.append(chunk)
1792 else:
1793 pieces.append(chunk)
1794 buffer_length += chunklen
1795
1796 if pieces:
1797 output.append(SYM_EMPTY.join(pieces))
1798 return output
1799
1800 def _socket_is_empty(self):
1801 """Check if the socket is empty"""
1802 return len(self._reader._buffer) == 0
1803
1804 async def process_invalidation_messages(self):
1805 while not self._socket_is_empty():
1806 await self.read_response(push_request=True)
1807
1808 def set_re_auth_token(self, token: TokenInterface | None):
1809 self._re_auth_token = token
1810
1811 async def re_auth(self):
1812 """
1813 Send the pending AUTH, if any.
1814
1815 The token stays pending until this socket accepts it, or until the
1816 connection opens a new socket, whose handshake authenticates with
1817 current credentials. A connection that is disconnected, or marked for
1818 reconnect, is skipped for that reason: the AUTH would go to a socket
1819 that is about to be replaced. A token set while the AUTH is in flight
1820 stays pending.
1821 """
1822 token = self._re_auth_token
1823 if token is None or not self.is_connected or self.should_reconnect():
1824 return
1825 await self.send_command("AUTH", token.try_get("oid"), token.get_value())
1826 await self.read_response()
1827 if self._re_auth_token is token:
1828 self._re_auth_token = None
1829
1830
1831class Connection(AbstractConnection):
1832 "Manages TCP communication to and from a Redis server"
1833
1834 def __init__(
1835 self,
1836 *,
1837 host: str = "localhost",
1838 port: str | int = 6379,
1839 socket_keepalive: bool = True,
1840 socket_keepalive_options: Mapping[int, int | bytes] | object | None = SENTINEL,
1841 socket_type: int = 0,
1842 **kwargs,
1843 ):
1844 """
1845 Initialize a TCP connection.
1846
1847 Parameters
1848 ----------
1849 socket_keepalive : bool
1850 If `True`, TCP keepalive is enabled for TCP socket connections.
1851 socket_keepalive_options : Mapping[int, int | bytes] | object | None
1852 Mapping of TCP keepalive socket option constants to values, for
1853 example `{socket.TCP_KEEPIDLE: 30}`. If left unspecified, redis-py
1854 uses TCP keepalive defaults when `socket_keepalive` is enabled:
1855 idle 30 seconds, interval 5 seconds, and 3 probes. Platform-specific
1856 options that are not available are skipped. Pass `None` or `{}` to
1857 avoid setting additional TCP keepalive options.
1858 """
1859 self.host = host
1860 # bool subclasses int; port=True would become privileged port 1.
1861 # Numeric strings stay valid. Callers still pass "6379".
1862 if isinstance(port, bool):
1863 raise TypeError("port must be an integer, not bool")
1864 if isinstance(port, str):
1865 try:
1866 port = int(port)
1867 except ValueError:
1868 raise TypeError("port must be an integer, not str") from None
1869 elif not isinstance(port, int):
1870 raise TypeError(f"port must be an integer, not {type(port).__name__}")
1871 if not 0 <= port <= 65535:
1872 raise ValueError(f"port must be in 0..65535, got {port}")
1873 self.port = port
1874 self.socket_keepalive = socket_keepalive
1875 if socket_keepalive_options is SENTINEL:
1876 socket_keepalive_options = get_default_socket_keepalive_options()
1877 self.socket_keepalive_options = socket_keepalive_options or {}
1878 self.socket_type = socket_type
1879 super().__init__(**kwargs)
1880
1881 def repr_pieces(self):
1882 pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
1883 if self.client_name:
1884 pieces.append(("client_name", self.client_name))
1885 return pieces
1886
1887 def _connection_arguments(self) -> Mapping:
1888 return {"host": self.host, "port": self.port}
1889
1890 async def _connect(self):
1891 """Create a TCP socket connection"""
1892 async with async_timeout(self.socket_connect_timeout):
1893 reader, writer = await asyncio.open_connection(
1894 **self._connection_arguments()
1895 )
1896 self._reader = reader
1897 self._writer = writer
1898 sock = writer.transport.get_extra_info("socket")
1899 if sock:
1900 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1901 try:
1902 # TCP_KEEPALIVE
1903 if self.socket_keepalive:
1904 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
1905 for k, v in self.socket_keepalive_options.items():
1906 sock.setsockopt(socket.SOL_TCP, k, v)
1907
1908 except (OSError, TypeError):
1909 # `socket_keepalive_options` might contain invalid options
1910 # causing an error. Do not leave the connection open.
1911 writer.close()
1912 raise
1913
1914 def _host_error(self) -> str:
1915 return f"{self.host}:{self.port}"
1916
1917
1918class SSLConnection(Connection):
1919 """Manages SSL connections to and from the Redis server(s).
1920 This class extends the Connection class, adding SSL functionality, and making
1921 use of ssl.SSLContext (https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
1922 """
1923
1924 def __init__(
1925 self,
1926 ssl_keyfile: Optional[str] = None,
1927 ssl_certfile: Optional[str] = None,
1928 ssl_cert_reqs: Union[str, ssl.VerifyMode] = "required",
1929 ssl_include_verify_flags: Optional[List["ssl.VerifyFlags"]] = None,
1930 ssl_exclude_verify_flags: Optional[List["ssl.VerifyFlags"]] = None,
1931 ssl_ca_certs: Optional[str] = None,
1932 ssl_ca_data: Optional[str] = None,
1933 ssl_ca_path: Optional[str] = None,
1934 ssl_check_hostname: bool = True,
1935 ssl_min_version: Optional[TLSVersion] = None,
1936 ssl_ciphers: Optional[str] = None,
1937 ssl_password: Optional[str] = None,
1938 **kwargs,
1939 ):
1940 if not SSL_AVAILABLE:
1941 raise RedisError("Python wasn't built with SSL support")
1942
1943 self.ssl_context: RedisSSLContext = RedisSSLContext(
1944 keyfile=ssl_keyfile,
1945 certfile=ssl_certfile,
1946 cert_reqs=ssl_cert_reqs,
1947 include_verify_flags=ssl_include_verify_flags,
1948 exclude_verify_flags=ssl_exclude_verify_flags,
1949 ca_certs=ssl_ca_certs,
1950 ca_data=ssl_ca_data,
1951 ca_path=ssl_ca_path,
1952 check_hostname=ssl_check_hostname,
1953 min_version=ssl_min_version,
1954 ciphers=ssl_ciphers,
1955 password=ssl_password,
1956 )
1957 super().__init__(**kwargs)
1958
1959 def _connection_arguments(self) -> Mapping:
1960 kwargs = super()._connection_arguments()
1961 kwargs["ssl"] = self.ssl_context.get()
1962 return kwargs
1963
1964 @property
1965 def keyfile(self):
1966 return self.ssl_context.keyfile
1967
1968 @property
1969 def certfile(self):
1970 return self.ssl_context.certfile
1971
1972 @property
1973 def cert_reqs(self):
1974 return self.ssl_context.cert_reqs
1975
1976 @property
1977 def include_verify_flags(self):
1978 return self.ssl_context.include_verify_flags
1979
1980 @property
1981 def exclude_verify_flags(self):
1982 return self.ssl_context.exclude_verify_flags
1983
1984 @property
1985 def ca_certs(self):
1986 return self.ssl_context.ca_certs
1987
1988 @property
1989 def ca_data(self):
1990 return self.ssl_context.ca_data
1991
1992 @property
1993 def check_hostname(self):
1994 return self.ssl_context.check_hostname
1995
1996 @property
1997 def min_version(self):
1998 return self.ssl_context.min_version
1999
2000
2001class RedisSSLContext:
2002 __slots__ = (
2003 "keyfile",
2004 "certfile",
2005 "cert_reqs",
2006 "include_verify_flags",
2007 "exclude_verify_flags",
2008 "ca_certs",
2009 "ca_data",
2010 "ca_path",
2011 "context",
2012 "check_hostname",
2013 "min_version",
2014 "ciphers",
2015 "password",
2016 )
2017
2018 def __init__(
2019 self,
2020 keyfile: Optional[str] = None,
2021 certfile: Optional[str] = None,
2022 cert_reqs: Optional[Union[str, ssl.VerifyMode]] = None,
2023 include_verify_flags: Optional[List["ssl.VerifyFlags"]] = None,
2024 exclude_verify_flags: Optional[List["ssl.VerifyFlags"]] = None,
2025 ca_certs: Optional[str] = None,
2026 ca_data: Optional[str] = None,
2027 ca_path: Optional[str] = None,
2028 check_hostname: bool = False,
2029 min_version: Optional[TLSVersion] = None,
2030 ciphers: Optional[str] = None,
2031 password: Optional[str] = None,
2032 ):
2033 if not SSL_AVAILABLE:
2034 raise RedisError("Python wasn't built with SSL support")
2035
2036 self.keyfile = keyfile
2037 self.certfile = certfile
2038 if cert_reqs is None:
2039 cert_reqs = ssl.CERT_NONE
2040 elif isinstance(cert_reqs, str):
2041 CERT_REQS = { # noqa: N806
2042 "none": ssl.CERT_NONE,
2043 "optional": ssl.CERT_OPTIONAL,
2044 "required": ssl.CERT_REQUIRED,
2045 }
2046 if cert_reqs not in CERT_REQS:
2047 raise RedisError(
2048 f"Invalid SSL Certificate Requirements Flag: {cert_reqs}"
2049 )
2050 cert_reqs = CERT_REQS[cert_reqs]
2051 self.cert_reqs = cert_reqs
2052 self.include_verify_flags = include_verify_flags
2053 self.exclude_verify_flags = exclude_verify_flags
2054 self.ca_certs = ca_certs
2055 self.ca_data = ca_data
2056 self.ca_path = ca_path
2057 self.check_hostname = (
2058 check_hostname if self.cert_reqs != ssl.CERT_NONE else False
2059 )
2060 self.min_version = min_version
2061 self.ciphers = ciphers
2062 self.password = password
2063 self.context: Optional[SSLContext] = None
2064
2065 def _build(self) -> SSLContext:
2066 context = ssl.create_default_context()
2067 context.check_hostname = self.check_hostname
2068 context.verify_mode = self.cert_reqs
2069 if self.include_verify_flags:
2070 for flag in self.include_verify_flags:
2071 context.verify_flags |= flag
2072 if self.exclude_verify_flags:
2073 for flag in self.exclude_verify_flags:
2074 context.verify_flags &= ~flag
2075 if self.certfile or self.keyfile:
2076 context.load_cert_chain(
2077 certfile=self.certfile,
2078 keyfile=self.keyfile,
2079 password=self.password,
2080 )
2081 if self.ca_certs or self.ca_data or self.ca_path:
2082 context.load_verify_locations(
2083 cafile=self.ca_certs, capath=self.ca_path, cadata=self.ca_data
2084 )
2085 if self.min_version is not None:
2086 context.minimum_version = self.min_version
2087 if self.ciphers is not None:
2088 context.set_ciphers(self.ciphers)
2089 return context
2090
2091 def get(self) -> SSLContext:
2092 if not self.context:
2093 if not isinstance(self.password, (str, bytes, type(None))):
2094 # Only the documented password types are shared. Anything else gets a
2095 # private context, so the cache key never holds a reference to it.
2096 self.context = self._build()
2097 else:
2098 self.context = get_shared_ssl_context(
2099 self._build,
2100 (
2101 type(self),
2102 self.cert_reqs,
2103 self.check_hostname,
2104 tuple(self.include_verify_flags or ()),
2105 tuple(self.exclude_verify_flags or ()),
2106 self.password,
2107 self.ca_data,
2108 self.min_version,
2109 self.ciphers,
2110 ),
2111 (self.certfile, self.keyfile, self.ca_certs, self.ca_path),
2112 )
2113 return self.context
2114
2115
2116class UnixDomainSocketConnection(AbstractConnection):
2117 "Manages UDS communication to and from a Redis server"
2118
2119 def __init__(self, *, path: str = "", **kwargs):
2120 self.path = path
2121 super().__init__(**kwargs)
2122
2123 def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
2124 pieces = [("path", self.path), ("db", self.db)]
2125 if self.client_name:
2126 pieces.append(("client_name", self.client_name))
2127 return pieces
2128
2129 async def _connect(self):
2130 async with async_timeout(self.socket_connect_timeout):
2131 reader, writer = await asyncio.open_unix_connection(path=self.path)
2132 self._reader = reader
2133 self._writer = writer
2134
2135 def _host_error(self) -> str:
2136 return self.path
2137
2138
2139FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO", "OFF")
2140
2141
2142def to_bool(value) -> Optional[bool]:
2143 if value is None or value == "":
2144 return None
2145 if isinstance(value, str) and value.upper() in FALSE_STRINGS:
2146 return False
2147 return bool(value)
2148
2149
2150def parse_ssl_verify_flags(value):
2151 # flags are passed in as a string representation of a list,
2152 # e.g. VERIFY_X509_STRICT, VERIFY_X509_PARTIAL_CHAIN
2153 verify_flags_str = value.replace("[", "").replace("]", "")
2154
2155 verify_flags = []
2156 for flag in verify_flags_str.split(","):
2157 flag = flag.strip()
2158 if not hasattr(VerifyFlags, flag):
2159 raise ValueError(f"Invalid ssl verify flag: {flag}")
2160 verify_flags.append(getattr(VerifyFlags, flag))
2161 return verify_flags
2162
2163
2164def parse_retry_on_error(value):
2165 # exception class names are passed as a comma-separated list,
2166 # e.g. ConnectionError,TimeoutError
2167 retry_on_error = []
2168 for name in value.replace("[", "").replace("]", "").split(","):
2169 name = name.strip()
2170 if not name:
2171 raise ValueError("Empty retry_on_error entry")
2172 exc = getattr(redis_exceptions, name, None)
2173 if not (isinstance(exc, type) and issubclass(exc, Exception)):
2174 raise ValueError(f"Unknown redis exception {name!r}")
2175 retry_on_error.append(exc)
2176 return retry_on_error
2177
2178
2179URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyType(
2180 {
2181 "db": int,
2182 "socket_timeout": float,
2183 "socket_connect_timeout": float,
2184 "socket_read_size": int,
2185 "socket_keepalive": to_bool,
2186 "retry_on_timeout": to_bool,
2187 "retry_on_error": parse_retry_on_error,
2188 "max_connections": int,
2189 "health_check_interval": int,
2190 "ssl_check_hostname": to_bool,
2191 "ssl_include_verify_flags": parse_ssl_verify_flags,
2192 "ssl_exclude_verify_flags": parse_ssl_verify_flags,
2193 "ssl_min_version": int,
2194 "timeout": float,
2195 "protocol": int,
2196 "legacy_responses": to_bool,
2197 }
2198)
2199
2200
2201class ConnectKwargs(TypedDict, total=False):
2202 username: str
2203 password: str
2204 connection_class: Type[AbstractConnection]
2205 host: str
2206 port: int
2207 db: int
2208 path: str
2209
2210
2211def parse_url(url: str) -> ConnectKwargs:
2212 # Scheme names are case-insensitive (RFC 3986), so normalize before the
2213 # prefix check; the "://" is required so a URL like "redis:foo" (which
2214 # urlparse would still report as the "redis" scheme) is rejected.
2215 if not url.lower().startswith(("redis://", "rediss://", "unix://")):
2216 raise ValueError(
2217 "Redis URL must specify one of the following schemes "
2218 "(redis://, rediss://, unix://)"
2219 )
2220
2221 parsed: ParseResult = urlparse(url)
2222 kwargs: ConnectKwargs = {}
2223
2224 for name, value_list in parse_qs(parsed.query).items():
2225 if value_list and len(value_list) > 0:
2226 # parse_qs() already percent-decodes query values, so use the value
2227 # as-is; unquoting again here would double-decode (e.g. "%2520" ->
2228 # "%20" -> " "). See issue #4208.
2229 value = value_list[0]
2230 parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
2231 if parser:
2232 try:
2233 kwargs[name] = parser(value)
2234 except (TypeError, ValueError):
2235 raise ValueError(f"Invalid value for '{name}' in connection URL.")
2236 else:
2237 kwargs[name] = value
2238
2239 if parsed.username:
2240 kwargs["username"] = unquote(parsed.username)
2241 if parsed.password:
2242 kwargs["password"] = unquote(parsed.password)
2243
2244 # We only support redis://, rediss:// and unix:// schemes.
2245 if parsed.scheme == "unix":
2246 if parsed.path:
2247 kwargs["path"] = unquote(parsed.path)
2248 kwargs["connection_class"] = UnixDomainSocketConnection
2249
2250 else: # implied: parsed.scheme in ("redis", "rediss")
2251 if parsed.hostname:
2252 kwargs["host"] = unquote(parsed.hostname)
2253 if parsed.port is not None:
2254 kwargs["port"] = int(parsed.port)
2255
2256 # If there's a path argument, use it as the db argument if a
2257 # querystring value wasn't specified
2258 if parsed.path and "db" not in kwargs:
2259 try:
2260 kwargs["db"] = int(unquote(parsed.path).replace("/", ""))
2261 except (AttributeError, ValueError):
2262 pass
2263
2264 if parsed.scheme == "rediss":
2265 kwargs["connection_class"] = SSLConnection
2266
2267 return kwargs
2268
2269
2270_CP = TypeVar("_CP", bound="ConnectionPool")
2271
2272
2273class ConnectionPoolInterface(ABC):
2274 @abstractmethod
2275 def get_protocol(self):
2276 pass
2277
2278 @abstractmethod
2279 def reset(self) -> None:
2280 pass
2281
2282 @abstractmethod
2283 @deprecated_args(
2284 args_to_warn=["*"],
2285 reason="Use get_connection() without args instead",
2286 version="5.3.0",
2287 )
2288 async def get_connection(
2289 self, command_name: Optional[str] = None, *keys: Any, **options: Any
2290 ) -> "AbstractConnection":
2291 pass
2292
2293 @abstractmethod
2294 def get_encoder(self) -> "Encoder":
2295 pass
2296
2297 @abstractmethod
2298 async def release(self, connection: "AbstractConnection") -> None:
2299 pass
2300
2301 @abstractmethod
2302 async def disconnect(self, inuse_connections: bool = True) -> None:
2303 pass
2304
2305 @abstractmethod
2306 async def aclose(self) -> None:
2307 pass
2308
2309 @abstractmethod
2310 def set_retry(self, retry: "Retry") -> None:
2311 pass
2312
2313 @abstractmethod
2314 async def re_auth_callback(self, token: TokenInterface) -> None:
2315 pass
2316
2317 @abstractmethod
2318 def get_connection_count(self) -> List[Tuple[int, dict]]:
2319 """
2320 Returns a connection count (both idle and in use).
2321 """
2322 pass
2323
2324
2325class AsyncMaintNotificationsAbstractConnectionPool:
2326 """
2327 Internal mixin for async maintenance notification pool wiring.
2328
2329 The handler owns notification policy.
2330 This mixin owns pool state mutation because `_available_connections`,
2331 `_in_use_connections`, `connection_kwargs`, and the non-reentrant `asyncio.Lock`
2332 all live on the pool.
2333 """
2334
2335 def __init__(
2336 self,
2337 maint_notifications_config: MaintNotificationsConfig | None = None,
2338 oss_cluster_maint_notifications_handler: (
2339 "AsyncOSSMaintNotificationsHandler | None"
2340 ) = None,
2341 **kwargs: Any,
2342 ) -> None:
2343 protocol = kwargs.get("protocol")
2344 is_protocol_supported = check_protocol_version(protocol, 3)
2345 is_connection_supported = self._maintenance_notifications_supported()
2346
2347 if (
2348 maint_notifications_config is None
2349 and is_protocol_supported
2350 and is_connection_supported
2351 ):
2352 maint_notifications_config = MaintNotificationsConfig()
2353
2354 if maint_notifications_config and maint_notifications_config.enabled:
2355 if not is_connection_supported:
2356 if maint_notifications_config.enabled is True:
2357 # Unix sockets do not have a host endpoint for CLIENT
2358 # MAINT_NOTIFICATIONS to describe.
2359 if "path" in self.connection_kwargs:
2360 raise RedisError(
2361 "Maintenance notifications are not supported for "
2362 "Unix domain socket connections"
2363 )
2364
2365 # Custom connection classes must inherit the async maintenance
2366 # mixin so handlers can update connection state safely.
2367 if not self._maintenance_notifications_connection_class_supported():
2368 connection_class = getattr(self, "connection_class", None)
2369 connection_class_name = getattr(
2370 connection_class, "__name__", connection_class
2371 )
2372 raise RedisError(
2373 "Maintenance notifications are not supported for "
2374 f"connection class {connection_class_name}"
2375 )
2376
2377 # TCP-like connections still need a host to identify the
2378 # endpoint that can move during maintenance.
2379 raise RedisError(
2380 "Maintenance notifications are not supported for connections "
2381 "without a host"
2382 )
2383 self._maint_notifications_pool_handler = None
2384 self._oss_cluster_maint_notifications_handler = None
2385 return
2386
2387 if not is_protocol_supported:
2388 raise RedisError(
2389 "Maintenance notifications handlers on connection are only supported with RESP version 3"
2390 )
2391
2392 if oss_cluster_maint_notifications_handler:
2393 self._oss_cluster_maint_notifications_handler = (
2394 oss_cluster_maint_notifications_handler
2395 )
2396 self._update_connection_kwargs_for_maint_notifications(
2397 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler
2398 )
2399 self._maint_notifications_pool_handler = None
2400 else:
2401 self._oss_cluster_maint_notifications_handler = None
2402 self._maint_notifications_pool_handler = (
2403 AsyncMaintNotificationsPoolHandler(self, maint_notifications_config)
2404 )
2405 self._update_connection_kwargs_for_maint_notifications(
2406 maint_notifications_pool_handler=self._maint_notifications_pool_handler
2407 )
2408 else:
2409 self._maint_notifications_pool_handler = None
2410 self._oss_cluster_maint_notifications_handler = None
2411
2412 async def _on_close(self) -> None:
2413 """Hook invoked from the pool's ``aclose()`` before the pool is shut down."""
2414 if self._maint_notifications_pool_handler is not None:
2415 await self._maint_notifications_pool_handler.cancel_scheduled_tasks()
2416
2417 @property
2418 @abstractmethod
2419 def connection_kwargs(self) -> dict[str, Any]:
2420 pass
2421
2422 @connection_kwargs.setter
2423 @abstractmethod
2424 def connection_kwargs(self, value: dict[str, Any]) -> None:
2425 pass
2426
2427 @abstractmethod
2428 def _get_pool_lock(self) -> asyncio.Lock:
2429 pass
2430
2431 @abstractmethod
2432 def _get_free_connections(self) -> Iterable["AbstractConnection"]:
2433 pass
2434
2435 @abstractmethod
2436 def _get_in_use_connections(self) -> Iterable["AbstractConnection"]:
2437 pass
2438
2439 def _maintenance_notifications_supported(self) -> bool:
2440 if "path" in self.connection_kwargs:
2441 return False
2442 if not self._maintenance_notifications_connection_class_supported():
2443 return False
2444 return bool(self.connection_kwargs.get("host"))
2445
2446 def _maintenance_notifications_connection_class_supported(self) -> bool:
2447 connection_class = getattr(self, "connection_class", None)
2448 if connection_class is None:
2449 return False
2450 try:
2451 return issubclass(
2452 connection_class, AsyncMaintNotificationsAbstractConnection
2453 )
2454 except TypeError:
2455 return False
2456
2457 def maint_notifications_enabled(self):
2458 """
2459 Returns:
2460 True if the maintenance notifications are enabled, False otherwise.
2461 The maintenance notifications config is stored in the pool handler.
2462 If the pool handler is not set, the maintenance notifications are not enabled.
2463 """
2464 if self._oss_cluster_maint_notifications_handler:
2465 maint_notifications_config = (
2466 self._oss_cluster_maint_notifications_handler.config
2467 )
2468 else:
2469 maint_notifications_config = (
2470 self._maint_notifications_pool_handler.config
2471 if self._maint_notifications_pool_handler
2472 else None
2473 )
2474 return maint_notifications_config and maint_notifications_config.enabled
2475
2476 async def update_maint_notifications_config(
2477 self,
2478 maint_notifications_config: MaintNotificationsConfig,
2479 oss_cluster_maint_notifications_handler: (
2480 AsyncOSSMaintNotificationsHandler | None
2481 ) = None,
2482 ) -> None:
2483 """
2484 Updates the maintenance notifications configuration.
2485 This method should be called only if the pool was created
2486 without enabling the maintenance notifications and
2487 in a later point in time maintenance notifications
2488 are requested to be enabled.
2489 """
2490 if (
2491 self.maint_notifications_enabled()
2492 and not maint_notifications_config.enabled
2493 ):
2494 raise ValueError(
2495 "Cannot disable maintenance notifications after enabling them"
2496 )
2497
2498 if oss_cluster_maint_notifications_handler:
2499 self._oss_cluster_maint_notifications_handler = (
2500 oss_cluster_maint_notifications_handler
2501 )
2502 # OSS cluster mode and pool-handler mode are mutually exclusive
2503 # (see __init__). A pool created with the default RESP3 "auto"
2504 # config wires a pool handler before this method runs; clear it so
2505 # new and existing connections are not configured with both handlers.
2506 self._maint_notifications_pool_handler = None
2507 else:
2508 if (
2509 maint_notifications_config.enabled
2510 and not self._maintenance_notifications_supported()
2511 ):
2512 if maint_notifications_config.enabled is True:
2513 # Unix sockets do not have a host endpoint for CLIENT
2514 # MAINT_NOTIFICATIONS to describe.
2515 if "path" in self.connection_kwargs:
2516 raise RedisError(
2517 "Maintenance notifications are not supported for "
2518 "Unix domain socket connections"
2519 )
2520
2521 # Custom connection classes must inherit the async maintenance
2522 # mixin so handlers can update connection state safely.
2523 if not self._maintenance_notifications_connection_class_supported():
2524 connection_class = getattr(self, "connection_class", None)
2525 connection_class_name = getattr(
2526 connection_class, "__name__", connection_class
2527 )
2528 raise RedisError(
2529 "Maintenance notifications are not supported for "
2530 f"connection class {connection_class_name}"
2531 )
2532
2533 # TCP-like connections still need a host to identify the
2534 # endpoint that can move during maintenance.
2535 raise RedisError(
2536 "Maintenance notifications are not supported for connections "
2537 "without a host"
2538 )
2539 self._maint_notifications_pool_handler = None
2540 return
2541
2542 if self._oss_cluster_maint_notifications_handler:
2543 # Pool already in OSS cluster mode; update the OSS handler config
2544 # instead of creating a mutually-exclusive pool handler (which
2545 # would be silently ignored because the OSS handler wins priority
2546 # in both update helpers below).
2547 self._oss_cluster_maint_notifications_handler.config = (
2548 maint_notifications_config
2549 )
2550 elif not self._maint_notifications_pool_handler:
2551 self._maint_notifications_pool_handler = (
2552 AsyncMaintNotificationsPoolHandler(self, maint_notifications_config)
2553 )
2554 else:
2555 self._maint_notifications_pool_handler.config = (
2556 maint_notifications_config
2557 )
2558
2559 self._update_connection_kwargs_for_maint_notifications(
2560 maint_notifications_pool_handler=self._maint_notifications_pool_handler,
2561 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler,
2562 )
2563 await self._update_maint_notifications_configs_for_connections(
2564 maint_notifications_pool_handler=self._maint_notifications_pool_handler,
2565 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler,
2566 )
2567
2568 def _update_connection_kwargs_for_maint_notifications(
2569 self,
2570 maint_notifications_pool_handler: (
2571 AsyncMaintNotificationsPoolHandler | None
2572 ) = None,
2573 oss_cluster_maint_notifications_handler: (
2574 AsyncOSSMaintNotificationsHandler | None
2575 ) = None,
2576 ) -> None:
2577 """
2578 Update the connection kwargs for all future connections.
2579 """
2580 if not self.maint_notifications_enabled():
2581 return
2582
2583 if maint_notifications_pool_handler:
2584 self.connection_kwargs.update(
2585 {
2586 "maint_notifications_pool_handler": maint_notifications_pool_handler,
2587 "maint_notifications_config": maint_notifications_pool_handler.config,
2588 }
2589 )
2590 if oss_cluster_maint_notifications_handler:
2591 self.connection_kwargs.update(
2592 {
2593 "oss_cluster_maint_notifications_handler": oss_cluster_maint_notifications_handler,
2594 "maint_notifications_config": oss_cluster_maint_notifications_handler.config,
2595 }
2596 )
2597 # OSS cluster mode and pool-handler mode are mutually exclusive.
2598 # Drop any pool handler a default (RESP3 "auto") pool creation may
2599 # have wired so future connections are not configured with both.
2600 self.connection_kwargs.pop("maint_notifications_pool_handler", None)
2601
2602 # Store original connection parameters for maintenance notifications.
2603 if self.connection_kwargs.get("orig_host_address", None) is None:
2604 # If orig_host_address is None it means we haven't
2605 # configured the original values yet
2606 self.connection_kwargs.update(
2607 {
2608 "orig_host_address": self.connection_kwargs.get("host"),
2609 "orig_socket_timeout": self.connection_kwargs.get(
2610 "socket_timeout", DEFAULT_SOCKET_TIMEOUT
2611 ),
2612 "orig_socket_connect_timeout": self.connection_kwargs.get(
2613 "socket_connect_timeout", DEFAULT_SOCKET_CONNECT_TIMEOUT
2614 ),
2615 }
2616 )
2617
2618 async def _update_maint_notifications_configs_for_connections(
2619 self,
2620 maint_notifications_pool_handler: (
2621 AsyncMaintNotificationsPoolHandler | None
2622 ) = None,
2623 oss_cluster_maint_notifications_handler: (
2624 AsyncOSSMaintNotificationsHandler | None
2625 ) = None,
2626 ) -> None:
2627 """Update the maintenance notifications config for all connections in the pool."""
2628 async with self._get_pool_lock():
2629 for conn in list(self._get_free_connections()):
2630 if oss_cluster_maint_notifications_handler:
2631 conn.set_maint_notifications_cluster_handler_for_connection(
2632 oss_cluster_maint_notifications_handler
2633 )
2634 conn.maint_notifications_config = (
2635 oss_cluster_maint_notifications_handler.config
2636 )
2637 elif maint_notifications_pool_handler:
2638 conn.set_maint_notifications_pool_handler_for_connection(
2639 maint_notifications_pool_handler
2640 )
2641 conn.maint_notifications_config = (
2642 maint_notifications_pool_handler.config
2643 )
2644 else:
2645 raise ValueError(
2646 "Either maint_notifications_pool_handler or "
2647 "oss_cluster_maint_notifications_handler must be set"
2648 )
2649 await conn.disconnect()
2650
2651 for conn in list(self._get_in_use_connections()):
2652 if oss_cluster_maint_notifications_handler:
2653 # Use set_maint_notifications_cluster_handler_for_connection
2654 # (not _configure_maintenance_notifications) so the parser is
2655 # obtained from the connection itself. _configure_* requires a
2656 # parser argument and would raise here; it would also reset the
2657 # connection's orig_* settings, which is wrong for an in-use
2658 # (active) connection. This mirrors the idle-connection branch
2659 # above and the pool-handler branches.
2660 conn.set_maint_notifications_cluster_handler_for_connection(
2661 oss_cluster_maint_notifications_handler
2662 )
2663 conn.maint_notifications_config = (
2664 oss_cluster_maint_notifications_handler.config
2665 )
2666 elif maint_notifications_pool_handler:
2667 conn.set_maint_notifications_pool_handler_for_connection(
2668 maint_notifications_pool_handler
2669 )
2670 conn.maint_notifications_config = (
2671 maint_notifications_pool_handler.config
2672 )
2673 else:
2674 raise ValueError(
2675 "Either maint_notifications_pool_handler or "
2676 "oss_cluster_maint_notifications_handler must be set"
2677 )
2678 if logger.isEnabledFor(logging.DEBUG):
2679 logger.debug(
2680 "Marking active connection for reconnect after config update "
2681 f"config update: {conn}, {conn.extract_connection_details()}"
2682 )
2683 conn.mark_for_reconnect()
2684
2685 def _should_update_connection(
2686 self,
2687 conn: "AbstractConnection",
2688 matching_pattern: str = "connected_address",
2689 matching_address: str | None = None,
2690 matching_notification_hash: int | None = None,
2691 ) -> bool:
2692 """
2693 Check if the connection should be updated based on the matching criteria.
2694 """
2695 if matching_pattern == "connected_address":
2696 if matching_address and conn.getpeername() != matching_address:
2697 return False
2698 elif matching_pattern == "configured_address":
2699 if matching_address and conn.host != matching_address:
2700 return False
2701 elif matching_pattern == "notification_hash":
2702 if (
2703 matching_notification_hash is not None
2704 and conn.maintenance_notification_hash != matching_notification_hash
2705 ):
2706 return False
2707 return True
2708
2709 def update_connection_settings(
2710 self,
2711 conn: "AsyncMaintNotificationsAbstractConnection",
2712 state: MaintenanceState | None = None,
2713 maintenance_notification_hash: int | None = None,
2714 host_address: str | None = None,
2715 relaxed_timeout: float | None = None,
2716 update_notification_hash: bool = False,
2717 reset_host_address: bool = False,
2718 reset_relaxed_timeout: bool = False,
2719 ) -> None:
2720 """
2721 Update the settings for a single connection.
2722 """
2723 if state:
2724 self._complete_maintenance_taken_over_by_handoff(conn, state)
2725 conn.maintenance_state = state
2726
2727 if update_notification_hash:
2728 # update the notification hash only if requested
2729 conn.maintenance_notification_hash = maintenance_notification_hash
2730
2731 if host_address is not None:
2732 conn.set_tmp_settings(tmp_host_address=host_address)
2733
2734 if relaxed_timeout is not None:
2735 conn.set_tmp_settings(tmp_relaxed_timeout=relaxed_timeout)
2736
2737 if reset_relaxed_timeout or reset_host_address:
2738 conn.reset_tmp_settings(
2739 reset_host_address=reset_host_address,
2740 reset_relaxed_timeout=reset_relaxed_timeout,
2741 )
2742
2743 conn.update_current_socket_timeout(relaxed_timeout)
2744
2745 def _complete_maintenance_taken_over_by_handoff(
2746 self, conn: "AsyncMaintNotificationsAbstractConnection", state: MaintenanceState
2747 ) -> None:
2748 """
2749 Report the MAINTENANCE relaxation of a connection a handoff is taking
2750 over as completed. The connection's completion notification is skipped
2751 while it is MOVING, and the handoff's own cleanup restores it without
2752 looking at what it superseded, so this is the only point at which the
2753 pair opened by the start event can be closed.
2754 """
2755 if (
2756 state is not MaintenanceState.MOVING
2757 or conn.maintenance_state is not MaintenanceState.MAINTENANCE
2758 or conn.maint_notifications_config is None
2759 ):
2760 return
2761 _dispatch_maintenance_event(
2762 conn.maint_notifications_config,
2763 MaintenanceCompletedEvent(
2764 connection_pool=self,
2765 connection=conn,
2766 state=MaintenanceState.MAINTENANCE,
2767 notification=None,
2768 config=conn.maint_notifications_config,
2769 ),
2770 )
2771
2772 async def update_connections_settings(
2773 self,
2774 state: MaintenanceState | None = None,
2775 maintenance_notification_hash: int | None = None,
2776 host_address: str | None = None,
2777 relaxed_timeout: float | None = None,
2778 matching_address: str | None = None,
2779 matching_notification_hash: int | None = None,
2780 matching_pattern: Literal[
2781 "connected_address", "configured_address", "notification_hash"
2782 ] = "connected_address",
2783 update_notification_hash: bool = False,
2784 reset_host_address: bool = False,
2785 reset_relaxed_timeout: bool = False,
2786 include_free_connections: bool = True,
2787 ) -> None:
2788 """
2789 Update the settings for all matching connections in the pool.
2790
2791 This method does not create new connections.
2792 This method does not affect the connection kwargs.
2793
2794 :param state: The maintenance state to set for the connection.
2795 :param maintenance_notification_hash: The hash of the maintenance notification
2796 to set for the connection.
2797 :param host_address: The host address to set for the connection.
2798 :param relaxed_timeout: The relaxed timeout to set for the connection.
2799 :param matching_address: The address to match for the connection.
2800 :param matching_notification_hash: The notification hash to match for the connection.
2801 :param matching_pattern: The pattern to match for the connection.
2802 :param update_notification_hash: Whether to update the notification hash for the connection.
2803 :param reset_host_address: Whether to reset the host address to the original address.
2804 :param reset_relaxed_timeout: Whether to reset the relaxed timeout to the original timeout.
2805 :param include_free_connections: Whether to include free/available connections.
2806 """
2807 async with self._get_pool_lock():
2808 self._update_connections_settings_without_locking(
2809 state=state,
2810 maintenance_notification_hash=maintenance_notification_hash,
2811 host_address=host_address,
2812 relaxed_timeout=relaxed_timeout,
2813 matching_address=matching_address,
2814 matching_notification_hash=matching_notification_hash,
2815 matching_pattern=matching_pattern,
2816 update_notification_hash=update_notification_hash,
2817 reset_host_address=reset_host_address,
2818 reset_relaxed_timeout=reset_relaxed_timeout,
2819 include_free_connections=include_free_connections,
2820 )
2821
2822 def _update_connections_settings_without_locking(
2823 self,
2824 state: MaintenanceState | None = None,
2825 maintenance_notification_hash: int | None = None,
2826 host_address: str | None = None,
2827 relaxed_timeout: float | None = None,
2828 matching_address: str | None = None,
2829 matching_notification_hash: int | None = None,
2830 matching_pattern: Literal[
2831 "connected_address", "configured_address", "notification_hash"
2832 ] = "connected_address",
2833 update_notification_hash: bool = False,
2834 reset_host_address: bool = False,
2835 reset_relaxed_timeout: bool = False,
2836 include_free_connections: bool = True,
2837 ) -> None:
2838 """
2839 Update matching connections while the caller already holds the pool lock.
2840
2841 This helper intentionally does not acquire the pool lock so callers can
2842 compose several pool mutations inside one critical section without
2843 deadlocking the non-reentrant `asyncio.Lock`.
2844 """
2845 for conn in self._get_in_use_connections():
2846 if self._should_update_connection(
2847 conn,
2848 matching_pattern,
2849 matching_address,
2850 matching_notification_hash,
2851 ):
2852 self.update_connection_settings(
2853 conn,
2854 state=state,
2855 maintenance_notification_hash=maintenance_notification_hash,
2856 host_address=host_address,
2857 relaxed_timeout=relaxed_timeout,
2858 update_notification_hash=update_notification_hash,
2859 reset_host_address=reset_host_address,
2860 reset_relaxed_timeout=reset_relaxed_timeout,
2861 )
2862
2863 if include_free_connections:
2864 for conn in self._get_free_connections():
2865 if self._should_update_connection(
2866 conn,
2867 matching_pattern,
2868 matching_address,
2869 matching_notification_hash,
2870 ):
2871 self.update_connection_settings(
2872 conn,
2873 state=state,
2874 maintenance_notification_hash=maintenance_notification_hash,
2875 host_address=host_address,
2876 relaxed_timeout=relaxed_timeout,
2877 update_notification_hash=update_notification_hash,
2878 reset_host_address=reset_host_address,
2879 reset_relaxed_timeout=reset_relaxed_timeout,
2880 )
2881
2882 def update_connection_kwargs(self, **kwargs: Any) -> None:
2883 """
2884 Update the connection kwargs for all future connections.
2885
2886 This method updates the connection kwargs for all future connections created by the pool.
2887 Existing connections are not affected.
2888 """
2889 self.connection_kwargs.update(kwargs)
2890
2891 async def apply_moving_notification(
2892 self,
2893 notification: NodeMovingNotification,
2894 config: MaintNotificationsConfig,
2895 moving_address_src: str | None,
2896 run_proactive_reconnect: bool = False,
2897 ) -> None:
2898 """
2899 Apply the pool state transition for a MOVING notification atomically.
2900
2901 Async pools use a non-reentrant `asyncio.Lock`, so the handler cannot
2902 safely compose several separately locked calls. Existing connection
2903 updates, optional proactive reconnect, and future `connection_kwargs`
2904 changes must happen under one pool-owned lock; otherwise a connection
2905 can move between active/free lists and escape handling.
2906 """
2907 if logger.isEnabledFor(logging.DEBUG):
2908 logger.debug(
2909 f"Applying MOVING notification to pool: {notification}, "
2910 f"moving address src: {moving_address_src}, "
2911 f"proactive reconnect: {run_proactive_reconnect}"
2912 )
2913 async with self._get_pool_lock():
2914 # Record maintenance state for pools that expose the hook.
2915 self._set_in_maintenance(True)
2916 try:
2917 self._update_connections_settings_without_locking(
2918 state=MaintenanceState.MOVING,
2919 maintenance_notification_hash=hash(notification),
2920 relaxed_timeout=config.relaxed_timeout,
2921 host_address=notification.new_node_host,
2922 matching_address=moving_address_src,
2923 matching_pattern="connected_address",
2924 update_notification_hash=True,
2925 include_free_connections=True,
2926 )
2927
2928 if run_proactive_reconnect:
2929 await self._run_proactive_reconnect_without_locking(
2930 moving_address_src
2931 )
2932
2933 self.update_connection_kwargs(
2934 **_build_moving_connection_kwargs(notification, config)
2935 )
2936 finally:
2937 self._set_in_maintenance(False)
2938
2939 async def run_proactive_reconnect(
2940 self,
2941 moving_address_src: str | None = None,
2942 ) -> None:
2943 """
2944 Mark active connections and disconnect free connections atomically.
2945
2946 This operation is pool-owned because the active/free lists can change
2947 while tasks acquire or release connections. Keeping the mark/disconnect
2948 pass under one lock avoids a connection moving between lists between
2949 separately locked calls.
2950 """
2951 async with self._get_pool_lock():
2952 await self._run_proactive_reconnect_without_locking(moving_address_src)
2953
2954 async def _run_proactive_reconnect_without_locking(
2955 self,
2956 moving_address_src: str | None = None,
2957 ) -> None:
2958 """
2959 Mark and disconnect matching connections while the caller holds the pool lock.
2960
2961 This helper intentionally does not acquire the pool lock so it can be
2962 reused by larger atomic operations that already hold the non-reentrant
2963 `asyncio.Lock`.
2964 """
2965 debug = logger.isEnabledFor(logging.DEBUG)
2966 for conn in self._get_in_use_connections():
2967 if self._should_update_connection(
2968 conn, "connected_address", moving_address_src
2969 ):
2970 if debug:
2971 logger.debug(
2972 f"Marking active connection for reconnect: {conn}, "
2973 f"{conn.extract_connection_details()}"
2974 )
2975 conn.mark_for_reconnect()
2976
2977 free_connections = [
2978 conn
2979 for conn in self._get_free_connections()
2980 if self._should_update_connection(
2981 conn, "connected_address", moving_address_src
2982 )
2983 ]
2984 if debug:
2985 for conn in free_connections:
2986 logger.debug(
2987 f"Disconnecting free connection: {conn}, "
2988 f"{conn.extract_connection_details()}"
2989 )
2990 await self._disconnect_connections(free_connections)
2991
2992 async def cleanup_moving_notification(
2993 self,
2994 notification_hash: int,
2995 reset_relaxed_timeout: bool,
2996 reset_host_address: bool,
2997 ) -> bool:
2998 """
2999 Revert MOVING pool state atomically after the notification TTL.
3000
3001 Future connection kwargs and existing connection state must be cleaned
3002 up in the same critical section. Splitting the cleanup lets an
3003 acquire/release interleave, which can leave stale MOVING state or undo a
3004 newer overlapping MOVING notification.
3005
3006 Returns True when the pool's connection kwargs were reverted, False when
3007 a newer MOVING notification had superseded this one and they were left
3008 for it to revert.
3009 """
3010 if logger.isEnabledFor(logging.DEBUG):
3011 logger.debug(
3012 "Cleaning up MOVING pool state for notification hash "
3013 f"{notification_hash}, reset_relaxed_timeout="
3014 f"{reset_relaxed_timeout}, reset_host_address={reset_host_address}"
3015 )
3016 async with self._get_pool_lock():
3017 kwargs = _build_moving_cleanup_connection_kwargs(
3018 self.connection_kwargs, notification_hash
3019 )
3020 if kwargs is not None:
3021 self.update_connection_kwargs(**kwargs)
3022
3023 self._update_connections_settings_without_locking(
3024 relaxed_timeout=-1,
3025 state=MaintenanceState.NONE,
3026 maintenance_notification_hash=None,
3027 matching_notification_hash=notification_hash,
3028 matching_pattern="notification_hash",
3029 update_notification_hash=True,
3030 reset_relaxed_timeout=reset_relaxed_timeout,
3031 reset_host_address=reset_host_address,
3032 include_free_connections=True,
3033 )
3034 return kwargs is not None
3035
3036 async def _disconnect_connections(
3037 self, connections: Iterable["AbstractConnection"]
3038 ) -> None:
3039 connections = tuple(connections)
3040 if not connections:
3041 return
3042 results = await asyncio.gather(
3043 *(connection.disconnect() for connection in connections),
3044 return_exceptions=True,
3045 )
3046 exc = next(
3047 (result for result in results if isinstance(result, BaseException)), None
3048 )
3049 if exc:
3050 raise exc
3051
3052 def _set_in_maintenance(self, in_maintenance: bool) -> None:
3053 """Flip the pool's maintenance flag if it exposes one (BlockingConnectionPool)."""
3054 set_in_maintenance = getattr(self, "set_in_maintenance", None)
3055 if callable(set_in_maintenance):
3056 set_in_maintenance(in_maintenance)
3057
3058
3059class ConnectionPool(
3060 AsyncMaintNotificationsAbstractConnectionPool, ConnectionPoolInterface
3061):
3062 """
3063 Create a connection pool. ``If max_connections`` is set, then this
3064 object raises :py:class:`~redis.ConnectionError` when the pool's
3065 limit is reached.
3066
3067 By default, TCP connections are created unless ``connection_class``
3068 is specified. Use :py:class:`~redis.UnixDomainSocketConnection` for
3069 unix sockets.
3070 :py:class:`~redis.SSLConnection` can be used for SSL enabled connections.
3071
3072 Any additional keyword arguments are passed to the constructor of
3073 ``connection_class``.
3074 """
3075
3076 @classmethod
3077 def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
3078 """
3079 Return a connection pool configured from the given URL.
3080
3081 For example::
3082
3083 redis://[[username]:[password]]@localhost:6379/0
3084 rediss://[[username]:[password]]@localhost:6379/0
3085 unix://[username@]/path/to/socket.sock?db=0[&password=password]
3086
3087 Three URL schemes are supported:
3088
3089 - `redis://` creates a TCP socket connection. See more at:
3090 <https://www.iana.org/assignments/uri-schemes/prov/redis>
3091 - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
3092 <https://www.iana.org/assignments/uri-schemes/prov/rediss>
3093 - ``unix://``: creates a Unix Domain Socket connection.
3094
3095 The username, password, hostname and path are passed through
3096 urllib.parse.unquote in order to replace any percent-encoded values
3097 with their corresponding characters. Querystring values are decoded
3098 by urllib.parse.parse_qs and are not unquoted again.
3099
3100 There are several ways to specify a database number. The first value
3101 found will be used:
3102
3103 1. A ``db`` querystring option, e.g. redis://localhost?db=0
3104
3105 2. If using the redis:// or rediss:// schemes, the path argument
3106 of the url, e.g. redis://localhost/0
3107
3108 3. A ``db`` keyword argument to this function.
3109
3110 If none of these options are specified, the default db=0 is used.
3111
3112 All querystring options are cast to their appropriate Python types.
3113 Boolean arguments can be specified with string values "True"/"False"
3114 or "Yes"/"No". Values that cannot be properly cast cause a
3115 ``ValueError`` to be raised. Once parsed, the querystring arguments
3116 and keyword arguments are passed to the ``ConnectionPool``'s
3117 class initializer. In the case of conflicting arguments, querystring
3118 arguments always win.
3119 """
3120 url_options = parse_url(url)
3121
3122 if "connection_class" in kwargs:
3123 url_options["connection_class"] = kwargs["connection_class"]
3124
3125 kwargs.update(url_options)
3126 return cls(**kwargs)
3127
3128 def __init__(
3129 self,
3130 connection_class: Type[AbstractConnection] = Connection,
3131 max_connections: Optional[int] = None,
3132 maint_notifications_config: MaintNotificationsConfig | None = None,
3133 **connection_kwargs,
3134 ):
3135 max_connections = max_connections or 100
3136 if not isinstance(max_connections, int) or max_connections < 0:
3137 raise ValueError('"max_connections" must be a positive integer')
3138
3139 retry = connection_kwargs.get("retry")
3140 if retry is not None:
3141 connection_kwargs["retry"] = _to_async_retry(retry)
3142
3143 self.connection_class = connection_class
3144 self._connection_kwargs = connection_kwargs
3145 self.max_connections = max_connections
3146
3147 # Resolve the HIMPORT registry. A pre-built ``himport_registry`` (shared, e.g.
3148 # from the cluster client) takes precedence; otherwise build a fresh empty one.
3149 # A registry always exists so runtime ``himport_prepare`` mutates a single object
3150 # every connection already shares. The object stays in ``connection_kwargs`` so
3151 # it reaches every connection. It is injected unconditionally (like other
3152 # auto-added pool kwargs), so a custom ``connection_class`` must accept
3153 # ``**kwargs`` (or a ``himport_registry`` parameter), as built-ins do.
3154 himport_registry = connection_kwargs.get("himport_registry")
3155 if himport_registry is None:
3156 himport_registry = HImportRegistry()
3157 connection_kwargs["himport_registry"] = himport_registry
3158 self.himport_registry = himport_registry
3159
3160 self._available_connections: List[AbstractConnection] = []
3161 self._in_use_connections: Set[AbstractConnection] = set()
3162 self.encoder_class = self.connection_kwargs.get("encoder_class", Encoder)
3163 self._lock = asyncio.Lock()
3164 self._background_releases: Set[asyncio.Task] = set()
3165 self._event_dispatcher = self.connection_kwargs.get("event_dispatcher", None)
3166 if self._event_dispatcher is None:
3167 self._event_dispatcher = EventDispatcher()
3168
3169 AsyncMaintNotificationsAbstractConnectionPool.__init__(
3170 self,
3171 maint_notifications_config=maint_notifications_config,
3172 **connection_kwargs,
3173 )
3174
3175 # Keys that should be redacted in __repr__ to avoid exposing sensitive information
3176 SENSITIVE_REPR_KEYS = frozenset(
3177 {
3178 "password",
3179 "username",
3180 "ssl_password",
3181 "credential_provider",
3182 }
3183 )
3184
3185 # Internal plumbing kwargs omitted from __repr__ (not user-facing config).
3186 OMIT_REPR_KEYS = frozenset({"himport_registry"})
3187
3188 def __repr__(self):
3189 conn_kwargs = ",".join(
3190 [
3191 f"{k}={'<REDACTED>' if k in self.SENSITIVE_REPR_KEYS else v}"
3192 for k, v in self.connection_kwargs.items()
3193 if k not in self.OMIT_REPR_KEYS
3194 ]
3195 )
3196 return (
3197 f"<{self.__class__.__module__}.{self.__class__.__name__}"
3198 f"(<{self.connection_class.__module__}.{self.connection_class.__name__}"
3199 f"({conn_kwargs})>)>"
3200 )
3201
3202 @property
3203 def connection_kwargs(self) -> dict[str, Any]:
3204 return self._connection_kwargs
3205
3206 @connection_kwargs.setter
3207 def connection_kwargs(self, value: dict[str, Any]) -> None:
3208 self._connection_kwargs = value
3209
3210 def _get_pool_lock(self) -> asyncio.Lock:
3211 return self._lock
3212
3213 def _get_free_connections(self) -> Iterable[AbstractConnection]:
3214 return self._available_connections
3215
3216 def _get_in_use_connections(self) -> Iterable[AbstractConnection]:
3217 return self._in_use_connections
3218
3219 def get_protocol(self):
3220 """
3221 Returns:
3222 The RESP protocol version, or ``None`` if the protocol is not specified,
3223 in which case the server default will be used.
3224 """
3225 return self.connection_kwargs.get("protocol", None)
3226
3227 def reset(self):
3228 # Record metrics for connections being removed before clearing
3229 # (only if attributes exist - they won't during __init__)
3230 if hasattr(self, "_available_connections") and hasattr(
3231 self, "_in_use_connections"
3232 ):
3233 idle_count = len(self._available_connections)
3234 in_use_count = len(self._in_use_connections)
3235 if idle_count > 0 or in_use_count > 0:
3236 pool_name = get_pool_name(self)
3237 # Note: Using sync version since reset() is sync
3238 from redis.observability.recorder import (
3239 record_connection_count as sync_record_connection_count,
3240 )
3241
3242 if idle_count > 0:
3243 sync_record_connection_count(
3244 pool_name=pool_name,
3245 connection_state=ConnectionState.IDLE,
3246 counter=-idle_count,
3247 )
3248 if in_use_count > 0:
3249 sync_record_connection_count(
3250 pool_name=pool_name,
3251 connection_state=ConnectionState.USED,
3252 counter=-in_use_count,
3253 )
3254
3255 self._available_connections = []
3256 self._in_use_connections = weakref.WeakSet()
3257
3258 def __del__(self) -> None:
3259 """Clean up connection pool and record metrics when garbage collected."""
3260 try:
3261 if not hasattr(self, "_available_connections") or not hasattr(
3262 self, "_in_use_connections"
3263 ):
3264 return
3265 idle_count = len(self._available_connections)
3266 in_use_count = len(self._in_use_connections)
3267 if idle_count > 0 or in_use_count > 0:
3268 pool_name = get_pool_name(self)
3269 # Note: Using sync version since __del__ is sync
3270 from redis.observability.recorder import (
3271 record_connection_count as sync_record_connection_count,
3272 )
3273
3274 if idle_count > 0:
3275 sync_record_connection_count(
3276 pool_name=pool_name,
3277 connection_state=ConnectionState.IDLE,
3278 counter=-idle_count,
3279 )
3280 if in_use_count > 0:
3281 sync_record_connection_count(
3282 pool_name=pool_name,
3283 connection_state=ConnectionState.USED,
3284 counter=-in_use_count,
3285 )
3286 except Exception:
3287 pass
3288
3289 def can_get_connection(self) -> bool:
3290 """Return True if a connection can be retrieved from the pool."""
3291 return (
3292 self._available_connections
3293 or len(self._in_use_connections) < self.max_connections
3294 )
3295
3296 @deprecated_args(
3297 args_to_warn=["*"],
3298 reason="Use get_connection() without args instead",
3299 version="5.3.0",
3300 )
3301 async def get_connection(self, command_name=None, *keys, **options):
3302 """Get a connected connection from the pool"""
3303 # Track connection count before to detect if a new connection is created
3304 async with self._lock:
3305 connections_before = len(self._available_connections) + len(
3306 self._in_use_connections
3307 )
3308 start_time_created = time.monotonic()
3309 connection = self.get_available_connection()
3310 connections_after = len(self._available_connections) + len(
3311 self._in_use_connections
3312 )
3313 is_created = connections_after > connections_before
3314
3315 # Record state transition for observability
3316 # This ensures counters stay balanced if ensure_connection() fails and release() is called
3317 pool_name = get_pool_name(self)
3318 if is_created:
3319 # New connection created and acquired: just USED +1
3320 await record_connection_count(
3321 pool_name=pool_name,
3322 connection_state=ConnectionState.USED,
3323 counter=1,
3324 )
3325 else:
3326 # Existing connection acquired from pool: IDLE -> USED
3327 await record_connection_count(
3328 pool_name=pool_name,
3329 connection_state=ConnectionState.IDLE,
3330 counter=-1,
3331 )
3332 await record_connection_count(
3333 pool_name=pool_name,
3334 connection_state=ConnectionState.USED,
3335 counter=1,
3336 )
3337
3338 # We now perform the connection check outside of the lock.
3339 try:
3340 await self.ensure_connection(connection)
3341
3342 if is_created:
3343 await record_connection_create_time(
3344 connection_pool=self,
3345 duration_seconds=time.monotonic() - start_time_created,
3346 )
3347
3348 return connection
3349 except BaseException:
3350 await self.release(connection)
3351 raise
3352
3353 def get_available_connection(self):
3354 """Get a connection from the pool, without making sure it is connected"""
3355 try:
3356 connection = self._available_connections.pop()
3357 except IndexError:
3358 if len(self._in_use_connections) >= self.max_connections:
3359 raise MaxConnectionsError("Too many connections") from None
3360 connection = self.make_connection()
3361 self._in_use_connections.add(connection)
3362 return connection
3363
3364 def get_encoder(self):
3365 """Return an encoder based on encoding settings"""
3366 kwargs = self.connection_kwargs
3367 return self.encoder_class(
3368 encoding=kwargs.get("encoding", "utf-8"),
3369 encoding_errors=kwargs.get("encoding_errors", "strict"),
3370 decode_responses=kwargs.get("decode_responses", False),
3371 )
3372
3373 def make_connection(self):
3374 """Create a new connection. Can be overridden by child classes."""
3375 # Note: We don't record IDLE here because async uses a sync make_connection
3376 # but async record_connection_count. The recording is handled in get_connection.
3377 return self.connection_class(**self.connection_kwargs)
3378
3379 async def ensure_connection(self, connection: AbstractConnection):
3380 """Ensure that the connection object is connected and valid"""
3381 await connection.connect()
3382 # connections that the pool provides should be ready to send
3383 # a command. if not, the connection was either returned to the
3384 # pool before all data has been read or the socket has been
3385 # closed. either way, reconnect and verify everything is good.
3386 # With maintenance notifications enabled the pending data may be
3387 # push notifications that have to be applied rather than a reason
3388 # to reconnect; reading them is what tells the two apart, and it
3389 # raises for a socket the server has closed in the meantime.
3390 try:
3391 if await connection.can_read():
3392 if self.maint_notifications_enabled():
3393 await connection.handle_pending_push_notifications()
3394 else:
3395 raise ConnectionError("Connection has data") from None
3396 except (ConnectionError, TimeoutError, OSError):
3397 await connection.disconnect()
3398 await connection.connect()
3399 if await connection.can_read() and not self.maint_notifications_enabled():
3400 raise ConnectionError("Connection not ready") from None
3401
3402 async def release(self, connection: AbstractConnection):
3403 """Releases the connection back to the pool"""
3404 # Run the listeners, such as a deferred AUTH, while the connection is
3405 # still in use, so no other task can take it, and outside the pool
3406 # lock, so their I/O does not block the pool. A listener error is
3407 # raised once the connection is back.
3408 listener_error = None
3409 try:
3410 await self._event_dispatcher.dispatch_async(
3411 AsyncAfterConnectionReleasedEvent(connection)
3412 )
3413 except BaseException as e:
3414 listener_error = e
3415 locked = False
3416 disconnect_failed = False
3417 try:
3418 async with self._lock:
3419 locked = True
3420 # Connections should always be returned to the correct pool,
3421 # not doing so is an error that will cause an exception here.
3422 self._in_use_connections.remove(connection)
3423 try:
3424 if connection.should_reconnect():
3425 if logger.isEnabledFor(logging.DEBUG):
3426 logger.debug(
3427 "Disconnecting released connection marked for "
3428 f"reconnect: {connection}, "
3429 f"{connection.extract_connection_details()}"
3430 )
3431 await connection.disconnect()
3432 except BaseException:
3433 # Not known to be closed: close it so reuse reconnects.
3434 connection._force_disconnect()
3435 disconnect_failed = True
3436 raise
3437 finally:
3438 # Even if disconnect() is cancelled, don't drop it.
3439 self._available_connections.append(connection)
3440 except BaseException as e:
3441 if disconnect_failed:
3442 # It is back in the pool: still record the metrics.
3443 self._run_in_background(self._finish_release(connection))
3444 elif not locked and isinstance(e, asyncio.CancelledError):
3445 # Cancelled while waiting for a contended lock: don't leak.
3446 self._release_in_background(connection)
3447 raise
3448
3449 await self._finish_release(connection)
3450 if listener_error is not None:
3451 raise listener_error
3452
3453 async def _finish_release(self, connection: AbstractConnection) -> None:
3454 # Record state transition: USED -> IDLE
3455 pool_name = get_pool_name(self)
3456 await record_connection_count(
3457 pool_name=pool_name,
3458 connection_state=ConnectionState.USED,
3459 counter=-1,
3460 )
3461 await record_connection_count(
3462 pool_name=pool_name,
3463 connection_state=ConnectionState.IDLE,
3464 counter=1,
3465 )
3466
3467 def _release_in_background(self, connection: AbstractConnection) -> None:
3468 if asyncio.current_task() in self._background_releases:
3469 return # this is the background release itself, e.g. at shutdown
3470 self._run_in_background(self.release(connection))
3471
3472 def _run_in_background(self, release_step: Awaitable[None]) -> None:
3473 task = asyncio.ensure_future(release_step)
3474 self._background_releases.add(task)
3475 task.add_done_callback(self._on_background_release_done)
3476
3477 def _on_background_release_done(self, task: asyncio.Task) -> None:
3478 self._background_releases.discard(task)
3479 if not task.cancelled() and task.exception() is not None:
3480 logger.warning(
3481 "A background connection release failed",
3482 exc_info=task.exception(),
3483 )
3484
3485 async def disconnect(self, inuse_connections: bool = True):
3486 """
3487 Disconnects connections in the pool
3488
3489 If ``inuse_connections`` is True, disconnect connections that are
3490 current in use, potentially by other tasks. Otherwise only disconnect
3491 connections that are idle in the pool.
3492 """
3493 if inuse_connections:
3494 connections: Iterable[AbstractConnection] = chain(
3495 self._available_connections, self._in_use_connections
3496 )
3497 else:
3498 connections = self._available_connections
3499 resp = await asyncio.gather(
3500 *(connection.disconnect() for connection in connections),
3501 return_exceptions=True,
3502 )
3503
3504 exc = next((r for r in resp if isinstance(r, BaseException)), None)
3505 if exc:
3506 raise exc
3507
3508 async def update_active_connections_for_reconnect(self):
3509 """
3510 Mark all active connections for reconnect.
3511 """
3512 debug = logger.isEnabledFor(logging.DEBUG)
3513 async with self._lock:
3514 for conn in self._in_use_connections:
3515 if debug:
3516 logger.debug(
3517 f"Marking active connection for reconnect: {conn}, "
3518 f"{conn.extract_connection_details()}"
3519 )
3520 conn.mark_for_reconnect()
3521
3522 async def aclose(self) -> None:
3523 """Close the pool, disconnecting all connections"""
3524 try:
3525 await self._on_close()
3526 finally:
3527 await self.disconnect()
3528
3529 async def __aenter__(self: _CP) -> _CP:
3530 return self
3531
3532 async def __aexit__(self, exc_type, exc_value, traceback) -> None:
3533 await self.aclose()
3534
3535 def set_retry(self, retry: "Retry") -> None:
3536 retry = _to_async_retry(retry)
3537 self.connection_kwargs["retry"] = retry
3538 for conn in self._available_connections:
3539 conn.retry = retry
3540 for conn in self._in_use_connections:
3541 conn.retry = retry
3542
3543 async def re_auth_callback(self, token: TokenInterface):
3544 """
3545 Send AUTH with ``token`` on every connected free connection, and defer
3546 it to the next release of every in-use one.
3547
3548 A free connection whose AUTH fails keeps ``token`` pending, like an
3549 in-use one. The first error is raised after every connection is
3550 handled, an ``AuthenticationError`` first.
3551 """
3552 auth_error = None
3553 first_error = None
3554 async with self._lock:
3555 # Send every AUTH before reading any reply, so the pool lock is
3556 # held for about one round trip instead of one per connection
3557 sent = []
3558 # Replies read so far, in send order
3559 done = 0
3560 try:
3561 for conn in self._available_connections:
3562 if not conn.is_connected:
3563 # It authenticates with current credentials when it
3564 # connects. Sending AUTH would connect it here, under the
3565 # pool lock.
3566 continue
3567 # Pending until the AUTH below succeeds
3568 conn.set_re_auth_token(token)
3569 try:
3570 await conn.retry.call_with_retry(
3571 lambda: conn.send_command(
3572 "AUTH", token.try_get("oid"), token.get_value()
3573 ),
3574 lambda error: self._mock(error),
3575 )
3576 except Exception as e:
3577 if first_error is None:
3578 first_error = e
3579 else:
3580 sent.append(conn)
3581 for conn in sent:
3582 try:
3583 await conn.retry.call_with_retry(
3584 lambda: conn.read_response(),
3585 lambda error: self._mock(error),
3586 is_retryable=lambda error: not isinstance(
3587 error, AuthenticationError
3588 ),
3589 )
3590 except AuthenticationError as e:
3591 if auth_error is None:
3592 auth_error = e
3593 except Exception as e:
3594 if first_error is None:
3595 first_error = e
3596 else:
3597 conn.set_re_auth_token(None)
3598 done += 1
3599 except BaseException:
3600 # Interrupted, for example cancelled: the replies not read yet
3601 # would be read by the next command on those connections
3602 for conn in sent[done:]:
3603 conn._force_disconnect()
3604 raise
3605 for conn in self._in_use_connections:
3606 conn.set_re_auth_token(token)
3607 if auth_error is not None:
3608 raise auth_error
3609 if first_error is not None:
3610 raise first_error
3611
3612 async def _mock(self, error: RedisError):
3613 """
3614 Dummy functions, needs to be passed as error callback to retry object.
3615 :param error:
3616 :return:
3617 """
3618 pass
3619
3620 def get_connection_count(self) -> List[tuple[int, dict]]:
3621 """
3622 Returns a connection count (both idle and in use).
3623 """
3624 attributes = AttributeBuilder.build_base_attributes()
3625 attributes[DB_CLIENT_CONNECTION_POOL_NAME] = get_pool_name(self)
3626 free_connections_attributes = attributes.copy()
3627 in_use_connections_attributes = attributes.copy()
3628
3629 free_connections_attributes[DB_CLIENT_CONNECTION_STATE] = (
3630 ConnectionState.IDLE.value
3631 )
3632 in_use_connections_attributes[DB_CLIENT_CONNECTION_STATE] = (
3633 ConnectionState.USED.value
3634 )
3635
3636 return [
3637 (len(self._available_connections), free_connections_attributes),
3638 (len(self._in_use_connections), in_use_connections_attributes),
3639 ]
3640
3641
3642class BlockingConnectionPool(ConnectionPool):
3643 """
3644 A blocking connection pool::
3645
3646 >>> from redis.asyncio import Redis, BlockingConnectionPool
3647 >>> client = Redis.from_pool(BlockingConnectionPool())
3648
3649 It performs the same function as the default
3650 :py:class:`~redis.asyncio.connection.ConnectionPool` implementation, in that,
3651 it maintains a pool of reusable connections that can be shared by
3652 multiple async redis clients.
3653
3654 The difference is that, in the event that a client tries to get a
3655 connection from the pool when all of connections are in use, rather than
3656 raising a :py:class:`~redis.exceptions.MaxConnectionsError` (as the default
3657 :py:class:`~redis.asyncio.connection.ConnectionPool` implementation does), it
3658 blocks the current `Task` for a specified number of seconds until
3659 a connection becomes available.
3660
3661 Use ``max_connections`` to increase / decrease the pool size::
3662
3663 >>> pool = BlockingConnectionPool(max_connections=10)
3664
3665 Use ``timeout`` to tell it either how many seconds to wait for a connection
3666 to become available, or to block forever:
3667
3668 >>> # Block forever.
3669 >>> pool = BlockingConnectionPool(timeout=None)
3670
3671 >>> # Raise a ``ConnectionError`` after five seconds if a connection is
3672 >>> # not available.
3673 >>> pool = BlockingConnectionPool(timeout=5)
3674 """
3675
3676 def __init__(
3677 self,
3678 max_connections: int = 50,
3679 timeout: Optional[float] = 20,
3680 connection_class: Type[AbstractConnection] = Connection,
3681 queue_class: Type[asyncio.Queue] = asyncio.LifoQueue, # deprecated
3682 **connection_kwargs,
3683 ):
3684 super().__init__(
3685 connection_class=connection_class,
3686 max_connections=max_connections,
3687 **connection_kwargs,
3688 )
3689 self._condition = asyncio.Condition()
3690 self.timeout = timeout
3691 self._in_maintenance = False
3692
3693 def set_in_maintenance(self, in_maintenance: bool) -> None:
3694 """
3695 Record the pool's maintenance state.
3696
3697 ``get_connection`` and ``release`` always serialize their pool mutations
3698 through ``self._lock``, independently of this flag, so they also wait for
3699 reauthentication and maintenance handlers.
3700 """
3701 self._in_maintenance = in_maintenance
3702
3703 @deprecated_args(
3704 args_to_warn=["*"],
3705 reason="Use get_connection() without args instead",
3706 version="5.3.0",
3707 )
3708 async def get_connection(self, command_name=None, *keys, **options):
3709 """Gets a connection from the pool, blocking until one is available"""
3710 # Start timing for wait time observability
3711 start_time_acquired = time.monotonic()
3712
3713 try:
3714 async with self._condition:
3715 async with async_timeout(self.timeout):
3716 await self._condition.wait_for(self.can_get_connection)
3717 async with self._lock:
3718 # Track connection count before to detect if a new connection is created
3719 connections_before = len(self._available_connections) + len(
3720 self._in_use_connections
3721 )
3722 start_time_created = time.monotonic()
3723 connection = super().get_available_connection()
3724 connections_after = len(self._available_connections) + len(
3725 self._in_use_connections
3726 )
3727 is_created = connections_after > connections_before
3728 except asyncio.TimeoutError as err:
3729 await record_connection_timeout(pool_name=get_pool_name(self))
3730 raise ConnectionError("No connection available.") from err
3731
3732 # Record state transition for observability.
3733 pool_name = get_pool_name(self)
3734 if is_created:
3735 # New connection created and acquired: just USED +1
3736 await record_connection_count(
3737 pool_name=pool_name,
3738 connection_state=ConnectionState.USED,
3739 counter=1,
3740 )
3741 else:
3742 # Existing connection acquired from pool: IDLE -> USED
3743 await record_connection_count(
3744 pool_name=pool_name,
3745 connection_state=ConnectionState.IDLE,
3746 counter=-1,
3747 )
3748 await record_connection_count(
3749 pool_name=pool_name,
3750 connection_state=ConnectionState.USED,
3751 counter=1,
3752 )
3753
3754 # We now perform the connection check outside of the lock.
3755 try:
3756 await self.ensure_connection(connection)
3757
3758 if is_created:
3759 await record_connection_create_time(
3760 connection_pool=self,
3761 duration_seconds=time.monotonic() - start_time_created,
3762 )
3763
3764 await record_connection_wait_time(
3765 pool_name=get_pool_name(self),
3766 duration_seconds=time.monotonic() - start_time_acquired,
3767 )
3768
3769 return connection
3770 except BaseException:
3771 await self.release(connection)
3772 raise
3773
3774 async def release(self, connection: AbstractConnection):
3775 """Releases the connection back to the pool."""
3776 # Released outside the condition, so the listeners the release runs,
3777 # such as a deferred AUTH, do not hold up the tasks waiting for a
3778 # connection. The condition is taken only to wake one of them once the
3779 # connection is back.
3780 try:
3781 await super().release(connection)
3782 finally:
3783 try:
3784 async with self._condition:
3785 self._condition.notify()
3786 except asyncio.CancelledError:
3787 # Cancelled while waiting for the condition: still wake a
3788 # waiter, or it can miss the returned connection
3789 self._run_in_background(self._notify_waiter())
3790 raise
3791
3792 async def _notify_waiter(self) -> None:
3793 async with self._condition:
3794 self._condition.notify()
3795
3796
3797def __getattr__(name: str):
3798 """
3799 Serve the deprecated ``SYM_STAR`` and ``SYM_DOLLAR`` constants, warning on the way.
3800
3801 A module attribute cannot be deprecated by decoration, so the constants are bound to
3802 private names above and resolved here instead - which is only reached because no module
3803 attribute of that name exists.
3804 """
3805 if name == "SYM_STAR":
3806 value = _DEPRECATED_SYM_STAR
3807 elif name == "SYM_DOLLAR":
3808 value = _DEPRECATED_SYM_DOLLAR
3809 else:
3810 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
3811 warn_deprecated(
3812 name,
3813 reason="Nothing in this library uses it any more",
3814 version="8.2.0",
3815 stacklevel=3,
3816 )
3817 return value