Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/connection.py: 21%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import copy
2import functools
3import ipaddress
4import logging
5import os
6import secrets
7import socket
8import sys
9import threading
10import time
11import weakref
12from abc import ABC, abstractmethod
13from itertools import chain
14from queue import Empty, Full, LifoQueue
15from typing import (
16 Any,
17 Callable,
18 Dict,
19 Iterable,
20 List,
21 Literal,
22 Optional,
23 Type,
24 TypeVar,
25 Union,
26)
27from urllib.parse import parse_qs, unquote, urlparse
29from redis.cache import (
30 CacheConfig,
31 CacheEntry,
32 CacheEntryStatus,
33 CacheFactory,
34 CacheFactoryInterface,
35 CacheInterface,
36 CacheKey,
37 CacheProxy,
38 TrackingMode,
39)
40from redis.commands.metadata import MetadataResolver
42from . import exceptions as redis_exceptions
43from ._defaults import (
44 DEFAULT_SOCKET_CONNECT_TIMEOUT,
45 DEFAULT_SOCKET_READ_SIZE,
46 DEFAULT_SOCKET_TIMEOUT,
47 get_default_socket_keepalive_options,
48)
49from ._parsers import (
50 UNRECOVERABLE_PARSE_ERRORS,
51 BaseParser,
52 Encoder,
53 _HiredisParser,
54 _RESP2Parser,
55 _RESP3Parser,
56)
57from .auth.token import TokenInterface
58from .backoff import NoBackoff
59from .credentials import CredentialProvider, UsernamePasswordCredentialProvider
60from .driver_info import DriverInfo, resolve_driver_info
61from .event import (
62 AfterConnectionReleasedEvent,
63 EventDispatcher,
64 MaintenanceCompletedEvent,
65)
66from .exceptions import (
67 AuthenticationError,
68 AuthenticationWrongNumberOfArgsError,
69 ChildDeadlockedError,
70 ConnectionError,
71 DataError,
72 MaxConnectionsError,
73 RedisError,
74 ResponseError,
75 TimeoutError,
76)
77from .himport import HImportRegistry
78from .maint_notifications import (
79 PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT,
80 MaintenanceState,
81 MaintNotificationsConfig,
82 MaintNotificationsConnectionHandler,
83 MaintNotificationsPoolHandler,
84 OSSMaintNotificationsHandler,
85 _dispatch_maintenance_event,
86)
87from .observability.attributes import (
88 DB_CLIENT_CONNECTION_POOL_NAME,
89 DB_CLIENT_CONNECTION_STATE,
90 AttributeBuilder,
91 ConnectionState,
92 CSCReason,
93 CSCResult,
94 get_pool_name,
95)
96from .observability.metrics import CloseReason
97from .observability.recorder import (
98 init_csc_items,
99 record_connection_closed,
100 record_connection_count,
101 record_connection_create_time,
102 record_connection_timeout,
103 record_connection_wait_time,
104 record_csc_eviction,
105 record_csc_network_saved,
106 record_csc_request,
107 record_error_count,
108 register_csc_items_callback,
109)
110from .retry import Retry
111from .utils import (
112 CRYPTOGRAPHY_AVAILABLE,
113 DEFAULT_RESP_VERSION,
114 HIREDIS_AVAILABLE,
115 SENTINEL,
116 SSL_AVAILABLE,
117 check_protocol_version,
118 compare_versions,
119 deprecated_args,
120 ensure_string,
121 format_error_message,
122 get_shared_ssl_context,
123 is_os_level_timeout,
124 str_if_bytes,
125 warn_deprecated,
126)
128if SSL_AVAILABLE:
129 import ssl
130 from ssl import VerifyFlags
131else:
132 ssl = None
133 VerifyFlags = None
135if HIREDIS_AVAILABLE:
136 import hiredis
138# ``SYM_STAR`` and ``SYM_DOLLAR`` are deprecated: nothing in this library uses them any
139# more. They are bound to private names and served through the module ``__getattr__``
140# below, so that reading them warns. The annotations let linters and type checkers see the
141# names without binding them, which would bypass the warning.
142SYM_STAR: bytes
143SYM_DOLLAR: bytes
144_DEPRECATED_SYM_STAR = b"*"
145_DEPRECATED_SYM_DOLLAR = b"$"
146SYM_CRLF = b"\r\n"
147SYM_EMPTY = b""
149DefaultParser: Type[Union[_RESP2Parser, _RESP3Parser, _HiredisParser]]
150if HIREDIS_AVAILABLE:
151 DefaultParser = _HiredisParser
152else:
153 DefaultParser = _RESP2Parser
155logger = logging.getLogger(__name__)
158def add_debug_log_for_connection_failure(
159 connection: "AbstractConnection",
160 error: BaseException,
161 operation: str,
162) -> None:
163 """
164 Render the connection's live state on a failure that is about to close it.
166 Must be called *before* ``disconnect()``. ``extract_connection_details()``
167 reads the resolved ip, local port and armed read timeout off the socket, so
168 once the socket is gone it can only report ``not connected`` - which hides
169 exactly the state needed to explain the failure. In particular it is what
170 tells apart a read that ran under the original timeout from one that ran
171 under a relaxed maintenance timeout.
172 """
173 if logger.isEnabledFor(logging.DEBUG):
174 logger.debug(
175 f"{type(error).__name__} while {operation}, "
176 f"with connection: {connection}, "
177 f"details: {connection.extract_connection_details()}, "
178 f"error: {error}",
179 )
182class HiredisRespSerializer:
183 def __init__(self, fallback=None, encode=None):
184 self._fallback = fallback
185 self._encode = encode
187 def pack(self, *args: List):
188 """Pack a series of arguments into the Redis protocol"""
189 if self._fallback is not None and any(
190 isinstance(arg, memoryview) for arg in args
191 ):
192 return self._fallback(*args)
193 output = []
195 if isinstance(args[0], str):
196 args = tuple(args[0].encode().split()) + args[1:]
197 elif b" " in args[0]:
198 args = tuple(args[0].split()) + args[1:]
199 args = tuple(
200 bytes(arg)
201 if isinstance(arg, (bytearray, memoryview))
202 else self._encode(arg)
203 if self._encode is not None
204 else arg
205 for arg in args
206 )
207 try:
208 output.append(hiredis.pack_command(args))
209 except TypeError:
210 _, value, traceback = sys.exc_info()
211 raise DataError(value).with_traceback(traceback)
213 return output
216class PythonRespSerializer:
217 def __init__(self, buffer_cutoff, encode) -> None:
218 self._buffer_cutoff = buffer_cutoff
219 self.encode = encode
221 def pack(self, *args):
222 """Pack a series of arguments into the Redis protocol"""
223 output = []
224 # the client might have included 1 or more literal arguments in
225 # the command name, e.g., 'CONFIG GET'. The Redis server expects these
226 # arguments to be sent separately, so split the first argument
227 # manually. These arguments should be bytestrings so that they are
228 # not encoded.
229 if isinstance(args[0], str):
230 args = tuple(args[0].encode().split()) + args[1:]
231 elif b" " in args[0]:
232 args = tuple(args[0].split()) + args[1:]
234 buff = b"*%d\r\n" % len(args)
236 buffer_cutoff = self._buffer_cutoff
237 for arg in map(self.encode, args):
238 # to avoid large string mallocs, chunk the command into the
239 # output list if we're sending large values or memoryviews
240 arg_length = len(arg)
241 if (
242 len(buff) > buffer_cutoff
243 or arg_length > buffer_cutoff
244 or isinstance(arg, memoryview)
245 ):
246 output.append(b"%s$%d\r\n" % (buff, arg_length))
247 output.append(arg)
248 buff = SYM_CRLF
249 else:
250 buff = b"%s$%d\r\n%s\r\n" % (buff, arg_length, arg)
251 output.append(buff)
252 return output
255class ConnectionInterface:
256 _resp2_fallback = False
258 @abstractmethod
259 def repr_pieces(self):
260 pass
262 @abstractmethod
263 def register_connect_callback(self, callback):
264 pass
266 @abstractmethod
267 def deregister_connect_callback(self, callback):
268 pass
270 @abstractmethod
271 def set_parser(self, parser_class):
272 pass
274 @abstractmethod
275 def get_protocol(self):
276 pass
278 @abstractmethod
279 def connect(self):
280 pass
282 @abstractmethod
283 def on_connect(self):
284 pass
286 @abstractmethod
287 def disconnect(self, *args, **kwargs):
288 pass
290 @abstractmethod
291 def check_health(self):
292 pass
294 @abstractmethod
295 def send_packed_command(self, command, check_health=True):
296 pass
298 @abstractmethod
299 def send_command(self, *args, **kwargs):
300 pass
302 @abstractmethod
303 def can_read(self, timeout: float = 0) -> bool:
304 # TODO: Rename this API; it detects pending data or dirty/closed
305 # connection state, not only whether application data can be read.
306 pass
308 @abstractmethod
309 def read_response(
310 self,
311 disable_decoding=False,
312 *,
313 timeout: Union[float, object] = SENTINEL,
314 disconnect_on_error=True,
315 push_request=False,
316 ):
317 pass
319 @abstractmethod
320 def pack_command(self, *args):
321 pass
323 @abstractmethod
324 def pack_commands(self, commands):
325 pass
327 @property
328 @abstractmethod
329 def handshake_metadata(self) -> Union[Dict[bytes, bytes], Dict[str, str]]:
330 pass
332 @abstractmethod
333 def set_re_auth_token(self, token: TokenInterface | None):
334 pass
336 @abstractmethod
337 def re_auth(self):
338 pass
340 @abstractmethod
341 def mark_for_reconnect(self):
342 """
343 Mark the connection to be reconnected on the next command.
344 This is useful when a connection is moved to a different node.
345 """
346 pass
348 @abstractmethod
349 def should_reconnect(self):
350 """
351 Returns True if the connection should be reconnected.
352 """
353 pass
355 @abstractmethod
356 def reset_should_reconnect(self):
357 """
358 Reset the internal flag to False.
359 """
360 pass
362 @abstractmethod
363 def extract_connection_details(self) -> str:
364 pass
366 @property
367 @abstractmethod
368 def is_connected(self) -> bool:
369 """
370 Return ``True`` if the connection to the server is active.
371 """
372 pass
375class MaintNotificationsAbstractConnection:
376 """
377 Abstract class for handling maintenance notifications logic.
378 This class is expected to be used as base class together with ConnectionInterface.
380 This class is intended to be used with multiple inheritance!
382 All logic related to maintenance notifications is encapsulated in this class.
383 """
385 def __init__(
386 self,
387 maint_notifications_config: Optional[MaintNotificationsConfig],
388 maint_notifications_pool_handler: Optional[
389 MaintNotificationsPoolHandler
390 ] = None,
391 maintenance_state: "MaintenanceState" = MaintenanceState.NONE,
392 maintenance_notification_hash: Optional[int] = None,
393 orig_host_address: Optional[str] = None,
394 orig_socket_timeout: Optional[float] = None,
395 orig_socket_connect_timeout: Optional[float] = None,
396 oss_cluster_maint_notifications_handler: Optional[
397 OSSMaintNotificationsHandler
398 ] = None,
399 parser: Optional[BaseParser] = None,
400 event_dispatcher: Optional[EventDispatcher] = None,
401 ):
402 """
403 Initialize the maintenance notifications for the connection.
405 Args:
406 maint_notifications_config (MaintNotificationsConfig): The configuration for maintenance notifications.
407 maint_notifications_pool_handler (Optional[MaintNotificationsPoolHandler]): The pool handler for maintenance notifications.
408 maintenance_state (MaintenanceState): The current maintenance state of the connection.
409 maintenance_notification_hash (Optional[int]): The current maintenance notification hash of the connection.
410 orig_host_address (Optional[str]): The original host address of the connection.
411 orig_socket_timeout (Optional[float]): The original socket timeout of the connection.
412 orig_socket_connect_timeout (Optional[float]): The original socket connect timeout of the connection.
413 oss_cluster_maint_notifications_handler (Optional[OSSMaintNotificationsHandler]): The OSS cluster handler for maintenance notifications.
414 parser (Optional[BaseParser]): The parser to use for maintenance notifications.
415 If not provided, the parser from the connection is used.
416 This is useful when the parser is created after this object.
417 """
418 self.maint_notifications_config = maint_notifications_config
419 self.maintenance_state = maintenance_state
420 self.maintenance_notification_hash = maintenance_notification_hash
422 if event_dispatcher is not None:
423 self.event_dispatcher = event_dispatcher
424 else:
425 self.event_dispatcher = EventDispatcher()
427 self._configure_maintenance_notifications(
428 maint_notifications_pool_handler,
429 orig_host_address,
430 orig_socket_timeout,
431 orig_socket_connect_timeout,
432 oss_cluster_maint_notifications_handler,
433 parser,
434 )
435 self._processed_start_maint_notifications = set()
436 self._skipped_end_maint_notifications = set()
438 @abstractmethod
439 def _get_parser(self) -> BaseParser:
440 pass
442 def _get_push_notifications_parser(self) -> Union[_HiredisParser, _RESP3Parser]:
443 parser = self._get_parser()
444 if not isinstance(parser, (_HiredisParser, _RESP3Parser)):
445 raise RedisError(
446 "Maintenance notifications are only supported with hiredis and RESP3 parsers!"
447 )
448 return parser
450 def _complete_maintenance_on_disconnect(self) -> None:
451 """
452 Restore the settings a maintenance relaxed on this connection when it is
453 closed, and report the relaxation as completed - the same way the
454 completion notification would have been reported. The MOVING state is
455 left alone: it is owned by the pool-level TTL cleanup.
456 """
457 if self.maintenance_state != MaintenanceState.MAINTENANCE:
458 return
459 self.reset_tmp_settings(reset_relaxed_timeout=True)
460 self.maintenance_state = MaintenanceState.NONE
461 # reset the sets that keep track of received start maint
462 # notifications and skipped end maint notifications
463 self.reset_received_notifications()
464 if self.maint_notifications_config is not None:
465 pool_handler = self._maint_notifications_pool_handler
466 _dispatch_maintenance_event(
467 self.maint_notifications_config,
468 MaintenanceCompletedEvent(
469 connection_pool=(
470 pool_handler.pool if pool_handler is not None else None
471 ),
472 connection=self,
473 state=MaintenanceState.MAINTENANCE,
474 notification=None,
475 config=self.maint_notifications_config,
476 ),
477 )
479 def handle_pending_push_notifications(self) -> None:
480 """
481 Process the push notifications buffered on this idle connection if it
482 is still alive, and report a connection that has to be reconnected.
484 A pooled connection that has readable data while idle either has push
485 notifications waiting, or has been closed by the server - or both, when
486 the notifications announced the maintenance that closed it. The socket
487 state cannot be told apart from the pending data without reading it, so
488 the notifications are collected first and handed to their handlers only
489 once the drain has shown the socket to be alive: the server closes the
490 connections of a moved endpoint when the MOVING time-to-live expires,
491 so an alive socket means the maintenance is still in progress and the
492 announced address current. A notification buffered on a socket the
493 server has since closed describes a maintenance that is over, after
494 which the configured address is what to connect to again: it is
495 discarded, and the ``ConnectionError`` raised here makes the pool
496 reconnect before any command is sent.
498 Anything read that is not a maintenance notification or a client-side
499 cache invalidation - a reply, a null or an error reply left unread by an
500 earlier command - means the connection is dirty and is reported the same
501 way, as is a drain that does not complete within
502 ``PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT``.
503 """
504 if self._resp2_fallback:
505 raise ConnectionError("Connection has data")
506 parser = self._get_push_notifications_parser()
507 deferred: list = []
509 def defer(handler):
510 def deferred_handler(notification):
511 deferred.append((handler, notification))
513 return deferred_handler
515 handlers = (
516 (parser.node_moving_push_handler_func, parser.set_node_moving_push_handler),
517 (parser.maintenance_push_handler_func, parser.set_maintenance_push_handler),
518 (
519 parser.oss_cluster_maint_push_handler_func,
520 parser.set_oss_cluster_maint_push_handler,
521 ),
522 # Client-side cache invalidations are pushes too; the ones on a
523 # connection that has to be reconnected are covered by the cache
524 # flush its disconnect performs
525 (
526 parser.invalidation_push_handler_func,
527 parser.set_invalidation_push_handler,
528 ),
529 )
530 for handler, set_handler in handlers:
531 if handler is not None:
532 set_handler(defer(handler))
534 alive = False
535 deadline = time.monotonic() + PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT
536 try:
537 while self.can_read():
538 remaining = deadline - time.monotonic()
539 if remaining <= 0:
540 raise ConnectionError(
541 "Timed out reading pending push notifications"
542 )
543 read = len(deferred)
544 # The pool disconnects the connection it handed out - with
545 # caching the proxy, not the wrapped connection - on the error.
546 # The parsers apply the timeout to each receive of a frame; the
547 # deadline bounds the drain across frames.
548 self.read_response(
549 push_request=True,
550 timeout=remaining,
551 disconnect_on_error=False,
552 )
553 # Only a push reaches a deferred handler; anything else is a
554 # reply left unread by an earlier command
555 if len(deferred) == read:
556 raise ConnectionError("Connection has data")
557 alive = True
558 except ResponseError as e:
559 raise ConnectionError("Connection has data") from e
560 finally:
561 for handler, set_handler in handlers:
562 set_handler(handler)
563 if not alive and deferred and logger.isEnabledFor(logging.DEBUG):
564 logger.debug(
565 f"Discarding {len(deferred)} push notification(s) buffered on "
566 f"a connection that is closed or dirty, reconnecting: {self}"
567 )
569 for handler, notification in deferred:
570 try:
571 handler(notification)
572 except Exception as e:
573 logger.error(f"Error handling {notification}: {e}")
575 @abstractmethod
576 def _get_socket(self) -> Optional[socket.socket]:
577 pass
579 @abstractmethod
580 def get_protocol(self) -> Union[int, str]:
581 """
582 Returns:
583 The RESP protocol version, or ``None`` if the protocol is not specified,
584 in which case the server default will be used.
585 """
586 pass
588 @property
589 @abstractmethod
590 def host(self) -> str:
591 pass
593 @host.setter
594 @abstractmethod
595 def host(self, value: str):
596 pass
598 @property
599 @abstractmethod
600 def socket_timeout(self) -> Optional[Union[float, int]]:
601 pass
603 @socket_timeout.setter
604 @abstractmethod
605 def socket_timeout(self, value: Optional[Union[float, int]]):
606 pass
608 @property
609 @abstractmethod
610 def socket_connect_timeout(self) -> Optional[Union[float, int]]:
611 pass
613 @socket_connect_timeout.setter
614 @abstractmethod
615 def socket_connect_timeout(self, value: Optional[Union[float, int]]):
616 pass
618 @abstractmethod
619 def send_command(self, *args, **kwargs):
620 pass
622 @abstractmethod
623 def read_response(
624 self,
625 disable_decoding=False,
626 *,
627 timeout: Union[float, object] = SENTINEL,
628 disconnect_on_error=True,
629 push_request=False,
630 ):
631 pass
633 @abstractmethod
634 def disconnect(self, *args, **kwargs):
635 pass
637 @abstractmethod
638 def mark_for_reconnect(self):
639 pass
641 def _configure_maintenance_notifications(
642 self,
643 maint_notifications_pool_handler: Optional[
644 MaintNotificationsPoolHandler
645 ] = None,
646 orig_host_address=None,
647 orig_socket_timeout=None,
648 orig_socket_connect_timeout=None,
649 oss_cluster_maint_notifications_handler: Optional[
650 OSSMaintNotificationsHandler
651 ] = None,
652 parser: Optional[BaseParser] = None,
653 ):
654 """
655 Enable maintenance notifications by setting up
656 handlers and storing original connection parameters.
658 Should be used ONLY with parsers that support push notifications.
659 """
660 if (
661 not self.maint_notifications_config
662 or not self.maint_notifications_config.enabled
663 ):
664 self._maint_notifications_pool_handler = None
665 self._maint_notifications_connection_handler = None
666 self._oss_cluster_maint_notifications_handler = None
667 return
669 if not parser:
670 raise RedisError(
671 "To configure maintenance notifications, a parser must be provided!"
672 )
674 if not isinstance(parser, _HiredisParser) and not isinstance(
675 parser, _RESP3Parser
676 ):
677 raise RedisError(
678 "Maintenance notifications are only supported with hiredis and RESP3 parsers!"
679 )
681 if maint_notifications_pool_handler:
682 # Extract a reference to a new pool handler that copies all properties
683 # of the original one and has a different connection reference
684 # This is needed because when we attach the handler to the parser
685 # we need to make sure that the handler has a reference to the
686 # connection that the parser is attached to.
687 self._maint_notifications_pool_handler = (
688 maint_notifications_pool_handler.get_handler_for_connection()
689 )
690 self._maint_notifications_pool_handler.set_connection(self)
691 else:
692 self._maint_notifications_pool_handler = None
694 self._maint_notifications_connection_handler = (
695 MaintNotificationsConnectionHandler(self, self.maint_notifications_config)
696 )
698 if oss_cluster_maint_notifications_handler:
699 self._oss_cluster_maint_notifications_handler = (
700 oss_cluster_maint_notifications_handler
701 )
702 # Set up OSS cluster handler to parser
703 parser.set_oss_cluster_maint_push_handler(
704 self._oss_cluster_maint_notifications_handler.handle_notification
705 )
706 else:
707 self._oss_cluster_maint_notifications_handler = None
709 # Set up pool handler to parser if available
710 if self._maint_notifications_pool_handler:
711 parser.set_node_moving_push_handler(
712 self._maint_notifications_pool_handler.handle_notification
713 )
715 # Set up connection handler
716 parser.set_maintenance_push_handler(
717 self._maint_notifications_connection_handler.handle_notification
718 )
720 # Store original connection parameters
721 self.orig_host_address = orig_host_address if orig_host_address else self.host
722 self.orig_socket_timeout = (
723 orig_socket_timeout if orig_socket_timeout else self.socket_timeout
724 )
725 self.orig_socket_connect_timeout = (
726 orig_socket_connect_timeout
727 if orig_socket_connect_timeout
728 else self.socket_connect_timeout
729 )
731 def set_maint_notifications_pool_handler_for_connection(
732 self, maint_notifications_pool_handler: MaintNotificationsPoolHandler
733 ):
734 if self._resp2_fallback:
735 return
736 # Deep copy the pool handler to avoid sharing the same pool handler
737 # between multiple connections, because otherwise each connection will override
738 # the connection reference and the pool handler will only hold a reference
739 # to the last connection that was set.
740 maint_notifications_pool_handler_copy = (
741 maint_notifications_pool_handler.get_handler_for_connection()
742 )
744 maint_notifications_pool_handler_copy.set_connection(self)
745 parser = self._get_push_notifications_parser()
746 parser.set_node_moving_push_handler(
747 maint_notifications_pool_handler_copy.handle_notification
748 )
750 self._maint_notifications_pool_handler = maint_notifications_pool_handler_copy
752 # Update maintenance notification connection handler if it doesn't exist
753 if not self._maint_notifications_connection_handler:
754 self._maint_notifications_connection_handler = (
755 MaintNotificationsConnectionHandler(
756 self, maint_notifications_pool_handler.config
757 )
758 )
759 parser.set_maintenance_push_handler(
760 self._maint_notifications_connection_handler.handle_notification
761 )
762 else:
763 self._maint_notifications_connection_handler.config = (
764 maint_notifications_pool_handler.config
765 )
767 def set_maint_notifications_cluster_handler_for_connection(
768 self, oss_cluster_maint_notifications_handler: OSSMaintNotificationsHandler
769 ):
770 if self._resp2_fallback:
771 return
772 parser = self._get_push_notifications_parser()
773 parser.set_oss_cluster_maint_push_handler(
774 oss_cluster_maint_notifications_handler.handle_notification
775 )
776 # OSS cluster mode and pool-handler mode are mutually exclusive. Clear
777 # any node-moving/pool handler a default (RESP3 "auto") pool wired in
778 # __init__ so this existing connection is not configured with both.
779 parser.set_node_moving_push_handler(None)
780 self._maint_notifications_pool_handler = None
782 self._oss_cluster_maint_notifications_handler = (
783 oss_cluster_maint_notifications_handler
784 )
786 # Update maintenance notification connection handler if it doesn't exist
787 if not self._maint_notifications_connection_handler:
788 self._maint_notifications_connection_handler = (
789 MaintNotificationsConnectionHandler(
790 self, oss_cluster_maint_notifications_handler.config
791 )
792 )
793 parser.set_maintenance_push_handler(
794 self._maint_notifications_connection_handler.handle_notification
795 )
796 else:
797 self._maint_notifications_connection_handler.config = (
798 oss_cluster_maint_notifications_handler.config
799 )
801 def _should_enable_maint_notifications(self) -> bool:
802 # Maintenance notifications are sent only if RESP3 is active
803 # and maintenance notifications are enabled
804 # and we have a host to determine the endpoint type from.
805 host = getattr(self, "host", None)
806 return bool(
807 check_protocol_version(self.get_protocol(), 3)
808 and self.maint_notifications_config
809 and self.maint_notifications_config.enabled
810 and self._maint_notifications_connection_handler
811 and host is not None
812 )
814 def activate_maint_notifications_handling_if_enabled(self, check_health=True):
815 # When the maint_notifications_config enabled mode is "auto",
816 # we just log a warning if the handshake fails
817 # When the mode is enabled=True, we raise an exception in case of failure
818 if self._should_enable_maint_notifications():
819 self._enable_maintenance_notifications(
820 maint_notifications_config=self.maint_notifications_config,
821 check_health=check_health,
822 )
824 def _enable_maintenance_notifications(
825 self, maint_notifications_config: MaintNotificationsConfig, check_health=True
826 ):
827 # Kept for callers that enable maintenance notifications outside of the
828 # connection handshake. During on_connect the send and the response
829 # handling are split (see _send_maint_notifications_command /
830 # _handle_maint_notifications_response) so the reply can be pipelined
831 # with the rest of the handshake.
832 self._send_maint_notifications_command(
833 maint_notifications_config, check_health=check_health
834 )
835 self._handle_maint_notifications_response(maint_notifications_config)
837 def _maint_notifications_command_args(
838 self, maint_notifications_config: MaintNotificationsConfig
839 ):
840 host = getattr(self, "host", None)
841 if host is None:
842 raise ValueError(
843 "Cannot enable maintenance notifications for connection"
844 " object that doesn't have a host attribute."
845 )
846 endpoint_type = maint_notifications_config.get_endpoint_type(host, self)
847 return (
848 "CLIENT",
849 "MAINT_NOTIFICATIONS",
850 "ON",
851 "moving-endpoint-type",
852 endpoint_type.value,
853 )
855 def _send_maint_notifications_command(
856 self, maint_notifications_config: MaintNotificationsConfig, check_health=True
857 ):
858 self.send_command(
859 *self._maint_notifications_command_args(maint_notifications_config),
860 check_health=check_health,
861 )
863 def _add_maint_notifications_to_handshake(self, deferred_reads, check_health=True):
864 # If maintenance notifications are enabled for this connection, send the
865 # CLIENT MAINT_NOTIFICATIONS command with the rest of the handshake tail and
866 # defer reading its reply (appended to deferred_reads), rather than paying its
867 # own round-trip. When enabled == "auto" a failure is logged and swallowed;
868 # when enabled is True it raises.
869 if not self._should_enable_maint_notifications():
870 return
871 maint_notifications_config = self.maint_notifications_config
872 self._send_maint_notifications_command(
873 maint_notifications_config, check_health=check_health
874 )
875 deferred_reads.append(
876 lambda: self._handle_maint_notifications_response(
877 maint_notifications_config
878 )
879 )
881 def _handle_maint_notifications_response(
882 self, maint_notifications_config: MaintNotificationsConfig
883 ):
884 try:
885 response = self.read_response()
886 if not response or str_if_bytes(response) != "OK":
887 raise ResponseError(
888 "The server doesn't support maintenance notifications"
889 )
890 except Exception as e:
891 if (
892 isinstance(e, ResponseError)
893 and maint_notifications_config.enabled == "auto"
894 ):
895 # Log warning but don't fail the connection
896 logger.debug(f"Failed to enable maintenance notifications: {e}")
897 else:
898 raise
900 def _read_ok_or_raise(self, error_message):
901 # Read one handshake reply and require it to be "OK".
902 if str_if_bytes(self.read_response()) != "OK":
903 raise ConnectionError(error_message)
905 def _read_optional_setinfo(self):
906 # Read one CLIENT SETINFO reply. Older servers may not support the command,
907 # so a ResponseError is swallowed instead of failing the connection.
908 try:
909 self.read_response()
910 except ResponseError:
911 pass
913 def get_resolved_ip(self) -> Optional[str]:
914 """
915 Extract the resolved IP address from an
916 established connection or resolve it from the host.
918 First tries to get the actual IP from the socket (most accurate),
919 then falls back to DNS resolution if needed.
921 Returns:
922 str: The resolved IP address, or None if it cannot be determined
923 """
925 # Method 1: Try to get the actual IP from the established socket connection
926 # This is most accurate as it shows the exact IP being used
927 try:
928 conn_socket = self._get_socket()
929 if conn_socket is not None:
930 peer_addr = conn_socket.getpeername()
931 # For TCP sockets, peer_addr is typically a (host, port) tuple.
932 # AF_UNIX sockets report a path string instead, and indexing it
933 # would yield the first character of the path.
934 if isinstance(peer_addr, tuple) and peer_addr:
935 # Return just the host part
936 return peer_addr[0]
937 except (AttributeError, OSError):
938 # Socket might not be connected or getpeername() might fail
939 pass
941 # Method 2: Fallback to DNS resolution of the host
942 # This is less accurate but works when socket is not available
943 try:
944 host = getattr(self, "host", "localhost")
945 port = getattr(self, "port", 6379)
946 if host:
947 # Use getaddrinfo to resolve the hostname to IP
948 # This mimics what the connection would do during _connect()
949 addr_info = socket.getaddrinfo(
950 host, port, socket.AF_UNSPEC, socket.SOCK_STREAM
951 )
952 if addr_info:
953 # Return the IP from the first result
954 # addr_info[0] is (family, socktype, proto, canonname, sockaddr)
955 # sockaddr[0] is the IP address
956 return str(addr_info[0][4][0])
957 except (AttributeError, OSError, socket.gaierror):
958 # DNS resolution might fail
959 pass
961 return None
963 @property
964 def maintenance_state(self) -> MaintenanceState:
965 return self._maintenance_state
967 @maintenance_state.setter
968 def maintenance_state(self, state: "MaintenanceState"):
969 self._maintenance_state = state
971 def add_maint_start_notification(self, id: int):
972 self._processed_start_maint_notifications.add(id)
974 def get_processed_start_notifications(self) -> set:
975 return self._processed_start_maint_notifications
977 def add_skipped_end_notification(self, id: int):
978 self._skipped_end_maint_notifications.add(id)
980 def get_skipped_end_notifications(self) -> set:
981 return self._skipped_end_maint_notifications
983 def reset_received_notifications(self):
984 self._processed_start_maint_notifications.clear()
985 self._skipped_end_maint_notifications.clear()
987 def getpeername(self):
988 """
989 Returns the peer name of the connection.
990 """
991 conn_socket = self._get_socket()
992 if conn_socket:
993 return conn_socket.getpeername()[0]
994 return None
996 def update_current_socket_timeout(self, relaxed_timeout: Optional[float] = None):
997 conn_socket = self._get_socket()
998 if conn_socket:
999 timeout = relaxed_timeout if relaxed_timeout != -1 else self.socket_timeout
1000 # if the current timeout is 0 it means we are in the middle of a can_read call
1001 # in this case we don't want to change the timeout because the operation
1002 # is non-blocking and should return immediately
1003 # Changing the state from non-blocking to blocking in the middle of a read operation
1004 # will lead to a deadlock
1005 if conn_socket.gettimeout() != 0:
1006 conn_socket.settimeout(timeout)
1007 # Deliberately outside the guard above. The parser caches this value
1008 # to restore after a per-call timeout override, so while a can_read
1009 # probe holds the socket at 0 the cache *is* the pending restore
1010 # value: writing it is how the new timeout gets armed without
1011 # flipping the socket back to blocking mid-read. Skipping it here
1012 # instead would let the probe restore the pre-relaxation timeout and
1013 # lose a maintenance relaxation for the life of the connection.
1014 self.update_parser_timeout(timeout)
1016 def update_parser_timeout(self, timeout: Optional[float] = None):
1017 parser = self._get_parser()
1018 if parser and parser._buffer:
1019 # Both parsers cache this value to restore after a per-call timeout
1020 # override, so both must receive exactly what was armed on the
1021 # socket - including None, which means "block indefinitely".
1022 if isinstance(parser, _RESP3Parser):
1023 parser._buffer.socket_timeout = timeout
1024 elif isinstance(parser, _HiredisParser):
1025 parser._socket_timeout = timeout
1027 def set_tmp_settings(
1028 self,
1029 tmp_host_address: Optional[Union[str, object]] = SENTINEL,
1030 tmp_relaxed_timeout: Optional[float] = -1,
1031 ):
1032 """
1033 SENTINEL keeps the host unchanged. -1 keeps the relaxed timeout unchanged.
1034 """
1035 if tmp_host_address and tmp_host_address != SENTINEL:
1036 self.host = str(tmp_host_address)
1037 if tmp_relaxed_timeout != -1:
1038 self.socket_timeout = tmp_relaxed_timeout
1039 self.socket_connect_timeout = tmp_relaxed_timeout
1041 def reset_tmp_settings(
1042 self,
1043 reset_host_address: bool = False,
1044 reset_relaxed_timeout: bool = False,
1045 ):
1046 if reset_host_address:
1047 self.host = self.orig_host_address
1048 if reset_relaxed_timeout:
1049 self.socket_timeout = self.orig_socket_timeout
1050 self.socket_connect_timeout = self.orig_socket_connect_timeout
1053class AbstractConnection(MaintNotificationsAbstractConnection, ConnectionInterface):
1054 "Manages communication to and from a Redis server"
1056 @deprecated_args(
1057 args_to_warn=["lib_name", "lib_version"],
1058 reason="Use 'driver_info' parameter instead. "
1059 "lib_name and lib_version will be removed in a future version.",
1060 )
1061 def __init__(
1062 self,
1063 db: int = 0,
1064 password: Optional[str] = None,
1065 socket_timeout: Optional[float] = DEFAULT_SOCKET_TIMEOUT,
1066 socket_connect_timeout: Optional[float] = DEFAULT_SOCKET_CONNECT_TIMEOUT,
1067 retry_on_timeout: bool = False,
1068 retry_on_error: Union[Iterable[Type[Exception]], object] = SENTINEL,
1069 encoding: str = "utf-8",
1070 encoding_errors: str = "strict",
1071 decode_responses: bool = False,
1072 parser_class=DefaultParser,
1073 socket_read_size: int = DEFAULT_SOCKET_READ_SIZE,
1074 health_check_interval: int = 0,
1075 client_name: Optional[str] = None,
1076 lib_name: Union[Optional[str], object] = SENTINEL,
1077 lib_version: Union[Optional[str], object] = SENTINEL,
1078 driver_info: Union[Optional[DriverInfo], object] = SENTINEL,
1079 username: Optional[str] = None,
1080 retry: Union[Any, None] = None,
1081 redis_connect_func: Optional[Callable[[], None]] = None,
1082 credential_provider: Optional[CredentialProvider] = None,
1083 protocol: Optional[int] = None,
1084 legacy_responses: bool = True,
1085 command_packer: Optional[Callable[[], None]] = None,
1086 event_dispatcher: Optional[EventDispatcher] = None,
1087 maint_notifications_config: Optional[MaintNotificationsConfig] = None,
1088 maint_notifications_pool_handler: Optional[
1089 MaintNotificationsPoolHandler
1090 ] = None,
1091 maintenance_state: "MaintenanceState" = MaintenanceState.NONE,
1092 maintenance_notification_hash: Optional[int] = None,
1093 orig_host_address: Optional[str] = None,
1094 orig_socket_timeout: Optional[float] = None,
1095 orig_socket_connect_timeout: Optional[float] = None,
1096 oss_cluster_maint_notifications_handler: Optional[
1097 OSSMaintNotificationsHandler
1098 ] = None,
1099 himport_registry: HImportRegistry | None = None,
1100 ):
1101 """
1102 Initialize a new Connection.
1104 To specify a retry policy for specific errors, first set
1105 `retry_on_error` to a list of the error/s to retry on, then set
1106 `retry` to a valid `Retry` object.
1107 To retry on TimeoutError, `retry_on_timeout` can also be set to `True`.
1109 Parameters
1110 ----------
1111 driver_info : DriverInfo, optional
1112 Driver metadata for CLIENT SETINFO. If provided, lib_name and lib_version
1113 are ignored. If not provided, a DriverInfo will be created from lib_name
1114 and lib_version. Explicit None disables CLIENT SETINFO.
1115 lib_name : str, optional
1116 **Deprecated.** Use driver_info instead. Library name for CLIENT SETINFO.
1117 lib_version : str, optional
1118 **Deprecated.** Use driver_info instead. Library version for CLIENT SETINFO.
1119 """
1120 if (username or password) and credential_provider is not None:
1121 raise DataError(
1122 "'username' and 'password' cannot be passed along with 'credential_"
1123 "provider'. Please provide only one of the following arguments: \n"
1124 "1. 'password' and (optional) 'username'\n"
1125 "2. 'credential_provider'"
1126 )
1127 if event_dispatcher is None:
1128 self._event_dispatcher = EventDispatcher()
1129 else:
1130 self._event_dispatcher = event_dispatcher
1131 self.pid = os.getpid()
1132 self.db = db
1133 self.client_name = client_name
1135 # Handle driver_info: if provided, use it; otherwise create from lib_name/lib_version.
1136 self.driver_info = resolve_driver_info(driver_info, lib_name, lib_version)
1138 self.credential_provider = credential_provider
1139 self.password = password
1140 self.username = username
1141 self._socket_timeout = socket_timeout
1142 if socket_connect_timeout is None:
1143 socket_connect_timeout = socket_timeout
1144 self._socket_connect_timeout = socket_connect_timeout
1145 self.retry_on_timeout = retry_on_timeout
1146 if retry_on_error is SENTINEL:
1147 retry_on_errors_list = []
1148 else:
1149 retry_on_errors_list = list(retry_on_error)
1150 if retry_on_timeout:
1151 # Add TimeoutError to the errors list to retry on
1152 retry_on_errors_list.append(TimeoutError)
1153 self.retry_on_error = retry_on_errors_list
1154 if retry or self.retry_on_error:
1155 if retry is None:
1156 self.retry = Retry(NoBackoff(), 1)
1157 else:
1158 # deep-copy the Retry object as it is mutable
1159 self.retry = copy.deepcopy(retry)
1160 if self.retry_on_error:
1161 # Update the retry's supported errors with the specified errors
1162 self.retry.update_supported_errors(self.retry_on_error)
1163 else:
1164 self.retry = Retry(NoBackoff(), 0)
1165 self.health_check_interval = health_check_interval
1166 self.next_health_check = 0
1167 self.redis_connect_func = redis_connect_func
1168 self.encoder = Encoder(encoding, encoding_errors, decode_responses)
1169 self.handshake_metadata = None
1170 self._resp2_fallback = False
1171 self._client_side_caching = False
1172 self._sock = None
1173 self._socket_read_size = socket_read_size
1174 self._connect_callbacks = []
1175 self._buffer_cutoff = 6000
1176 self._re_auth_token: Optional[TokenInterface] = None
1177 try:
1178 p = int(protocol)
1179 self._protocol_specified_explicitly = True
1180 except TypeError:
1181 p = DEFAULT_RESP_VERSION
1182 self._protocol_specified_explicitly = False
1183 except ValueError:
1184 raise ConnectionError("protocol must be an integer")
1185 else:
1186 if p < 2 or p > 3:
1187 raise ConnectionError("protocol must be either 2 or 3")
1188 self.protocol = p
1189 self.legacy_responses = legacy_responses
1190 if self.protocol == 3 and parser_class == _RESP2Parser:
1191 # If the protocol is 3 but the parser is RESP2, change it to RESP3
1192 # This is needed because the parser might be set before the protocol
1193 # or might be provided as a kwarg to the constructor
1194 # We need to react on discrepancy only for RESP2 and RESP3
1195 # as hiredis supports both
1196 parser_class = _RESP3Parser
1197 self.set_parser(parser_class)
1199 self._command_packer = self._construct_command_packer(command_packer)
1200 self._should_reconnect = False
1202 # HIMPORT client-side state. `himport_registry` is the shared client-level
1203 # registry (empty if unconfigured) and persists across reconnects.
1204 self.himport_registry = himport_registry
1205 self._reset_himport_state()
1207 # Set up maintenance notifications
1208 MaintNotificationsAbstractConnection.__init__(
1209 self,
1210 maint_notifications_config,
1211 maint_notifications_pool_handler,
1212 maintenance_state,
1213 maintenance_notification_hash,
1214 orig_host_address,
1215 orig_socket_timeout,
1216 orig_socket_connect_timeout,
1217 oss_cluster_maint_notifications_handler,
1218 self._parser,
1219 event_dispatcher=self._event_dispatcher,
1220 )
1222 def __repr__(self):
1223 repr_args = ",".join([f"{k}={v}" for k, v in self.repr_pieces()])
1224 return f"<{self.__class__.__module__}.{self.__class__.__name__}({repr_args})>"
1226 @abstractmethod
1227 def repr_pieces(self):
1228 pass
1230 def __del__(self):
1231 try:
1232 self.disconnect()
1233 except Exception:
1234 pass
1236 @property
1237 def is_connected(self) -> bool:
1238 return self._sock is not None
1240 def _construct_command_packer(self, packer):
1241 if packer is not None:
1242 return packer
1243 elif HIREDIS_AVAILABLE:
1244 fallback = PythonRespSerializer(self._buffer_cutoff, self.encoder.encode)
1245 return HiredisRespSerializer(fallback.pack, self.encoder.encode)
1246 else:
1247 return PythonRespSerializer(self._buffer_cutoff, self.encoder.encode)
1249 def register_connect_callback(self, callback):
1250 """
1251 Register a callback to be called when the connection is established either
1252 initially or reconnected. This allows listeners to issue commands that
1253 are ephemeral to the connection, for example pub/sub subscription or
1254 key tracking. The callback must be a _method_ and will be kept as
1255 a weak reference.
1256 """
1257 wm = weakref.WeakMethod(callback)
1258 if wm not in self._connect_callbacks:
1259 self._connect_callbacks.append(wm)
1261 def deregister_connect_callback(self, callback):
1262 """
1263 De-register a previously registered callback. It will no-longer receive
1264 notifications on connection events. Calling this is not required when the
1265 listener goes away, since the callbacks are kept as weak methods.
1266 """
1267 try:
1268 self._connect_callbacks.remove(weakref.WeakMethod(callback))
1269 except ValueError:
1270 pass
1272 def set_parser(self, parser_class):
1273 """
1274 Creates a new instance of parser_class with socket size:
1275 _socket_read_size and assigns it to the parser for the connection
1276 :param parser_class: The required parser class
1277 """
1278 self._parser = parser_class(socket_read_size=self._socket_read_size)
1280 def _get_parser(self) -> Union[_HiredisParser, _RESP3Parser, _RESP2Parser]:
1281 return self._parser
1283 def connect(self):
1284 "Connects to the Redis server if not already connected"
1285 # try once the socket connect with the handshake, retry the whole
1286 # connect/handshake flow based on retry policy
1287 self.retry.call_with_retry(
1288 lambda: self.connect_check_health(
1289 check_health=True, retry_socket_connect=False
1290 ),
1291 lambda error: self.disconnect(error),
1292 )
1294 def connect_check_health(
1295 self, check_health: bool = True, retry_socket_connect: bool = True
1296 ):
1297 if self._sock:
1298 return
1299 # Track actual retry attempts for error reporting
1300 actual_retry_attempts = [0]
1302 def failure_callback(error, failure_count):
1303 actual_retry_attempts[0] = failure_count
1304 self.disconnect(error=error, failure_count=failure_count)
1306 try:
1307 if retry_socket_connect:
1308 sock = self.retry.call_with_retry(
1309 self._connect,
1310 failure_callback,
1311 with_failure_count=True,
1312 )
1313 else:
1314 sock = self._connect()
1315 except socket.timeout:
1316 e = TimeoutError("Timeout connecting to server")
1317 record_error_count(
1318 server_address=self.host,
1319 server_port=self.port,
1320 network_peer_address=self.host,
1321 network_peer_port=self.port,
1322 error_type=e,
1323 retry_attempts=actual_retry_attempts[0],
1324 )
1325 raise e
1326 except OSError as e:
1327 conn_error = ConnectionError(self._error_message(e))
1328 record_error_count(
1329 server_address=getattr(self, "host", None),
1330 server_port=getattr(self, "port", None),
1331 network_peer_address=getattr(self, "host", None),
1332 network_peer_port=getattr(self, "port", None),
1333 error_type=conn_error,
1334 retry_attempts=actual_retry_attempts[0],
1335 )
1336 # Preserve the original OSError (with its errno) as the cause so
1337 # the retry policy can tell unrecoverable failures apart. Clear the
1338 # local afterwards so its traceback does not form a reference cycle
1339 # with this frame.
1340 try:
1341 raise conn_error from e
1342 finally:
1343 conn_error = None
1345 self._sock = sock
1346 # A new socket authenticates in the handshake below with current
1347 # credentials, which replaces any AUTH deferred on the old one
1348 self._re_auth_token = None
1349 try:
1350 if self.redis_connect_func is None:
1351 # Use the default on_connect function
1352 self.on_connect_check_health(check_health=check_health)
1353 else:
1354 # Use the passed function redis_connect_func
1355 self.redis_connect_func(self)
1356 except BaseException:
1357 # clean up after any error in on_connect, which includes whatever a
1358 # credential provider raises. A socket left in place reads as
1359 # connected, so the next command would run without AUTH and SELECT.
1360 self.disconnect()
1361 raise
1363 # run any user callbacks. right now the only internal callback
1364 # is for pubsub channel/pattern resubscription
1365 # first, remove any dead weakrefs
1366 self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()]
1367 for ref in self._connect_callbacks:
1368 callback = ref()
1369 if callback:
1370 callback(self)
1372 @abstractmethod
1373 def _connect(self):
1374 pass
1376 @abstractmethod
1377 def _host_error(self):
1378 pass
1380 def _error_message(self, exception):
1381 return format_error_message(self._host_error(), exception)
1383 def _reset_himport_state(self):
1384 # A fresh server session has no prepared HIMPORT fieldsets, so the next
1385 # himport_set must re-prepare on this connection. ``_himport_prepared`` maps
1386 # fieldset name -> the version prepared on the server; ``_himport_reconciled
1387 # _revision`` is the registry revision this connection last reconciled discards
1388 # against. Both are reset on connect/disconnect since the session is gone.
1389 self._himport_prepared: dict[str, int] = {}
1390 self._himport_reconciled_revision: int = 0
1392 def on_connect(self):
1393 self.on_connect_check_health(check_health=True)
1395 def _do_resp2_auth(self, auth_args) -> None:
1396 """Authenticate with the original credentials, retrying pre-6.0 AUTH."""
1397 # avoid checking health here -- PING will fail if we try
1398 # to check the health prior to the AUTH
1399 self.send_command("AUTH", *auth_args, check_health=False)
1400 try:
1401 auth_response = self.read_response()
1402 except AuthenticationWrongNumberOfArgsError:
1403 # a username and password were specified but the Redis
1404 # server seems to be < 6.0.0 which expects a single password
1405 # arg. retry auth with just the password.
1406 self.send_command("AUTH", auth_args[-1], check_health=False)
1407 auth_response = self.read_response()
1409 if str_if_bytes(auth_response) != "OK":
1410 raise AuthenticationError("Invalid Username or Password")
1412 def _fallback_to_resp2(self, error: ResponseError, parser, auth_args=None) -> None:
1413 """Handle HELLO failure by falling back to RESP2.
1415 Validates the error is a recoverable "unknown command" or "NOPROTO",
1416 checks that fallback is allowed (not explicitly configured, no
1417 RESP3-dependent features active), downgrades parser and protocol,
1418 emits a warning, and optionally re-authenticates via standalone AUTH.
1420 Args:
1421 error: The ResponseError from the failed HELLO command.
1422 parser: The original parser (for preserving EXCEPTION_CLASSES).
1423 auth_args: Original credentials to authenticate after downgrade.
1425 Raises:
1426 ResponseError: If the error is not recoverable or fallback
1427 is not permitted.
1428 """
1429 err_msg = str(error).lower().removeprefix("err ")
1430 if not (
1431 err_msg in ("unknown command", "noproto")
1432 or err_msg.startswith(("unknown command ", "noproto "))
1433 ):
1434 raise error
1435 if self._protocol_specified_explicitly or (
1436 self.maint_notifications_config
1437 and self.maint_notifications_config.enabled is True
1438 ):
1439 raise error
1440 if self._client_side_caching:
1441 raise ResponseError(
1442 "Client-side caching requires RESP3; cannot fall back to RESP2"
1443 ) from error
1444 logger.warning(
1445 "Server/proxy at %s does not support HELLO (RESP%s). "
1446 "Falling back to RESP2. To silence this warning, "
1447 "set protocol=2 explicitly or upgrade your "
1448 "server/proxy. Module commands (JSON, Search, TimeSeries, Bloom, "
1449 "vector sets) do not adapt their response parsers after automatic "
1450 "fallback; set protocol=2 explicitly before using them.",
1451 self._host_error(),
1452 self.protocol,
1453 )
1454 if isinstance(self._parser, _RESP3Parser):
1455 self.set_parser(_RESP2Parser)
1456 self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
1457 self._parser.on_connect(self)
1458 self.protocol = 2
1459 self._resp2_fallback = True
1460 self.handshake_metadata = {}
1461 self._oss_cluster_maint_notifications_handler = None
1462 self._maint_notifications_pool_handler = None
1463 self._maint_notifications_connection_handler = None
1464 if auth_args:
1465 self._do_resp2_auth(auth_args)
1467 def on_connect_check_health(self, check_health: bool = True):
1468 "Initialize the connection, authenticate and select a database"
1469 # A fresh socket is a new server session: no prepared HIMPORT fieldsets.
1470 self._reset_himport_state()
1471 self._parser.on_connect(self)
1472 parser = self._parser
1474 auth_args = None
1475 # if credential provider or username and/or password are set, authenticate
1476 if self.credential_provider or (self.username or self.password):
1477 cred_provider = (
1478 self.credential_provider
1479 or UsernamePasswordCredentialProvider(self.username, self.password)
1480 )
1481 auth_args = cred_provider.get_credentials()
1483 # if resp version is specified and we have auth args,
1484 # we need to send them via HELLO
1485 if auth_args and check_protocol_version(self.protocol, 3):
1486 if isinstance(self._parser, _RESP2Parser):
1487 self.set_parser(_RESP3Parser)
1488 # update cluster exception classes
1489 self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
1490 self._parser.on_connect(self)
1491 hello_auth_args = auth_args
1492 if len(auth_args) == 1:
1493 hello_auth_args = ("default", auth_args[0])
1494 # avoid checking health here -- PING will fail if we try
1495 # to check the health prior to the AUTH
1496 self.send_command(
1497 "HELLO", self.protocol, "AUTH", *hello_auth_args, check_health=False
1498 )
1499 try:
1500 self.handshake_metadata = self.read_response()
1501 if (
1502 self.handshake_metadata.get(b"proto") != self.protocol
1503 and self.handshake_metadata.get("proto") != self.protocol
1504 ):
1505 raise ConnectionError("Invalid RESP version")
1506 except ResponseError as e:
1507 self._fallback_to_resp2(e, parser, auth_args=auth_args)
1508 elif auth_args:
1509 self._do_resp2_auth(auth_args)
1511 # if resp version is specified, switch to it
1512 elif check_protocol_version(self.protocol, 3):
1513 if isinstance(self._parser, _RESP2Parser):
1514 self.set_parser(_RESP3Parser)
1515 # update cluster exception classes
1516 self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
1517 self._parser.on_connect(self)
1518 self.send_command("HELLO", self.protocol, check_health=check_health)
1519 try:
1520 self.handshake_metadata = self.read_response()
1521 if (
1522 self.handshake_metadata.get(b"proto") != self.protocol
1523 and self.handshake_metadata.get("proto") != self.protocol
1524 ):
1525 raise ConnectionError("Invalid RESP version")
1526 except ResponseError as e:
1527 self._fallback_to_resp2(e, parser)
1529 # The tail of the handshake (optional CLIENT MAINT_NOTIFICATIONS, then
1530 # CLIENT SETNAME / SETINFO / SELECT) does not affect control flow -- the replies
1531 # are only validated or discarded. So we optimize the flow: send every command
1532 # first (without blocking on a reply between them), then read the replies back in
1533 # send order. All requests are on the wire before we block on the first read, so
1534 # the whole tail costs a single round-trip instead of one per command. AUTH/HELLO
1535 # stays a separate round-trip above because its reply drives the RESP2->RESP3
1536 # parser upgrade, the pre-6.0 AUTH retry, and proto validation.
1537 #
1538 # deferred_reads holds one zero-arg handler per command sent below; each reads
1539 # exactly one reply (in send order) and validates it. Per-command check_health
1540 # reproduces the original behavior: at most one health PING/PONG fires before the
1541 # first tail command (only when no HELLO/AUTH ran, e.g. RESP2 no-auth), and it is
1542 # self-contained so it never desyncs the deferred replies.
1543 #
1544 # TODO: apply the same optimization to the async handshake in
1545 # redis/asyncio/connection.py, where not all tail commands are handled this way
1546 # yet (e.g. maintenance notifications are still issued separately there).
1547 deferred_reads = []
1549 # Maintenance notifications (RESP3-only, opt-in) go first when enabled, so their
1550 # reply is read together with the rest of the tail.
1551 self._add_maint_notifications_to_handshake(deferred_reads, check_health)
1553 # if a client_name is given, set it
1554 if self.client_name:
1555 self.send_command(
1556 "CLIENT", "SETNAME", self.client_name, check_health=check_health
1557 )
1558 deferred_reads.append(
1559 functools.partial(self._read_ok_or_raise, "Error setting client name")
1560 )
1562 # Set the library name and version from driver_info. Older servers may not
1563 # support CLIENT SETINFO, so any ResponseError to these replies is swallowed.
1564 if self.driver_info and self.driver_info.formatted_name:
1565 self.send_command(
1566 "CLIENT",
1567 "SETINFO",
1568 "LIB-NAME",
1569 self.driver_info.formatted_name,
1570 check_health=check_health,
1571 )
1572 deferred_reads.append(self._read_optional_setinfo)
1574 if self.driver_info and self.driver_info.lib_version:
1575 self.send_command(
1576 "CLIENT",
1577 "SETINFO",
1578 "LIB-VER",
1579 self.driver_info.lib_version,
1580 check_health=check_health,
1581 )
1582 deferred_reads.append(self._read_optional_setinfo)
1584 # if a database is specified, switch to it
1585 if self.db:
1586 self.send_command("SELECT", self.db, check_health=check_health)
1587 deferred_reads.append(
1588 functools.partial(self._read_ok_or_raise, "Invalid Database")
1589 )
1591 # Read the deferred replies in the order the commands were sent.
1592 for read_and_validate_response in deferred_reads:
1593 read_and_validate_response()
1595 def disconnect(self, *args, **kwargs):
1596 "Disconnects from the Redis server"
1597 # The server session is gone, so any HIMPORT fieldsets prepared on this
1598 # socket no longer exist; reset the tracking.
1599 self._reset_himport_state()
1600 # Likewise the relaxation a maintenance applied to it: restored and
1601 # reported here, ahead of a close that may find no socket to close
1602 self._complete_maintenance_on_disconnect()
1603 self._parser.on_disconnect()
1605 conn_sock = self._sock
1606 self._sock = None
1607 # reset the reconnect flag
1608 self.reset_should_reconnect()
1610 if conn_sock is None:
1611 return
1613 if os.getpid() == self.pid:
1614 try:
1615 conn_sock.shutdown(socket.SHUT_RDWR)
1616 except (OSError, TypeError):
1617 pass
1619 try:
1620 conn_sock.close()
1621 except OSError:
1622 pass
1624 error = kwargs.get("error")
1625 failure_count = kwargs.get("failure_count")
1626 health_check_failed = kwargs.get("health_check_failed")
1628 if error:
1629 if health_check_failed:
1630 close_reason = CloseReason.HEALTHCHECK_FAILED
1631 else:
1632 close_reason = CloseReason.ERROR
1634 if failure_count is not None and failure_count > self.retry.get_retries():
1635 record_error_count(
1636 server_address=self.host,
1637 server_port=self.port,
1638 network_peer_address=self.host,
1639 network_peer_port=self.port,
1640 error_type=error,
1641 retry_attempts=failure_count,
1642 )
1644 record_connection_closed(
1645 close_reason=close_reason,
1646 error_type=error,
1647 )
1648 else:
1649 record_connection_closed(
1650 close_reason=CloseReason.APPLICATION_CLOSE,
1651 )
1653 def mark_for_reconnect(self):
1654 self._should_reconnect = True
1656 def should_reconnect(self):
1657 return self._should_reconnect
1659 def reset_should_reconnect(self):
1660 self._should_reconnect = False
1662 def _send_ping(self):
1663 """Send PING, expect PONG in return"""
1664 self.send_command("PING", check_health=False)
1665 if str_if_bytes(self.read_response()) != "PONG":
1666 raise ConnectionError("Bad response from PING health check")
1668 def _ping_failed(self, error, failure_count):
1669 """Function to call when PING fails"""
1670 self.disconnect(
1671 error=error, failure_count=failure_count, health_check_failed=True
1672 )
1674 def check_health(self):
1675 """Check the health of the connection with a PING/PONG"""
1676 if self.health_check_interval and time.monotonic() > self.next_health_check:
1677 self.retry.call_with_retry(
1678 self._send_ping,
1679 self._ping_failed,
1680 with_failure_count=True,
1681 )
1683 def send_packed_command(self, command, check_health=True):
1684 """Send an already packed command to the Redis server"""
1685 if not self._sock:
1686 self.connect_check_health(check_health=False)
1687 # guard against health check recursion
1688 if check_health:
1689 self.check_health()
1690 try:
1691 if isinstance(command, str):
1692 command = [command]
1693 for item in command:
1694 self._sock.sendall(item)
1695 except socket.timeout as e:
1696 add_debug_log_for_connection_failure(self, e, "writing command")
1697 self.disconnect()
1698 if is_os_level_timeout(e):
1699 # ETIMEDOUT from the OS: the connection is dead, not slow.
1700 raise ConnectionError(
1701 f"Error {e.errno} while writing to socket. {e.strerror}."
1702 ) from e
1703 raise TimeoutError("Timeout writing to socket")
1704 except OSError as e:
1705 add_debug_log_for_connection_failure(self, e, "writing command")
1706 self.disconnect()
1707 if len(e.args) == 1:
1708 errno, errmsg = "UNKNOWN", e.args[0]
1709 else:
1710 errno = e.args[0]
1711 errmsg = e.args[1]
1712 raise ConnectionError(
1713 f"Error {errno} while writing to socket. {errmsg}."
1714 ) from e
1715 except BaseException as e:
1716 # BaseExceptions can be raised when a socket send operation is not
1717 # finished, e.g. due to a timeout. Ideally, a caller could then re-try
1718 # to send un-sent data. However, the send_packed_command() API
1719 # does not support it so there is no point in keeping the connection open.
1720 add_debug_log_for_connection_failure(self, e, "writing command")
1721 self.disconnect()
1722 raise
1724 def send_command(self, *args, **kwargs):
1725 """Pack and send a command to the Redis server"""
1726 self.send_packed_command(
1727 self._command_packer.pack(*args),
1728 check_health=kwargs.get("check_health", True),
1729 )
1731 def can_read(self, timeout: float = 0) -> bool:
1732 """Poll the socket to see if there's data that can be read."""
1733 # TODO: Rename this API; it detects pending data or dirty/closed
1734 # connection state, not only whether application data can be read.
1735 sock = self._sock
1736 if not sock:
1737 self.connect()
1739 host_error = self._host_error()
1741 try:
1742 return self._parser.can_read(timeout)
1744 except OSError as e:
1745 self.disconnect()
1746 raise ConnectionError(
1747 f"Error while reading from {host_error}: {e.args}"
1748 ) from e
1750 def read_response(
1751 self,
1752 disable_decoding=False,
1753 *,
1754 timeout: Union[float, object] = SENTINEL,
1755 disconnect_on_error=True,
1756 push_request=False,
1757 ):
1758 """Read the response from a previously sent command"""
1760 host_error = self._host_error()
1762 try:
1763 if self.protocol in ["3", 3]:
1764 response = self._parser.read_response(
1765 disable_decoding=disable_decoding,
1766 push_request=push_request,
1767 timeout=timeout,
1768 )
1769 else:
1770 response = self._parser.read_response(
1771 disable_decoding=disable_decoding, timeout=timeout
1772 )
1773 except socket.timeout as e:
1774 if disconnect_on_error:
1775 add_debug_log_for_connection_failure(self, e, "reading response")
1776 self.disconnect()
1777 raise TimeoutError(f"Timeout reading from {host_error}")
1778 except TimeoutError as e:
1779 # The parsers raise redis.exceptions.TimeoutError, which is not an
1780 # OSError, so without this branch it would fall through to
1781 # BaseException and keep the parser's undecorated message. Re-raise
1782 # it with the host, matching what the async stack already reports.
1783 if disconnect_on_error:
1784 add_debug_log_for_connection_failure(self, e, "reading response")
1785 self.disconnect()
1786 raise TimeoutError(f"Timeout reading from {host_error}")
1787 except OSError as e:
1788 if disconnect_on_error:
1789 add_debug_log_for_connection_failure(self, e, "reading response")
1790 self.disconnect()
1791 raise ConnectionError(
1792 f"Error while reading from {host_error} : {e.args}"
1793 ) from e
1794 except UNRECOVERABLE_PARSE_ERRORS as e:
1795 # The parser failed partway through a reply, after the read cursor
1796 # had already passed bytes it cannot re-interpret. The rewind and
1797 # disconnect_on_error=False exist so an *interrupted* read can be
1798 # re-parsed from the start (#2510, #2695) - an in-band ResponseError
1799 # is returned as a value and purged, never rewound. Re-parsing here
1800 # just reproduces the same failure, so honouring
1801 # disconnect_on_error=False would make every later read fail
1802 # identically, forever. Drop the connection regardless. See #4291.
1803 add_debug_log_for_connection_failure(self, e, "reading response")
1804 self.disconnect()
1805 raise
1806 except BaseException as e:
1807 # Also by default close in case of BaseException. A lot of code
1808 # relies on this behaviour when doing Command/Response pairs.
1809 # See #1128.
1810 if disconnect_on_error:
1811 add_debug_log_for_connection_failure(self, e, "reading response")
1812 self.disconnect()
1813 raise
1815 if self.health_check_interval:
1816 self.next_health_check = time.monotonic() + self.health_check_interval
1818 if isinstance(response, ResponseError):
1819 try:
1820 raise response
1821 finally:
1822 del response # avoid creating ref cycles
1823 return response
1825 def pack_command(self, *args):
1826 """Pack a series of arguments into the Redis protocol"""
1827 return self._command_packer.pack(*args)
1829 def pack_commands(self, commands):
1830 """Pack multiple commands into the Redis protocol"""
1831 output = []
1832 pieces = []
1833 buffer_length = 0
1834 buffer_cutoff = self._buffer_cutoff
1836 for cmd in commands:
1837 for chunk in self._command_packer.pack(*cmd):
1838 chunklen = len(chunk)
1839 if (
1840 buffer_length > buffer_cutoff
1841 or chunklen > buffer_cutoff
1842 or isinstance(chunk, memoryview)
1843 ):
1844 if pieces:
1845 output.append(SYM_EMPTY.join(pieces))
1846 buffer_length = 0
1847 pieces = []
1849 if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
1850 output.append(chunk)
1851 else:
1852 pieces.append(chunk)
1853 buffer_length += chunklen
1855 if pieces:
1856 output.append(SYM_EMPTY.join(pieces))
1857 return output
1859 def get_protocol(self) -> Union[int, str]:
1860 return self.protocol
1862 @property
1863 def handshake_metadata(self) -> Union[Dict[bytes, bytes], Dict[str, str]]:
1864 return self._handshake_metadata
1866 @handshake_metadata.setter
1867 def handshake_metadata(self, value: Union[Dict[bytes, bytes], Dict[str, str]]):
1868 self._handshake_metadata = value
1870 def set_re_auth_token(self, token: TokenInterface | None):
1871 self._re_auth_token = token
1873 def re_auth(self):
1874 """
1875 Send the pending AUTH, if any.
1877 The token stays pending until this socket accepts it, or until the
1878 connection opens a new socket, whose handshake authenticates with
1879 current credentials. A connection that is disconnected, or marked for
1880 reconnect, is skipped for that reason: the AUTH would go to a socket
1881 that is about to be replaced. A token set while the AUTH is in flight
1882 stays pending.
1883 """
1884 token = self._re_auth_token
1885 if token is None or self._sock is None or self.should_reconnect():
1886 return
1887 self.send_command("AUTH", token.try_get("oid"), token.get_value())
1888 self.read_response()
1889 if self._re_auth_token is token:
1890 self._re_auth_token = None
1892 def _get_socket(self) -> Optional[socket.socket]:
1893 return self._sock
1895 @property
1896 def socket_timeout(self) -> Optional[Union[float, int]]:
1897 return self._socket_timeout
1899 @socket_timeout.setter
1900 def socket_timeout(self, value: Optional[Union[float, int]]):
1901 self._socket_timeout = value
1903 @property
1904 def socket_connect_timeout(self) -> Optional[Union[float, int]]:
1905 return self._socket_connect_timeout
1907 @socket_connect_timeout.setter
1908 def socket_connect_timeout(self, value: Optional[Union[float, int]]):
1909 self._socket_connect_timeout = value
1911 def extract_connection_details(self) -> str:
1912 """
1913 Render the connection's identity, maintenance state and effective timeouts.
1915 This is what the debug logs use to explain a failed or timed out command:
1917 - ``host`` vs ``orig host`` says whether the connection still points at the
1918 node being moved away from, or has already been repointed at the new one.
1919 - ``state`` says whether maintenance handling touched this connection at
1920 all, so an unaffected node's connections are distinguishable.
1921 - ``socket_timeout`` vs ``active read timeout`` says which timeout the read
1922 actually ran under. They diverge for a command that was already in flight
1923 when the relaxed timeout was applied.
1924 """
1925 if self._sock is None:
1926 return "not connected"
1928 socket_address = None
1929 active_read_timeout = None
1930 try:
1931 socket_name = self._sock.getsockname()
1932 # AF_UNIX sockets report a path string rather than a (host, port) tuple
1933 if isinstance(socket_name, tuple) and len(socket_name) > 1:
1934 socket_address = socket_name[1]
1935 # The timeout armed on the socket is what a blocking read is really
1936 # using, which can lag self.socket_timeout for an in-flight command.
1937 active_read_timeout = self._sock.gettimeout()
1938 except (AttributeError, OSError):
1939 pass
1941 state = getattr(self.maintenance_state, "value", self.maintenance_state)
1942 return (
1943 f"connected to ip {self.get_resolved_ip()}, "
1944 f"local socket port: {socket_address}, "
1945 f"host: {self._host_error()} "
1946 f"(orig: {getattr(self, 'orig_host_address', None)}), "
1947 f"state: {state}, "
1948 f"socket_timeout: {self.socket_timeout} "
1949 f"(orig: {getattr(self, 'orig_socket_timeout', None)}), "
1950 f"active read timeout: {active_read_timeout}, "
1951 f"should_reconnect: {self.should_reconnect()}, "
1952 f"notification_hash: {self.maintenance_notification_hash}"
1953 )
1956class Connection(AbstractConnection):
1957 "Manages TCP communication to and from a Redis server"
1959 def __init__(
1960 self,
1961 host="localhost",
1962 port=6379,
1963 socket_keepalive=True,
1964 socket_keepalive_options=SENTINEL,
1965 socket_type=0,
1966 **kwargs,
1967 ):
1968 """
1969 Initialize a TCP connection.
1971 Parameters
1972 ----------
1973 socket_keepalive : bool
1974 If `True`, TCP keepalive is enabled for TCP socket connections.
1975 socket_keepalive_options : Mapping[int, int | bytes] | object | None
1976 Mapping of TCP keepalive socket option constants to values, for
1977 example `{socket.TCP_KEEPIDLE: 30}`. If left unspecified, redis-py
1978 uses TCP keepalive defaults when `socket_keepalive` is enabled:
1979 idle 30 seconds, interval 5 seconds, and 3 probes. Platform-specific
1980 options that are not available are skipped. Pass `None` or `{}` to
1981 avoid setting additional TCP keepalive options.
1982 """
1983 self._host = host
1984 # bool subclasses int; port=True would become privileged port 1.
1985 # Numeric strings stay valid. Callers still pass "6379".
1986 if isinstance(port, bool):
1987 raise TypeError("port must be an integer, not bool")
1988 if isinstance(port, str):
1989 try:
1990 port = int(port)
1991 except ValueError:
1992 raise TypeError("port must be an integer, not str") from None
1993 elif not isinstance(port, int):
1994 raise TypeError(f"port must be an integer, not {type(port).__name__}")
1995 if not 0 <= port <= 65535:
1996 raise ValueError(f"port must be in 0..65535, got {port}")
1997 self.port = port
1998 self.socket_keepalive = socket_keepalive
1999 if socket_keepalive_options is SENTINEL:
2000 socket_keepalive_options = get_default_socket_keepalive_options()
2001 self.socket_keepalive_options = socket_keepalive_options or {}
2002 self.socket_type = socket_type
2003 super().__init__(**kwargs)
2005 def repr_pieces(self):
2006 pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
2007 if self.client_name:
2008 pieces.append(("client_name", self.client_name))
2009 return pieces
2011 def _connect(self):
2012 "Create a TCP socket connection"
2013 # we want to mimic what socket.create_connection does to support
2014 # ipv4/ipv6, but we want to set options prior to calling
2015 # socket.connect()
2017 # Last caught connection error.
2018 # Re-thrown if we are unable to connect to any of the options returned
2019 # by getaddrinfo.
2020 # Note that we must clear this variable before returning - otherwise,
2021 # a caught err's traceback points to this frame, which points to err.
2022 # Clearing this lets refcounting reclaim the exception immediately
2023 # without deferring to the python garbage collector.
2024 err = None
2026 for res in socket.getaddrinfo(
2027 self.host, self.port, self.socket_type, socket.SOCK_STREAM
2028 ):
2029 family, socktype, proto, canonname, socket_address = res
2030 sock = None
2031 try:
2032 sock = socket.socket(family, socktype, proto)
2033 # TCP_NODELAY
2034 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
2036 # TCP_KEEPALIVE
2037 if self.socket_keepalive:
2038 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
2039 for k, v in self.socket_keepalive_options.items():
2040 sock.setsockopt(socket.IPPROTO_TCP, k, v)
2042 # set the socket_connect_timeout before we connect
2043 sock.settimeout(self.socket_connect_timeout)
2045 # connect
2046 sock.connect(socket_address)
2048 # set the socket_timeout now that we're connected
2049 sock.settimeout(self.socket_timeout)
2051 # If a previous connection attempt failed, clear the error
2052 err = None
2054 return sock
2056 except OSError as _:
2057 err = _
2058 if sock is not None:
2059 try:
2060 sock.shutdown(socket.SHUT_RDWR) # ensure a clean close
2061 except OSError:
2062 pass
2063 sock.close()
2065 if err is not None:
2066 try:
2067 raise err
2068 finally:
2069 # Ensure we clear local references to caught exceptions
2070 err = None
2071 raise OSError("socket.getaddrinfo returned an empty list")
2073 def _host_error(self):
2074 return f"{self.host}:{self.port}"
2076 @property
2077 def host(self) -> str:
2078 return self._host
2080 @host.setter
2081 def host(self, value: str):
2082 self._host = value
2085# Distinguishes "no locally-served reply is waiting" from a cached value that happens to be
2086# falsy. ``None`` cannot do the job: it is a legitimate reply shape, and the cache refuses to
2087# store it only by convention.
2088_NO_PENDING_HIT = object()
2090# A command name that does not start with one of these cannot be ``CLIENT`` or ``RESET``,
2091# so ``_cache_owned_command`` rejects nearly every command before it allocates anything.
2092_CLIENT_FIRST_CHARS = frozenset(("c", "C", b"c", b"C"))
2093_RESET_FIRST_CHARS = frozenset(("r", "R", b"r", b"R"))
2094# ``pack`` splits the command name on whitespace, so a name padded with it still reaches
2095# the server as ``CLIENT ...`` or ``RESET``. It encodes a ``str`` name before splitting,
2096# so ASCII whitespace is the only kind that splits.
2097_WHITESPACE_CHARS = frozenset(
2098 (*" \t\n\r\x0b\x0c", *(bytes((c,)) for c in b" \t\n\r\x0b\x0c"))
2099)
2101# The ``CLIENT`` subcommands the cache owns. ``TRACKINGINFO`` and ``GETREDIR`` only read the
2102# tracking state, so they are not here.
2103_CACHE_OWNED_CLIENT_SUBCOMMANDS = frozenset(("CACHING", "TRACKING"))
2106def _cache_owned_command(args) -> str | None:
2107 """
2108 The name of the command in ``args`` if it is one the cache owns - ``CLIENT CACHING``,
2109 ``CLIENT TRACKING`` or ``RESET`` - else ``None``. Matches every spelling
2110 ``pack_command`` accepts: ``"CLIENT CACHING"`` as one argument or ``"CLIENT"``,
2111 ``"CACHING"`` as two, as ``str``, ``bytes``, ``bytearray`` or ``memoryview``, in any
2112 case, padded with whitespace or not.
2113 """
2114 command = args[0]
2115 if not isinstance(command, (str, bytes)):
2116 if not isinstance(command, (bytearray, memoryview)):
2117 return None
2118 command = bytes(command)
2119 first_char = command[:1]
2120 if first_char in _RESET_FIRST_CHARS:
2121 # ``RESET`` takes no arguments, so only a five-character name, or one followed by
2122 # whitespace, can match. The check keeps the many other ``R`` commands (``RPOP``,
2123 # ``RENAME``, ...) allocation-free.
2124 if len(command) != 5 and command[5:6] not in _WHITESPACE_CHARS:
2125 return None
2126 elif first_char not in _CLIENT_FIRST_CHARS and first_char not in _WHITESPACE_CHARS:
2127 return None
2128 words = str_if_bytes(command).upper().split()
2129 if not words:
2130 return None
2131 if words[0] == "RESET":
2132 return "RESET"
2133 if words[0] != "CLIENT":
2134 return None
2135 if len(words) == 1 and len(args) > 1:
2136 subcommand = args[1]
2137 if isinstance(subcommand, (bytearray, memoryview)):
2138 subcommand = bytes(subcommand)
2139 if isinstance(subcommand, (str, bytes)):
2140 words.append(str_if_bytes(subcommand).upper())
2141 if len(words) > 1 and words[1] in _CACHE_OWNED_CLIENT_SUBCOMMANDS:
2142 return f"CLIENT {words[1]}"
2143 return None
2146_IMMUTABLE_TYPES = (bytes, str, int, float, bool, type(None))
2149def _clone_cache_value(value: Any) -> Any:
2150 # Restrict fast path to exact built-in types so subclasses with mutable
2151 # instance attributes are safely deep-copied.
2152 if type(value) in _IMMUTABLE_TYPES:
2153 return value
2154 return copy.deepcopy(value)
2157class CacheProxyConnection(MaintNotificationsAbstractConnection, ConnectionInterface):
2158 DUMMY_CACHE_VALUE = b"foo"
2159 MIN_ALLOWED_VERSION = "7.4.0"
2160 DEFAULT_SERVER_NAME = "redis"
2162 def __init__(
2163 self,
2164 conn: ConnectionInterface,
2165 cache: CacheInterface,
2166 pool_lock: threading.RLock,
2167 ):
2168 self.pid = os.getpid()
2169 self._conn = conn
2170 self._resp2_fallback = False
2171 if isinstance(conn, AbstractConnection):
2172 conn._client_side_caching = True
2173 self.retry = self._conn.retry
2174 self.host = self._conn.host
2175 # A UnixDomainSocketConnection has no port
2176 self.port = getattr(self._conn, "port", None)
2177 self.db = self._conn.db
2178 self._event_dispatcher = self._conn._event_dispatcher
2179 self.credential_provider = conn.credential_provider
2180 self._pool_lock = pool_lock
2181 self._cache = cache
2182 self._cache_lock = threading.RLock()
2183 self._current_command_cache_key = None
2184 # Read once: the configuration cannot change after the pool built the cache, and the
2185 # mode is a connection-setup property anyway - the server refuses to switch a live
2186 # connection between OPTIN and OPTOUT, so a configuration change applies to new
2187 # connections only.
2188 self._tracking_mode = cache.config.get_tracking_mode()
2189 # A CLIENT CACHING ``+OK`` is queued ahead of the next data reply.
2190 self._pending_caching_reply = False
2191 # The next command is an ASK-redirected attempt, which must not be paired.
2192 self._skip_next_caching = False
2193 # Distinguishes a reconnect from the first connect in the tracking callback.
2194 self._connected_once = False
2195 # A reply ``send_command`` resolved from the cache, waiting for ``read_response`` to
2196 # hand it back. Set means nothing was written, so there is no reply on the socket.
2197 self._pending_cache_hit = _NO_PENDING_HIT
2198 self.register_connect_callback(self._enable_tracking_callback)
2200 if isinstance(self._conn, MaintNotificationsAbstractConnection):
2201 MaintNotificationsAbstractConnection.__init__(
2202 self,
2203 self._conn.maint_notifications_config,
2204 self._conn._maint_notifications_pool_handler,
2205 self._conn.maintenance_state,
2206 self._conn.maintenance_notification_hash,
2207 self._conn.host,
2208 self._conn.socket_timeout,
2209 self._conn.socket_connect_timeout,
2210 self._conn._oss_cluster_maint_notifications_handler,
2211 self._conn._get_parser(),
2212 event_dispatcher=self._conn.event_dispatcher,
2213 )
2215 def repr_pieces(self):
2216 return self._conn.repr_pieces()
2218 @property
2219 def is_connected(self) -> bool:
2220 return self._conn.is_connected
2222 def register_connect_callback(self, callback):
2223 self._conn.register_connect_callback(callback)
2225 def deregister_connect_callback(self, callback):
2226 self._conn.deregister_connect_callback(callback)
2228 def set_parser(self, parser_class):
2229 self._conn.set_parser(parser_class)
2231 def set_maint_notifications_pool_handler_for_connection(
2232 self, maint_notifications_pool_handler
2233 ):
2234 if isinstance(self._conn, MaintNotificationsAbstractConnection):
2235 self._conn.set_maint_notifications_pool_handler_for_connection(
2236 maint_notifications_pool_handler
2237 )
2239 def set_maint_notifications_cluster_handler_for_connection(
2240 self, oss_cluster_maint_notifications_handler
2241 ):
2242 if isinstance(self._conn, MaintNotificationsAbstractConnection):
2243 self._conn.set_maint_notifications_cluster_handler_for_connection(
2244 oss_cluster_maint_notifications_handler
2245 )
2247 def get_protocol(self):
2248 return self._conn.get_protocol()
2250 def connect(self):
2251 self._conn.connect()
2253 server_name = self._conn.handshake_metadata.get(b"server", None)
2254 if server_name is None:
2255 server_name = self._conn.handshake_metadata.get("server", None)
2256 server_ver = self._conn.handshake_metadata.get(b"version", None)
2257 if server_ver is None:
2258 server_ver = self._conn.handshake_metadata.get("version", None)
2259 if server_ver is None or server_name is None:
2260 raise ConnectionError("Cannot retrieve information about server version")
2262 server_ver = ensure_string(server_ver)
2263 server_name = ensure_string(server_name)
2265 if (
2266 server_name != self.DEFAULT_SERVER_NAME
2267 or compare_versions(server_ver, self.MIN_ALLOWED_VERSION) == 1
2268 ):
2269 raise ConnectionError(
2270 "To maximize compatibility with all Redis products, client-side caching is supported by Redis 7.4 or later" # noqa: E501
2271 )
2273 def on_connect(self):
2274 self._conn.on_connect()
2276 def disconnect(self, *args, **kwargs):
2277 with self._cache_lock:
2278 self._cache.flush()
2279 # Both flags describe an exchange on the socket that is about to die with it. A stale
2280 # ``_pending_caching_reply`` would make the next ``read_response`` swallow a reply;
2281 # a stale ``_skip_next_caching`` would leak the ASK suppression onto an unrelated
2282 # later command.
2283 self._pending_caching_reply = False
2284 self._skip_next_caching = False
2285 self._pending_cache_hit = _NO_PENDING_HIT
2286 # The maintenance handlers are bound to this proxy, so the relaxation
2287 # a maintenance applied is reported with the proxy as its source
2288 if isinstance(self._conn, MaintNotificationsAbstractConnection):
2289 self._complete_maintenance_on_disconnect()
2290 self._conn.disconnect(*args, **kwargs)
2292 def check_health(self):
2293 self._conn.check_health()
2295 def send_packed_command(self, command, check_health=True):
2296 # TODO: Investigate if it's possible to unpack command
2297 # or extract keys from packed command
2298 # Pre-packed commands are not individually cacheable, so make sure the
2299 # next read_response does not try to cache their reply under a stale key.
2300 self._current_command_cache_key = None
2301 # A pre-packed write carries no CLIENT CACHING command of its own, so a flag left
2302 # over from an earlier send must not make the next read_response swallow a reply -
2303 # nor may a stale locally-served reply be handed back in place of this write's.
2304 # The server consumes a pending ASKING on this write, so the ASK suppression must
2305 # not carry over to a later command either.
2306 self._pending_caching_reply = False
2307 self._skip_next_caching = False
2308 self._pending_cache_hit = _NO_PENDING_HIT
2309 self._conn.send_packed_command(command)
2311 def send_command(self, *args, **kwargs):
2312 # Before anything else, so a refused command leaves no state behind.
2313 self._refuse_cache_owned_command(args)
2314 self._process_pending_invalidations()
2315 self._pending_caching_reply = False
2316 self._pending_cache_hit = _NO_PENDING_HIT
2318 if self._skip_next_caching:
2319 # An ASK-redirected attempt.
2320 # ``ASKING`` like ``CLIENT CACHING`` needs to be immediatelly before the next command
2321 # so we can't have both additions to the command we are sending,
2322 # and pairing here would strip the ASK allowance and the read would
2323 # be redirected again.
2324 # Cache nothing either: the reply belongs to a migrating
2325 # slot, and the attempt is tracked by default under optout anyway.
2326 self._skip_next_caching = False
2327 self._current_command_cache_key = None
2328 self._conn.send_command(*args, **kwargs)
2329 return
2331 command = args[0]
2332 if isinstance(command, str) and command.upper() == "ASKING":
2333 # The cluster executor sends ASKING as its own command on this connection right
2334 # before the redirected attempt, so observing it here is all the notice needed -
2335 # no kwarg threading, and the flag mirrors the server's own one-shot semantics.
2336 self._skip_next_caching = True
2338 # Eligibility, keyability and intent are three separate questions, and all three must
2339 # be answered yes before a reply may be stored. The command metadata answers the
2340 # first; the presence of ``keys`` answers the second, because a command's key
2341 # positions are supplied by its command method rather than derived here. A cacheable
2342 # command whose invocation carries no key list is therefore a gap in what this client
2343 # has been taught, not an error: send it normally and cache nothing. The configured
2344 # tracking mode and predicate answer the third.
2345 keys = kwargs.get("keys")
2346 store = False
2348 if keys is not None:
2349 # Materialized once: ``keys`` may be a one-shot iterable, and it is read again
2350 # below to build the ``CacheKey`` the reverse index is keyed by.
2351 keys = tuple(keys)
2353 # An empty key list - ``mget([])``, ``exists()`` - is treated as no key list: there
2354 # is nothing to track, and the predicate is promised never to see an empty tuple.
2355 if keys:
2356 with self._cache_lock:
2357 # Eligibility is asked with a throwaway empty-keys ``CacheKey`` because
2358 # ``DefaultCache.is_cachable`` looks only at ``key.command``.
2359 eligible = self._cache.is_cachable(
2360 CacheKey(command=command, redis_keys=(), redis_args=())
2361 )
2363 # Intent is asked separately, after the real keys are known, and outside the
2364 # cache lock: it invokes application code and touches no cache state. Folding it
2365 # into ``is_cachable`` would also invoke it from ``DefaultCache.set`` and from
2366 # the eligibility probe above, both with an empty key tuple.
2367 store = eligible and self._cache.config.should_cache(command, keys)
2369 if not store:
2370 self._current_command_cache_key = None
2372 # One path for keyless and ineligible commands alike, so an eligible read whose
2373 # command method never plumbed ``keys=`` still gets its optout ``NO``. That is the
2374 # correct direction: the server tracks it regardless, and we will not store it.
2375 #
2376 # Trackability is asked only here, and never affects storage. A ``NO`` in front of
2377 # a command the server would not track - a write, a keyless read - is consumed
2378 # with no effect, so the only cost of getting it wrong is a wasted command; the
2379 # check fails closed, which skips the ``NO`` rather than risking a stored reply.
2380 if self._tracking_mode is TrackingMode.OPTOUT and (
2381 self._cache.config.is_trackable_read(command)
2382 ):
2383 self._send_with_caching(b"NO", args, kwargs)
2384 else:
2385 self._conn.send_command(*args, **kwargs)
2386 return
2388 # Creates cache key. An invalidation names a key by the bytes it was sent as,
2389 # which ``DefaultCache.delete_by_redis_keys`` matches to a ``str`` or ``bytes``
2390 # key but never to a number, so a numeric key is indexed by its encoded form.
2391 redis_keys = keys
2392 for key in keys:
2393 if isinstance(key, (int, float)):
2394 encode = self._conn.encoder.encode
2395 redis_keys = tuple(
2396 encode(k) if isinstance(k, (int, float)) else k for k in keys
2397 )
2398 break
2399 # A float argument compares equal to an int or to the other signed zero
2400 # (1 == 1.0, 0.0 == -0.0) but is sent as different bytes, so it is keyed by
2401 # its encoded form, or HGET h 1.0 would be served the entry of HGET h 1.
2402 redis_args = args
2403 for arg in args:
2404 if isinstance(arg, float):
2405 encode = self._conn.encoder.encode
2406 redis_args = tuple(
2407 encode(a) if isinstance(a, float) else a for a in args
2408 )
2409 break
2410 self._current_command_cache_key = CacheKey(
2411 command=command, redis_keys=redis_keys, redis_args=redis_args
2412 )
2414 is_hit = False
2415 with self._cache_lock:
2416 candidate = self._cache.get(self._current_command_cache_key)
2417 if candidate is None or candidate.status == CacheEntryStatus.IN_PROGRESS:
2418 # Commit to a miss even if another connection subsequently promotes
2419 # the old placeholder, and never drain an IN_PROGRESS entry's owner:
2420 # its socket may still hold the reply to its outstanding command, and
2421 # the drain (which returns non-push replies too) would consume it.
2422 # Setting the placeholder here keeps the miss on a single lock section.
2423 candidate = None
2424 # Set temporary entry value to prevent
2425 # race condition from another connection.
2426 self._cache.set(
2427 CacheEntry(
2428 cache_key=self._current_command_cache_key,
2429 cache_value=self.DUMMY_CACHE_VALUE,
2430 status=CacheEntryStatus.IN_PROGRESS,
2431 connection_ref=self._conn,
2432 )
2433 )
2435 if candidate is not None:
2436 # Drain the connection that cached the entry so invalidations do not
2437 # accumulate on idle connections. This must run outside our cache lock: the
2438 # drain takes the pool lock, and invalidations call the owner's callback
2439 # under its cache lock. Holding ours would order a cache lock before the
2440 # pool lock and another after it, deadlocking connections draining each
2441 # other or a pool.disconnect() holding the pool lock while waiting for ours.
2442 with self._pool_lock:
2443 self._drain_invalidations(candidate.connection_ref)
2445 with self._cache_lock:
2446 # Re-check: the drained entry may have been invalidated or replaced.
2447 entry = self._cache.get(self._current_command_cache_key)
2449 # A hit requires this very entry object to have been drained. A
2450 # replacement filled during the drain may belong to another connection
2451 # with pending invalidations and is not trusted, even if it is VALID by
2452 # the time we check here.
2453 #
2454 # Whether this read is served locally is decided here, once, and the
2455 # value is carried to ``read_response`` - which must not re-derive it
2456 # from cache state. Two things can happen to the entry between the two
2457 # calls, and re-deriving desynchronises the connection under both:
2458 #
2459 # - another connection resolves this very entry object and flips it to
2460 # VALID with *its* reply, so a re-derived check would serve that value
2461 # and never read the reply we did send;
2462 # - an invalidation removes it, so a re-derived check would find nothing
2463 # and read a reply for a command we never sent.
2464 if entry is candidate:
2465 cached_value = entry.cache_value
2466 self._current_command_cache_key = None
2467 is_hit = True
2468 else:
2469 # Replace the lost candidate with our own placeholder.
2470 self._cache.set(
2471 CacheEntry(
2472 cache_key=self._current_command_cache_key,
2473 cache_value=self.DUMMY_CACHE_VALUE,
2474 status=CacheEntryStatus.IN_PROGRESS,
2475 connection_ref=self._conn,
2476 )
2477 )
2479 if is_hit:
2480 self._pending_cache_hit = _clone_cache_value(cached_value)
2481 return
2483 # Send command over socket only if it's allowed
2484 # read-only command that not yet cached. Under optin the server remembers nothing
2485 # unless ``CLIENT CACHING YES`` comes right before the read, so this - the one place
2486 # that decided to store the reply - is where the pair is sent. Under plain and optout
2487 # the read is tracked by default and goes out alone.
2488 if self._tracking_mode is TrackingMode.OPTIN:
2489 self._send_with_caching(b"YES", args, kwargs)
2490 else:
2491 self._conn.send_command(*args, **kwargs)
2493 def _send_with_caching(self, decision: bytes, args, kwargs) -> None:
2494 """
2495 Write ``CLIENT CACHING YES|NO`` and its read to the socket as one write.
2497 One write is the entire pairing guarantee: the server consumes the CACHING flag on the
2498 next command that is not a ``CLIENT`` subcommand, so anything the library slipped in
2499 between would take the flag instead of the read - under optin leaving the read
2500 untracked, under optout exempting the wrong command. Health-checking is left to
2501 ``send_packed_command``, which PINGs before it writes anything, so the PING cannot
2502 land inside the pair.
2504 Calls the wrapped connection's ``send_packed_command`` rather than this class's own
2505 override, which clears ``_current_command_cache_key`` and would discard the
2506 IN_PROGRESS placeholder the caller just set.
2508 Args:
2509 decision: ``b"YES"`` under optin, ``b"NO"`` under optout.
2510 args: The paired command, as ``send_command`` received it.
2511 kwargs: The paired command's keyword arguments, read for ``check_health``.
2512 """
2513 packed = self._conn.pack_commands([(b"CLIENT", b"CACHING", decision), args])
2514 self._conn.send_packed_command(
2515 packed, check_health=kwargs.get("check_health", True)
2516 )
2517 self._pending_caching_reply = True
2519 def can_read(self, timeout: float = 0) -> bool:
2520 # TODO: Rename this API; it detects pending data or dirty/closed
2521 # connection state, not only whether application data can be read.
2522 return self._conn.can_read(timeout)
2524 def read_response(
2525 self,
2526 disable_decoding=False,
2527 *,
2528 timeout: Union[float, object] = SENTINEL,
2529 disconnect_on_error=True,
2530 push_request=False,
2531 ):
2532 if self._pending_cache_hit is not _NO_PENDING_HIT:
2533 # ``send_command`` resolved this read from the cache and wrote nothing, so there
2534 # is no reply on the socket and the cache is deliberately not consulted again -
2535 # see the note there on why re-deriving the decision desynchronises the
2536 # connection.
2537 response = self._pending_cache_hit
2538 self._pending_cache_hit = _NO_PENDING_HIT
2539 record_csc_request(
2540 result=CSCResult.HIT,
2541 )
2542 record_csc_network_saved(
2543 bytes_saved=len(response) if hasattr(response, "__len__") else 0,
2544 )
2545 return response
2547 if self._current_command_cache_key is not None:
2548 # A key is still set, so ``send_command`` decided to store this reply and sent the
2549 # command: by construction a miss.
2550 record_csc_request(
2551 result=CSCResult.MISS,
2552 )
2554 try:
2555 if self._pending_caching_reply:
2556 # Consumed before the wire read below, so an interleaved invalidation cannot
2557 # be mistaken for either reply of the pair. Inside the ``try`` so a failure
2558 # here drops the placeholder exactly as a failed data read does.
2559 self._pending_caching_reply = False
2560 self._read_caching_reply(
2561 timeout=timeout, disconnect_on_error=disconnect_on_error
2562 )
2564 response = self._conn.read_response(
2565 disable_decoding=disable_decoding,
2566 timeout=timeout,
2567 disconnect_on_error=disconnect_on_error,
2568 push_request=push_request,
2569 )
2570 if self._current_command_cache_key is not None:
2571 cloned_response = _clone_cache_value(response)
2572 except BaseException:
2573 # The placeholder ``send_command`` staked is resolved only by the read that just
2574 # failed, so it has to go with it. Left behind, it sits in the pool-wide cache
2575 # until an invalidation or a disconnect happens to clear it: nothing else will,
2576 # because this command never completed and so the server is tracking nothing for
2577 # it. A ``WRONGTYPE`` or ``NOPERM`` reply is enough to strand one, as is the
2578 # ``-ASK`` on the first attempt of a redirected read.
2579 self._drop_own_placeholder()
2580 raise
2582 with self._cache_lock:
2583 # Prevent not-allowed command from caching.
2584 if self._current_command_cache_key is None:
2585 return response
2586 # If response is None prevent from caching. Only our own placeholder is
2587 # dropped: the entry may by now belong to another connection.
2588 if response is None:
2589 self._drop_own_placeholder()
2590 return response
2592 cache_entry = self._cache.get(self._current_command_cache_key)
2594 # Promote only the placeholder this connection staked. It may have been
2595 # invalidated in the meantime, or replaced by another connection's placeholder
2596 # for the same key - promoting that one would bind our reply to its
2597 # ``connection_ref``, and a later hit would drain that connection's own reply.
2598 if (
2599 cache_entry is not None
2600 and cache_entry.status == CacheEntryStatus.IN_PROGRESS
2601 and cache_entry.connection_ref is self._conn
2602 ):
2603 cache_entry.cache_value = cloned_response
2604 cache_entry.status = CacheEntryStatus.VALID
2605 self._cache.set(cache_entry)
2607 self._current_command_cache_key = None
2609 return response
2611 def _drop_own_placeholder(self) -> None:
2612 """
2613 Drop the ``IN_PROGRESS`` placeholder this connection staked, if it is still ours.
2615 Called when the read that would have resolved the placeholder fails. The cache is
2616 shared by the whole pool while each proxy's lock is its own, so the entry under this
2617 key may no longer be the one this connection put there, and the delete is scoped to
2618 the two conditions that prove it is:
2620 - still ``IN_PROGRESS`` - another connection's successful read can resolve this very
2621 entry to ``VALID`` in place, and deleting it would discard a correctly stored reply;
2622 - ``connection_ref`` is this connection - another connection's ``send_command`` for
2623 the same key replaces the entry with its own placeholder, and deleting it would
2624 evict a fetch that is still in flight.
2626 Clears ``_current_command_cache_key`` either way: the read it pointed at is over.
2627 """
2628 key = self._current_command_cache_key
2629 if key is None:
2630 return
2632 with self._cache_lock:
2633 entry = self._cache.get(key)
2634 if (
2635 entry is not None
2636 and entry.status == CacheEntryStatus.IN_PROGRESS
2637 and entry.connection_ref is self._conn
2638 ):
2639 self._cache.delete_by_cache_keys([key])
2641 self._current_command_cache_key = None
2643 def _read_caching_reply(self, *, timeout, disconnect_on_error) -> None:
2644 """
2645 Consume the ``+OK`` of a ``CLIENT CACHING`` command sent ahead of a read.
2647 Called inside ``read_response``'s ``try``, whose handlers clean up after any failure
2648 here the same way they do after a failed data read. A ``ConnectionError`` fails both
2649 commands together - never the read alone, whose reply would otherwise be stored
2650 without the tracking that makes it safe. The wrapped socket is closed, but the cache
2651 is flushed only when the client's error handling then disconnects this connection,
2652 or when the next connect re-enables tracking.
2654 Args:
2655 timeout: The caller's bound for this read.
2656 disconnect_on_error: Passed through to the wrapped connection.
2658 Raises:
2659 ResponseError: Re-raised after the paired read's reply has been drained.
2660 ConnectionError: If the server answered something other than ``OK``.
2661 """
2662 try:
2663 reply = self._conn.read_response(
2664 timeout=timeout, disconnect_on_error=disconnect_on_error
2665 )
2666 except ResponseError:
2667 # The paired read executed on the server regardless. Leaving its reply on the
2668 # socket would return this connection to the pool one reply out of sync, and the
2669 # next borrower would read our answer. The placeholder is dropped by the caller's
2670 # ``except BaseException``, as for any other failed read.
2671 self._conn.read_response(
2672 timeout=timeout, disconnect_on_error=disconnect_on_error
2673 )
2674 raise
2676 if str_if_bytes(reply) != "OK":
2677 raise ConnectionError(f"Unexpected CLIENT CACHING reply: {reply!r}")
2679 def pack_command(self, *args):
2680 return self._conn.pack_command(*args)
2682 def pack_commands(self, commands):
2683 # Every pipeline and transaction packs through here, so the guard covers them as
2684 # well. The cache's own commands are unaffected: ``_send_with_caching`` packs
2685 # through the wrapped connection, and the tracking handshake is sent on it.
2686 for args in commands:
2687 self._refuse_cache_owned_command(args)
2688 return self._conn.pack_commands(commands)
2690 @staticmethod
2691 def _refuse_cache_owned_command(args) -> None:
2692 """
2693 Refuse a user-sent ``CLIENT CACHING``, ``CLIENT TRACKING`` or ``RESET`` on a
2694 connection the cache manages.
2696 Each of them changes the tracking state the cache relies on for invalidations:
2698 - ``CLIENT CACHING`` sets a flag the server applies to the next command on the
2699 socket, and a pooled connection promises nothing about which command that is.
2700 Under ``optout`` a stray ``NO`` would leave the next cached read untracked while
2701 its reply is still stored, so it would never be invalidated. The cache sends it
2702 itself, paired with the read it belongs to, whenever the tracking mode needs it.
2703 - ``CLIENT TRACKING`` turns tracking off or reconfigures it, so the cache would keep
2704 storing replies that no invalidation reaches. The cache enables tracking itself
2705 when the connection is established.
2706 - ``RESET`` clears tracking along with the rest of the connection state.
2708 Raises:
2709 RedisError: If ``args`` is one of these commands.
2710 """
2711 command = _cache_owned_command(args)
2712 if command is None:
2713 return
2714 if command == "CLIENT CACHING":
2715 reason = "the cache sends it itself, paired with the read it applies to"
2716 elif command == "CLIENT TRACKING":
2717 reason = (
2718 "the cache enables tracking itself, and changing it would stop "
2719 "invalidations for cached replies"
2720 )
2721 else:
2722 reason = "it turns off the tracking the cache relies on for invalidations"
2723 raise RedisError(
2724 f"{command} cannot be sent on a connection with client-side caching "
2725 f"enabled: {reason}"
2726 )
2728 # HIMPORT state lives on the wrapped connection (HIMPORT is never cacheable);
2729 # delegate so callers treat the proxy like a plain connection and never need
2730 # to know a proxy is in play.
2731 @property
2732 def himport_registry(self):
2733 return self._conn.himport_registry
2735 @property
2736 def _himport_prepared(self):
2737 return self._conn._himport_prepared
2739 @_himport_prepared.setter
2740 def _himport_prepared(self, value):
2741 # Delegate reassignment to the wrapped connection, mirroring
2742 # ``_himport_reconciled_revision``. Production code only mutates the dict
2743 # in place, but ``_reset_himport_state`` (and any future caller) reassigns
2744 # it, and a getter-only property here would raise ``AttributeError`` only
2745 # when client-side caching is enabled -- a caching-specific latent trap.
2746 self._conn._himport_prepared = value
2748 @property
2749 def _himport_reconciled_revision(self):
2750 return self._conn._himport_reconciled_revision
2752 @_himport_reconciled_revision.setter
2753 def _himport_reconciled_revision(self, value):
2754 self._conn._himport_reconciled_revision = value
2756 @property
2757 def handshake_metadata(self) -> Union[Dict[bytes, bytes], Dict[str, str]]:
2758 return self._conn.handshake_metadata
2760 def set_re_auth_token(self, token: TokenInterface | None):
2761 self._conn.set_re_auth_token(token)
2763 def re_auth(self):
2764 # A cache hit on another connection drains this socket under the pool
2765 # lock, and the drain reads ordinary replies too, so the AUTH reply
2766 # must not be in flight outside it
2767 with self._pool_lock:
2768 self._conn.re_auth()
2770 def mark_for_reconnect(self):
2771 self._conn.mark_for_reconnect()
2773 def should_reconnect(self):
2774 return self._conn.should_reconnect()
2776 def reset_should_reconnect(self):
2777 self._conn.reset_should_reconnect()
2779 @property
2780 def host(self) -> str:
2781 return self._conn.host
2783 @host.setter
2784 def host(self, value: str):
2785 self._conn.host = value
2787 @property
2788 def socket_timeout(self) -> Optional[Union[float, int]]:
2789 return self._conn.socket_timeout
2791 @socket_timeout.setter
2792 def socket_timeout(self, value: Optional[Union[float, int]]):
2793 self._conn.socket_timeout = value
2795 @property
2796 def socket_connect_timeout(self) -> Optional[Union[float, int]]:
2797 return self._conn.socket_connect_timeout
2799 @socket_connect_timeout.setter
2800 def socket_connect_timeout(self, value: Optional[Union[float, int]]):
2801 self._conn.socket_connect_timeout = value
2803 @property
2804 def _maint_notifications_connection_handler(
2805 self,
2806 ) -> Optional[MaintNotificationsConnectionHandler]:
2807 if isinstance(self._conn, MaintNotificationsAbstractConnection):
2808 return self._conn._maint_notifications_connection_handler
2810 @_maint_notifications_connection_handler.setter
2811 def _maint_notifications_connection_handler(
2812 self, value: Optional[MaintNotificationsConnectionHandler]
2813 ):
2814 self._conn._maint_notifications_connection_handler = value
2816 def _get_socket(self) -> Optional[socket.socket]:
2817 if isinstance(self._conn, MaintNotificationsAbstractConnection):
2818 return self._conn._get_socket()
2819 else:
2820 raise NotImplementedError(
2821 "Maintenance notifications are not supported by this connection type"
2822 )
2824 def _get_parser(self) -> BaseParser:
2825 return self._conn._get_parser()
2827 def _get_maint_notifications_connection_instance(
2828 self, connection
2829 ) -> MaintNotificationsAbstractConnection:
2830 """
2831 Validate that connection instance supports maintenance notifications.
2832 With this helper method we ensure that we are working
2833 with the correct connection type.
2834 After twe validate that connection instance supports maintenance notifications
2835 we can safely return the connection instance
2836 as MaintNotificationsAbstractConnection.
2837 """
2838 if not isinstance(connection, MaintNotificationsAbstractConnection):
2839 raise NotImplementedError(
2840 "Maintenance notifications are not supported by this connection type"
2841 )
2842 else:
2843 return connection
2845 @property
2846 def maintenance_state(self) -> MaintenanceState:
2847 con = self._get_maint_notifications_connection_instance(self._conn)
2848 return con.maintenance_state
2850 @maintenance_state.setter
2851 def maintenance_state(self, state: MaintenanceState):
2852 con = self._get_maint_notifications_connection_instance(self._conn)
2853 con.maintenance_state = state
2855 def getpeername(self):
2856 con = self._get_maint_notifications_connection_instance(self._conn)
2857 return con.getpeername()
2859 def get_resolved_ip(self):
2860 con = self._get_maint_notifications_connection_instance(self._conn)
2861 return con.get_resolved_ip()
2863 def update_current_socket_timeout(self, relaxed_timeout: Optional[float] = None):
2864 con = self._get_maint_notifications_connection_instance(self._conn)
2865 con.update_current_socket_timeout(relaxed_timeout)
2867 def set_tmp_settings(
2868 self,
2869 tmp_host_address: Optional[str] = None,
2870 tmp_relaxed_timeout: Optional[float] = -1,
2871 ):
2872 con = self._get_maint_notifications_connection_instance(self._conn)
2873 con.set_tmp_settings(tmp_host_address, tmp_relaxed_timeout)
2875 def reset_tmp_settings(
2876 self,
2877 reset_host_address: bool = False,
2878 reset_relaxed_timeout: bool = False,
2879 ):
2880 con = self._get_maint_notifications_connection_instance(self._conn)
2881 con.reset_tmp_settings(reset_host_address, reset_relaxed_timeout)
2883 def _connect(self):
2884 self._conn._connect()
2886 def _host_error(self):
2887 return self._conn._host_error()
2889 def _enable_tracking_callback(self, conn: ConnectionInterface) -> None:
2890 if self._connected_once:
2891 # The server destroys a connection's tracking state on disconnect, so every entry
2892 # cached through the previous session has lost its invalidation channel. Paths
2893 # that reconnect silently inside the send path never call ``disconnect``, so the
2894 # flush cannot live there alone.
2895 #
2896 # Gated on a previous connect because this callback also fires on a first connect
2897 # and the cache is pool-shared: an unconditional flush would wipe other
2898 # connections' entries every time the pool grows. Flushing the whole shared cache
2899 # on reconnect is what ``disconnect`` already does, so the semantics do not
2900 # change - only the coverage does.
2901 #
2902 # The one entry kept is this connection's own in-flight placeholder. Every
2903 # reconnect that fires this callback happens inside the send path, before the
2904 # command is written, so the reply it is waiting for comes from the new session -
2905 # which this callback is about to enable tracking for. Dropping it would cost the
2906 # fill and gain nothing.
2907 with self._cache_lock:
2908 own_placeholder = None
2909 if self._current_command_cache_key is not None:
2910 entry = self._cache.get(self._current_command_cache_key)
2911 if (
2912 entry is not None
2913 and entry.status == CacheEntryStatus.IN_PROGRESS
2914 and entry.connection_ref is self._conn
2915 ):
2916 own_placeholder = entry
2917 self._cache.flush()
2918 if own_placeholder is not None:
2919 self._cache.set(own_placeholder)
2921 self._pending_caching_reply = False
2923 # The mode is sent in the handshake because that is what the server requires:
2924 # switching OPTIN <-> OPTOUT on a live connection is an error, so a configuration
2925 # change applies to new connections only.
2926 args = ["CLIENT", "TRACKING", "ON"]
2927 if self._tracking_mode is TrackingMode.OPTIN:
2928 args.append("OPTIN")
2929 elif self._tracking_mode is TrackingMode.OPTOUT:
2930 args.append("OPTOUT")
2932 conn.send_command(*args)
2933 conn.read_response()
2934 # Set only once tracking is on: a handshake that fails before this point cached
2935 # nothing, so the next connect has no session to flush for.
2936 self._connected_once = True
2937 conn._parser.set_invalidation_push_handler(self._on_invalidation_callback)
2939 def _drain_invalidations(self, conn: ConnectionInterface):
2940 while conn.can_read():
2941 try:
2942 conn.read_response(
2943 push_request=True, timeout=0, disconnect_on_error=False
2944 )
2945 except TimeoutError:
2946 break
2947 except UNRECOVERABLE_PARSE_ERRORS:
2948 # Invalidation replies are read straight off the raw
2949 # connection, so the disconnect a parse failure now forces
2950 # bypasses this proxy's disconnect() and its cache flush. The
2951 # next connect() opens a fresh CLIENT TRACKING session that the
2952 # server has no invalidation state for, so entries cached under
2953 # the old session would be served as if still tracked. Flush
2954 # them here for the same reason disconnect() does.
2955 with self._cache_lock:
2956 self._cache.flush()
2957 raise
2959 def _process_pending_invalidations(self):
2960 self._drain_invalidations(self._conn)
2962 def _on_invalidation_callback(self, data: List[Union[str, Optional[List[bytes]]]]):
2963 with self._cache_lock:
2964 # Flush cache when DB flushed on server-side
2965 if data[1] is None:
2966 self._cache.flush()
2967 else:
2968 keys_deleted = self._cache.delete_by_redis_keys(data[1])
2970 if len(keys_deleted) > 0:
2971 record_csc_eviction(
2972 count=len(keys_deleted),
2973 reason=CSCReason.INVALIDATION,
2974 )
2976 def extract_connection_details(self) -> str:
2977 return self._conn.extract_connection_details()
2980class SSLConnection(Connection):
2981 """Manages SSL connections to and from the Redis server(s).
2982 This class extends the Connection class, adding SSL functionality, and making
2983 use of ssl.SSLContext (https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
2984 """ # noqa
2986 def __init__(
2987 self,
2988 ssl_keyfile=None,
2989 ssl_certfile=None,
2990 ssl_cert_reqs="required",
2991 ssl_include_verify_flags: Optional[List["VerifyFlags"]] = None,
2992 ssl_exclude_verify_flags: Optional[List["VerifyFlags"]] = None,
2993 ssl_ca_certs=None,
2994 ssl_ca_data=None,
2995 ssl_check_hostname=True,
2996 ssl_ca_path=None,
2997 ssl_password=None,
2998 ssl_validate_ocsp=False,
2999 ssl_validate_ocsp_stapled=False,
3000 ssl_ocsp_context=None,
3001 ssl_ocsp_expected_cert=None,
3002 ssl_min_version=None,
3003 ssl_ciphers=None,
3004 **kwargs,
3005 ):
3006 """Constructor
3008 Args:
3009 ssl_keyfile: Path to an ssl private key. Defaults to None.
3010 ssl_certfile: Path to an ssl certificate. Defaults to None.
3011 ssl_cert_reqs: The string value for the SSLContext.verify_mode (none, optional, required),
3012 or an ssl.VerifyMode. Defaults to "required".
3013 ssl_include_verify_flags: A list of flags to be included in the SSLContext.verify_flags. Defaults to None.
3014 ssl_exclude_verify_flags: A list of flags to be excluded from the SSLContext.verify_flags. Defaults to None.
3015 ssl_ca_certs: The path to a file of concatenated CA certificates in PEM format. Defaults to None.
3016 ssl_ca_data: Either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates.
3017 ssl_check_hostname: If set, match the hostname during the SSL handshake. Defaults to True.
3018 ssl_ca_path: The path to a directory containing several CA certificates in PEM format. Defaults to None.
3019 ssl_password: Password for unlocking an encrypted private key. Defaults to None.
3021 ssl_validate_ocsp: If set, perform a full ocsp validation (i.e not a stapled verification)
3022 ssl_validate_ocsp_stapled: If set, perform a validation on a stapled ocsp response
3023 ssl_ocsp_context: A fully initialized OpenSSL.SSL.Context object to be used in verifying the ssl_ocsp_expected_cert
3024 ssl_ocsp_expected_cert: A PEM armoured string containing the expected certificate to be returned from the ocsp verification service.
3025 ssl_min_version: The lowest supported SSL version. It affects the supported SSL versions of the SSLContext. None leaves the default provided by ssl module.
3026 ssl_ciphers: A string listing the ciphers that are allowed to be used. Defaults to None, which means that the default ciphers are used. See https://docs.python.org/3/library/ssl.html#ssl.SSLContext.set_ciphers for more information.
3028 Raises:
3029 RedisError
3030 """ # noqa
3031 if not SSL_AVAILABLE:
3032 raise RedisError("Python wasn't built with SSL support")
3034 self.keyfile = ssl_keyfile
3035 self.certfile = ssl_certfile
3036 if ssl_cert_reqs is None:
3037 ssl_cert_reqs = ssl.CERT_NONE
3038 elif isinstance(ssl_cert_reqs, str):
3039 CERT_REQS = { # noqa: N806
3040 "none": ssl.CERT_NONE,
3041 "optional": ssl.CERT_OPTIONAL,
3042 "required": ssl.CERT_REQUIRED,
3043 }
3044 if ssl_cert_reqs not in CERT_REQS:
3045 raise RedisError(
3046 f"Invalid SSL Certificate Requirements Flag: {ssl_cert_reqs}"
3047 )
3048 ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
3049 self.cert_reqs = ssl_cert_reqs
3050 self.ssl_include_verify_flags = ssl_include_verify_flags
3051 self.ssl_exclude_verify_flags = ssl_exclude_verify_flags
3052 self.ca_certs = ssl_ca_certs
3053 self.ca_data = ssl_ca_data
3054 self.ca_path = ssl_ca_path
3055 self.check_hostname = (
3056 ssl_check_hostname if self.cert_reqs != ssl.CERT_NONE else False
3057 )
3058 self.certificate_password = ssl_password
3059 self.ssl_validate_ocsp = ssl_validate_ocsp
3060 self.ssl_validate_ocsp_stapled = ssl_validate_ocsp_stapled
3061 self.ssl_ocsp_context = ssl_ocsp_context
3062 self.ssl_ocsp_expected_cert = ssl_ocsp_expected_cert
3063 self.ssl_min_version = ssl_min_version
3064 self.ssl_ciphers = ssl_ciphers
3065 super().__init__(**kwargs)
3067 def _connect(self):
3068 """
3069 Wrap the socket with SSL support, handling potential errors.
3070 """
3071 sock = super()._connect()
3072 try:
3073 return self._wrap_socket_with_ssl(sock)
3074 except (OSError, RedisError):
3075 sock.close()
3076 raise
3078 def _build_ssl_context(self):
3079 """
3080 Builds an SSL context from the connection's TLS settings.
3082 Returns:
3083 A new ssl.SSLContext.
3084 """
3085 context = ssl.create_default_context()
3086 context.check_hostname = self.check_hostname
3087 context.verify_mode = self.cert_reqs
3088 if self.ssl_include_verify_flags:
3089 for flag in self.ssl_include_verify_flags:
3090 context.verify_flags |= flag
3091 if self.ssl_exclude_verify_flags:
3092 for flag in self.ssl_exclude_verify_flags:
3093 context.verify_flags &= ~flag
3094 if self.certfile or self.keyfile:
3095 context.load_cert_chain(
3096 certfile=self.certfile,
3097 keyfile=self.keyfile,
3098 password=self.certificate_password,
3099 )
3100 if (
3101 self.ca_certs is not None
3102 or self.ca_path is not None
3103 or self.ca_data is not None
3104 ):
3105 context.load_verify_locations(
3106 cafile=self.ca_certs, capath=self.ca_path, cadata=self.ca_data
3107 )
3108 if self.ssl_min_version is not None:
3109 context.minimum_version = self.ssl_min_version
3110 if self.ssl_ciphers:
3111 context.set_ciphers(self.ssl_ciphers)
3112 return context
3114 def _wrap_socket_with_ssl(self, sock):
3115 """
3116 Wraps the socket with SSL support.
3118 Args:
3119 sock: The plain socket to wrap with SSL.
3121 Returns:
3122 An SSL wrapped socket.
3123 """
3124 if not isinstance(self.certificate_password, (str, bytes, type(None))):
3125 # Only the documented password types are shared. Anything else gets a
3126 # private context, so the cache key never holds a reference to it.
3127 context = self._build_ssl_context()
3128 else:
3129 context = get_shared_ssl_context(
3130 self._build_ssl_context,
3131 (
3132 type(self),
3133 self.cert_reqs,
3134 self.check_hostname,
3135 tuple(self.ssl_include_verify_flags or ()),
3136 tuple(self.ssl_exclude_verify_flags or ()),
3137 self.certificate_password,
3138 self.ca_data,
3139 self.ssl_min_version,
3140 self.ssl_ciphers,
3141 ),
3142 (self.certfile, self.keyfile, self.ca_certs, self.ca_path),
3143 )
3144 if self.ssl_validate_ocsp is True and CRYPTOGRAPHY_AVAILABLE is False:
3145 raise RedisError("cryptography is not installed.")
3147 if self.ssl_validate_ocsp_stapled and self.ssl_validate_ocsp:
3148 raise RedisError(
3149 "Either an OCSP staple or pure OCSP connection must be validated "
3150 "- not both."
3151 )
3153 sock.settimeout(self.socket_connect_timeout)
3154 sslsock = context.wrap_socket(sock, server_hostname=self.host)
3155 sslsock.settimeout(self.socket_timeout)
3157 # validation for the stapled case
3158 if self.ssl_validate_ocsp_stapled:
3159 import OpenSSL
3161 from .ocsp import ocsp_staple_verifier
3163 # if a context is provided use it - otherwise, a basic context
3164 if self.ssl_ocsp_context is None:
3165 staple_ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
3166 staple_ctx.use_certificate_file(self.certfile)
3167 staple_ctx.use_privatekey_file(self.keyfile)
3168 else:
3169 staple_ctx = self.ssl_ocsp_context
3171 staple_ctx.set_ocsp_client_callback(
3172 ocsp_staple_verifier, self.ssl_ocsp_expected_cert
3173 )
3175 # need another socket
3176 con = OpenSSL.SSL.Connection(staple_ctx, socket.socket())
3177 # Send the same SNI as sslsock so the probe is given the same
3178 # certificate. ssl sends none for an IP address, so neither do we.
3179 try:
3180 ipaddress.ip_address(self.host)
3181 except ValueError:
3182 con.set_tlsext_host_name(self.host.encode())
3183 con.request_ocsp()
3184 con.connect((self.host, self.port))
3185 con.do_handshake()
3186 con.shutdown()
3188 # The staple was validated on a second connection, so it only
3189 # vouches for sslsock if both presented the same certificate.
3190 staple_cert = OpenSSL.crypto.dump_certificate(
3191 OpenSSL.crypto.FILETYPE_ASN1, con.get_peer_certificate()
3192 )
3193 if staple_cert != sslsock.getpeercert(True):
3194 sslsock.close()
3195 raise ConnectionError(
3196 "ocsp stapled certificate does not match the connection certificate"
3197 )
3198 return sslsock
3200 # pure ocsp validation
3201 if self.ssl_validate_ocsp is True and CRYPTOGRAPHY_AVAILABLE:
3202 from .ocsp import OCSPVerifier
3204 o = OCSPVerifier(sslsock, self.host, self.port, self.ca_certs)
3205 if o.is_valid():
3206 return sslsock
3207 else:
3208 raise ConnectionError("ocsp validation error")
3209 return sslsock
3212class UnixDomainSocketConnection(AbstractConnection):
3213 "Manages UDS communication to and from a Redis server"
3215 def __init__(self, path="", socket_timeout=DEFAULT_SOCKET_TIMEOUT, **kwargs):
3216 super().__init__(**kwargs)
3217 self.path = path
3218 self.socket_timeout = socket_timeout
3220 def repr_pieces(self):
3221 pieces = [("path", self.path), ("db", self.db)]
3222 if self.client_name:
3223 pieces.append(("client_name", self.client_name))
3224 return pieces
3226 def _connect(self):
3227 "Create a Unix domain socket connection"
3228 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
3229 sock.settimeout(self.socket_connect_timeout)
3230 try:
3231 sock.connect(self.path)
3232 except OSError:
3233 # Prevent ResourceWarnings for unclosed sockets.
3234 try:
3235 sock.shutdown(socket.SHUT_RDWR) # ensure a clean close
3236 except OSError:
3237 pass
3238 sock.close()
3239 raise
3240 sock.settimeout(self.socket_timeout)
3241 return sock
3243 def _host_error(self):
3244 return self.path
3247FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO", "OFF")
3250def to_bool(value):
3251 if value is None or value == "":
3252 return None
3253 if isinstance(value, str) and value.upper() in FALSE_STRINGS:
3254 return False
3255 return bool(value)
3258def parse_ssl_verify_flags(value):
3259 # flags are passed in as a string representation of a list,
3260 # e.g. VERIFY_X509_STRICT, VERIFY_X509_PARTIAL_CHAIN
3261 verify_flags_str = value.replace("[", "").replace("]", "")
3263 verify_flags = []
3264 for flag in verify_flags_str.split(","):
3265 flag = flag.strip()
3266 if not hasattr(VerifyFlags, flag):
3267 raise ValueError(f"Invalid ssl verify flag: {flag}")
3268 verify_flags.append(getattr(VerifyFlags, flag))
3269 return verify_flags
3272def parse_retry_on_error(value):
3273 # exception class names are passed as a comma-separated list,
3274 # e.g. ConnectionError,TimeoutError
3275 retry_on_error = []
3276 for name in value.replace("[", "").replace("]", "").split(","):
3277 name = name.strip()
3278 if not name:
3279 raise ValueError("Empty retry_on_error entry")
3280 exc = getattr(redis_exceptions, name, None)
3281 if not (isinstance(exc, type) and issubclass(exc, Exception)):
3282 raise ValueError(f"Unknown redis exception {name!r}")
3283 retry_on_error.append(exc)
3284 return retry_on_error
3287URL_QUERY_ARGUMENT_PARSERS = {
3288 "db": int,
3289 "socket_timeout": float,
3290 "socket_connect_timeout": float,
3291 "socket_read_size": int,
3292 "socket_keepalive": to_bool,
3293 "retry_on_timeout": to_bool,
3294 "retry_on_error": parse_retry_on_error,
3295 "max_connections": int,
3296 "health_check_interval": int,
3297 "ssl_check_hostname": to_bool,
3298 "ssl_validate_ocsp": to_bool,
3299 "ssl_validate_ocsp_stapled": to_bool,
3300 "ssl_include_verify_flags": parse_ssl_verify_flags,
3301 "ssl_exclude_verify_flags": parse_ssl_verify_flags,
3302 "ssl_min_version": int,
3303 "timeout": float,
3304 "protocol": int,
3305 "legacy_responses": to_bool,
3306}
3309def parse_url(url):
3310 # Scheme names are case-insensitive (RFC 3986), so normalize before the
3311 # prefix check; the "://" is required so a URL like "redis:foo" (which
3312 # urlparse would still report as the "redis" scheme) is rejected.
3313 if not url.lower().startswith(("redis://", "rediss://", "unix://")):
3314 raise ValueError(
3315 "Redis URL must specify one of the following "
3316 "schemes (redis://, rediss://, unix://)"
3317 )
3319 url = urlparse(url)
3320 kwargs = {}
3322 for name, value in parse_qs(url.query).items():
3323 if value and len(value) > 0:
3324 # parse_qs() already percent-decodes query values, so use the value
3325 # as-is; unquoting again here would double-decode (e.g. "%2520" ->
3326 # "%20" -> " "). See issue #4208.
3327 value = value[0]
3328 parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
3329 if parser:
3330 try:
3331 kwargs[name] = parser(value)
3332 except (TypeError, ValueError):
3333 raise ValueError(f"Invalid value for '{name}' in connection URL.")
3334 else:
3335 kwargs[name] = value
3337 if url.username:
3338 kwargs["username"] = unquote(url.username)
3339 if url.password:
3340 kwargs["password"] = unquote(url.password)
3342 # We only support redis://, rediss:// and unix:// schemes.
3343 if url.scheme == "unix":
3344 if url.path:
3345 kwargs["path"] = unquote(url.path)
3346 kwargs["connection_class"] = UnixDomainSocketConnection
3348 else: # implied: url.scheme in ("redis", "rediss"):
3349 if url.hostname:
3350 kwargs["host"] = unquote(url.hostname)
3351 if url.port is not None:
3352 kwargs["port"] = int(url.port)
3354 # If there's a path argument, use it as the db argument if a
3355 # querystring value wasn't specified
3356 if url.path and "db" not in kwargs:
3357 try:
3358 kwargs["db"] = int(unquote(url.path).replace("/", ""))
3359 except (AttributeError, ValueError):
3360 pass
3362 if url.scheme == "rediss":
3363 kwargs["connection_class"] = SSLConnection
3365 return kwargs
3368_CP = TypeVar("_CP", bound="ConnectionPool")
3371class ConnectionPoolInterface(ABC):
3372 @abstractmethod
3373 def get_protocol(self):
3374 pass
3376 @abstractmethod
3377 def reset(self):
3378 pass
3380 @abstractmethod
3381 @deprecated_args(
3382 args_to_warn=["*"],
3383 reason="Use get_connection() without args instead",
3384 version="5.3.0",
3385 )
3386 def get_connection(
3387 self, command_name: Optional[str], *keys, **options
3388 ) -> ConnectionInterface:
3389 pass
3391 @abstractmethod
3392 def get_encoder(self):
3393 pass
3395 @abstractmethod
3396 def release(self, connection: ConnectionInterface):
3397 pass
3399 @abstractmethod
3400 def disconnect(self, inuse_connections: bool = True):
3401 pass
3403 @abstractmethod
3404 def close(self):
3405 pass
3407 @abstractmethod
3408 def set_retry(self, retry: Retry):
3409 pass
3411 @abstractmethod
3412 def re_auth_callback(self, token: TokenInterface):
3413 pass
3415 @abstractmethod
3416 def get_connection_count(self) -> list[tuple[int, dict]]:
3417 """
3418 Returns a connection count (both idle and in use).
3419 """
3420 pass
3423class MaintNotificationsAbstractConnectionPool:
3424 """
3425 Abstract class for handling maintenance notifications logic.
3426 This class is mixed into the ConnectionPool classes.
3428 This class is not intended to be used directly!
3430 All logic related to maintenance notifications and
3431 connection pool handling is encapsulated in this class.
3432 """
3434 def __init__(
3435 self,
3436 maint_notifications_config: Optional[MaintNotificationsConfig] = None,
3437 oss_cluster_maint_notifications_handler: Optional[
3438 OSSMaintNotificationsHandler
3439 ] = None,
3440 **kwargs,
3441 ):
3442 # Initialize maintenance notifications
3443 is_protocol_supported = check_protocol_version(kwargs.get("protocol"), 3)
3445 if maint_notifications_config is None and is_protocol_supported:
3446 maint_notifications_config = MaintNotificationsConfig()
3448 if maint_notifications_config and maint_notifications_config.enabled:
3449 if not is_protocol_supported:
3450 raise RedisError(
3451 "Maintenance notifications handlers on connection are only supported with RESP version 3"
3452 )
3454 self._event_dispatcher = kwargs.get("event_dispatcher", None)
3455 if self._event_dispatcher is None:
3456 self._event_dispatcher = EventDispatcher()
3458 self._maint_notifications_pool_handler = MaintNotificationsPoolHandler(
3459 self, maint_notifications_config
3460 )
3461 if oss_cluster_maint_notifications_handler:
3462 self._oss_cluster_maint_notifications_handler = (
3463 oss_cluster_maint_notifications_handler
3464 )
3465 self._update_connection_kwargs_for_maint_notifications(
3466 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler
3467 )
3468 self._maint_notifications_pool_handler = None
3469 else:
3470 self._oss_cluster_maint_notifications_handler = None
3471 self._maint_notifications_pool_handler = MaintNotificationsPoolHandler(
3472 self, maint_notifications_config
3473 )
3475 self._update_connection_kwargs_for_maint_notifications(
3476 maint_notifications_pool_handler=self._maint_notifications_pool_handler
3477 )
3478 else:
3479 self._maint_notifications_pool_handler = None
3480 self._oss_cluster_maint_notifications_handler = None
3482 def _on_close(self) -> None:
3483 """Hook invoked from the pool's ``close()`` before the pool is shut down."""
3484 handler = getattr(self, "_maint_notifications_pool_handler", None)
3485 if handler is not None:
3486 handler.cancel_scheduled_tasks()
3488 def _on_reset_after_fork(self) -> None:
3489 """Hook invoked by ``reset()``; acts only in a forked child process."""
3490 handler = getattr(self, "_maint_notifications_pool_handler", None)
3491 # reset() also runs from __init__, where there is no pid yet
3492 pid = getattr(self, "pid", None)
3493 if handler is not None and pid is not None and pid != os.getpid():
3494 handler.reset_after_fork()
3496 @property
3497 @abstractmethod
3498 def connection_kwargs(self) -> Dict[str, Any]:
3499 pass
3501 @connection_kwargs.setter
3502 @abstractmethod
3503 def connection_kwargs(self, value: Dict[str, Any]):
3504 pass
3506 @abstractmethod
3507 def _get_pool_lock(self) -> threading.RLock:
3508 pass
3510 @abstractmethod
3511 def _get_free_connections(self) -> Iterable["MaintNotificationsAbstractConnection"]:
3512 pass
3514 @abstractmethod
3515 def _get_in_use_connections(
3516 self,
3517 ) -> Iterable["MaintNotificationsAbstractConnection"]:
3518 pass
3520 def maint_notifications_enabled(self):
3521 """
3522 Returns:
3523 True if the maintenance notifications are enabled, False otherwise.
3524 The maintenance notifications config is stored in the pool handler.
3525 If the pool handler is not set, the maintenance notifications are not enabled.
3526 """
3527 if self._oss_cluster_maint_notifications_handler:
3528 maint_notifications_config = (
3529 self._oss_cluster_maint_notifications_handler.config
3530 )
3531 else:
3532 maint_notifications_config = (
3533 self._maint_notifications_pool_handler.config
3534 if self._maint_notifications_pool_handler
3535 else None
3536 )
3538 return maint_notifications_config and maint_notifications_config.enabled
3540 def update_maint_notifications_config(
3541 self,
3542 maint_notifications_config: MaintNotificationsConfig,
3543 oss_cluster_maint_notifications_handler: Optional[
3544 OSSMaintNotificationsHandler
3545 ] = None,
3546 ):
3547 """
3548 Updates the maintenance notifications configuration.
3549 This method should be called only if the pool was created
3550 without enabling the maintenance notifications and
3551 in a later point in time maintenance notifications
3552 are requested to be enabled.
3553 """
3554 if (
3555 self.maint_notifications_enabled()
3556 and not maint_notifications_config.enabled
3557 ):
3558 raise ValueError(
3559 "Cannot disable maintenance notifications after enabling them"
3560 )
3561 if oss_cluster_maint_notifications_handler:
3562 self._oss_cluster_maint_notifications_handler = (
3563 oss_cluster_maint_notifications_handler
3564 )
3565 # OSS cluster mode and pool-handler mode are mutually exclusive
3566 # (see __init__). A pool created with the default RESP3 "auto"
3567 # config wires a pool handler before this method runs; clear it so
3568 # new and existing connections are not configured with both handlers.
3569 self._maint_notifications_pool_handler = None
3570 else:
3571 # first update pool settings
3572 if self._oss_cluster_maint_notifications_handler:
3573 # Pool already in OSS cluster mode; update the OSS handler config
3574 # instead of creating a mutually-exclusive pool handler (which
3575 # would be silently ignored because the OSS handler wins priority
3576 # in both update helpers below).
3577 self._oss_cluster_maint_notifications_handler.config = (
3578 maint_notifications_config
3579 )
3580 elif not self._maint_notifications_pool_handler:
3581 self._maint_notifications_pool_handler = MaintNotificationsPoolHandler(
3582 self, maint_notifications_config
3583 )
3584 else:
3585 self._maint_notifications_pool_handler.config = (
3586 maint_notifications_config
3587 )
3589 # then update connection kwargs and existing connections
3590 self._update_connection_kwargs_for_maint_notifications(
3591 maint_notifications_pool_handler=self._maint_notifications_pool_handler,
3592 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler,
3593 )
3594 self._update_maint_notifications_configs_for_connections(
3595 maint_notifications_pool_handler=self._maint_notifications_pool_handler,
3596 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler,
3597 )
3599 def _update_connection_kwargs_for_maint_notifications(
3600 self,
3601 maint_notifications_pool_handler: Optional[
3602 MaintNotificationsPoolHandler
3603 ] = None,
3604 oss_cluster_maint_notifications_handler: Optional[
3605 OSSMaintNotificationsHandler
3606 ] = None,
3607 ):
3608 """
3609 Update the connection kwargs for all future connections.
3610 """
3611 if not self.maint_notifications_enabled():
3612 return
3613 if maint_notifications_pool_handler:
3614 self.connection_kwargs.update(
3615 {
3616 "maint_notifications_pool_handler": maint_notifications_pool_handler,
3617 "maint_notifications_config": maint_notifications_pool_handler.config,
3618 }
3619 )
3620 if oss_cluster_maint_notifications_handler:
3621 self.connection_kwargs.update(
3622 {
3623 "oss_cluster_maint_notifications_handler": oss_cluster_maint_notifications_handler,
3624 "maint_notifications_config": oss_cluster_maint_notifications_handler.config,
3625 }
3626 )
3627 # OSS cluster mode and pool-handler mode are mutually exclusive.
3628 # Drop any pool handler a default (RESP3 "auto") pool creation may
3629 # have wired so future connections are not configured with both.
3630 self.connection_kwargs.pop("maint_notifications_pool_handler", None)
3632 # Store original connection parameters for maintenance notifications.
3633 if self.connection_kwargs.get("orig_host_address", None) is None:
3634 # If orig_host_address is None it means we haven't
3635 # configured the original values yet
3636 self.connection_kwargs.update(
3637 {
3638 "orig_host_address": self.connection_kwargs.get("host"),
3639 "orig_socket_timeout": self.connection_kwargs.get(
3640 "socket_timeout", DEFAULT_SOCKET_TIMEOUT
3641 ),
3642 "orig_socket_connect_timeout": self.connection_kwargs.get(
3643 "socket_connect_timeout", DEFAULT_SOCKET_CONNECT_TIMEOUT
3644 ),
3645 }
3646 )
3648 def _update_maint_notifications_configs_for_connections(
3649 self,
3650 maint_notifications_pool_handler: Optional[
3651 MaintNotificationsPoolHandler
3652 ] = None,
3653 oss_cluster_maint_notifications_handler: Optional[
3654 OSSMaintNotificationsHandler
3655 ] = None,
3656 ):
3657 """Update the maintenance notifications config for all connections in the pool."""
3658 with self._get_pool_lock():
3659 for conn in self._get_free_connections():
3660 if oss_cluster_maint_notifications_handler:
3661 # set cluster handler for conn
3662 conn.set_maint_notifications_cluster_handler_for_connection(
3663 oss_cluster_maint_notifications_handler
3664 )
3665 conn.maint_notifications_config = (
3666 oss_cluster_maint_notifications_handler.config
3667 )
3668 elif maint_notifications_pool_handler:
3669 conn.set_maint_notifications_pool_handler_for_connection(
3670 maint_notifications_pool_handler
3671 )
3672 conn.maint_notifications_config = (
3673 maint_notifications_pool_handler.config
3674 )
3675 else:
3676 raise ValueError(
3677 "Either maint_notifications_pool_handler or oss_cluster_maint_notifications_handler must be set"
3678 )
3679 conn.disconnect()
3680 for conn in self._get_in_use_connections():
3681 if oss_cluster_maint_notifications_handler:
3682 # Use set_maint_notifications_cluster_handler_for_connection
3683 # (not _configure_maintenance_notifications) so the parser is
3684 # obtained from the connection itself. _configure_* requires a
3685 # parser argument and would raise here; it would also reset the
3686 # connection's orig_* settings, which is wrong for an in-use
3687 # (active) connection. This mirrors the idle-connection branch
3688 # above and the pool-handler branches.
3689 conn.set_maint_notifications_cluster_handler_for_connection(
3690 oss_cluster_maint_notifications_handler
3691 )
3692 conn.maint_notifications_config = (
3693 oss_cluster_maint_notifications_handler.config
3694 )
3695 elif maint_notifications_pool_handler:
3696 conn.set_maint_notifications_pool_handler_for_connection(
3697 maint_notifications_pool_handler
3698 )
3699 conn.maint_notifications_config = (
3700 maint_notifications_pool_handler.config
3701 )
3702 else:
3703 raise ValueError(
3704 "Either maint_notifications_pool_handler or oss_cluster_maint_notifications_handler must be set"
3705 )
3706 if logger.isEnabledFor(logging.DEBUG):
3707 logger.debug(
3708 "Marking active connection for reconnect after config update "
3709 f"config update: {conn}, {conn.extract_connection_details()}"
3710 )
3711 conn.mark_for_reconnect()
3713 def _should_update_connection(
3714 self,
3715 conn: "MaintNotificationsAbstractConnection",
3716 matching_pattern: Literal[
3717 "connected_address", "configured_address", "notification_hash"
3718 ] = "connected_address",
3719 matching_address: Optional[str] = None,
3720 matching_notification_hash: Optional[int] = None,
3721 ) -> bool:
3722 """
3723 Check if the connection should be updated based on the matching criteria.
3724 """
3725 if matching_pattern == "connected_address":
3726 if matching_address and conn.getpeername() != matching_address:
3727 return False
3728 elif matching_pattern == "configured_address":
3729 if matching_address and conn.host != matching_address:
3730 return False
3731 elif matching_pattern == "notification_hash":
3732 if (
3733 matching_notification_hash is not None
3734 and conn.maintenance_notification_hash != matching_notification_hash
3735 ):
3736 return False
3737 return True
3739 def update_connection_settings(
3740 self,
3741 conn: "MaintNotificationsAbstractConnection",
3742 state: Optional["MaintenanceState"] = None,
3743 maintenance_notification_hash: Optional[int] = None,
3744 host_address: Optional[str] = None,
3745 relaxed_timeout: Optional[float] = None,
3746 update_notification_hash: bool = False,
3747 reset_host_address: bool = False,
3748 reset_relaxed_timeout: bool = False,
3749 ):
3750 """
3751 Update the settings for a single connection.
3752 """
3753 if state:
3754 self._complete_maintenance_taken_over_by_handoff(conn, state)
3755 conn.maintenance_state = state
3757 if update_notification_hash:
3758 # update the notification hash only if requested
3759 conn.maintenance_notification_hash = maintenance_notification_hash
3761 if host_address is not None:
3762 conn.set_tmp_settings(tmp_host_address=host_address)
3764 if relaxed_timeout is not None:
3765 conn.set_tmp_settings(tmp_relaxed_timeout=relaxed_timeout)
3767 if reset_relaxed_timeout or reset_host_address:
3768 conn.reset_tmp_settings(
3769 reset_host_address=reset_host_address,
3770 reset_relaxed_timeout=reset_relaxed_timeout,
3771 )
3773 conn.update_current_socket_timeout(relaxed_timeout)
3775 def _complete_maintenance_taken_over_by_handoff(
3776 self, conn: "MaintNotificationsAbstractConnection", state: "MaintenanceState"
3777 ) -> None:
3778 """
3779 Report the MAINTENANCE relaxation of a connection a handoff is taking
3780 over as completed. The connection's completion notification is skipped
3781 while it is MOVING, and the handoff's own cleanup restores it without
3782 looking at what it superseded, so this is the only point at which the
3783 pair opened by the start event can be closed.
3784 """
3785 if (
3786 state is not MaintenanceState.MOVING
3787 or conn.maintenance_state is not MaintenanceState.MAINTENANCE
3788 or conn.maint_notifications_config is None
3789 ):
3790 return
3791 _dispatch_maintenance_event(
3792 conn.maint_notifications_config,
3793 MaintenanceCompletedEvent(
3794 connection_pool=self,
3795 connection=conn,
3796 state=MaintenanceState.MAINTENANCE,
3797 notification=None,
3798 config=conn.maint_notifications_config,
3799 ),
3800 )
3802 def update_connections_settings(
3803 self,
3804 state: Optional["MaintenanceState"] = None,
3805 maintenance_notification_hash: Optional[int] = None,
3806 host_address: Optional[str] = None,
3807 relaxed_timeout: Optional[float] = None,
3808 matching_address: Optional[str] = None,
3809 matching_notification_hash: Optional[int] = None,
3810 matching_pattern: Literal[
3811 "connected_address", "configured_address", "notification_hash"
3812 ] = "connected_address",
3813 update_notification_hash: bool = False,
3814 reset_host_address: bool = False,
3815 reset_relaxed_timeout: bool = False,
3816 include_free_connections: bool = True,
3817 ):
3818 """
3819 Update the settings for all matching connections in the pool.
3821 This method does not create new connections.
3822 This method does not affect the connection kwargs.
3824 :param state: The maintenance state to set for the connection.
3825 :param maintenance_notification_hash: The hash of the maintenance notification
3826 to set for the connection.
3827 :param host_address: The host address to set for the connection.
3828 :param relaxed_timeout: The relaxed timeout to set for the connection.
3829 :param matching_address: The address to match for the connection.
3830 :param matching_notification_hash: The notification hash to match for the connection.
3831 :param matching_pattern: The pattern to match for the connection.
3832 :param update_notification_hash: Whether to update the notification hash for the connection.
3833 :param reset_host_address: Whether to reset the host address to the original address.
3834 :param reset_relaxed_timeout: Whether to reset the relaxed timeout to the original timeout.
3835 :param include_free_connections: Whether to include free/available connections.
3836 """
3837 with self._get_pool_lock():
3838 for conn in self._get_in_use_connections():
3839 if self._should_update_connection(
3840 conn,
3841 matching_pattern,
3842 matching_address,
3843 matching_notification_hash,
3844 ):
3845 self.update_connection_settings(
3846 conn,
3847 state=state,
3848 maintenance_notification_hash=maintenance_notification_hash,
3849 host_address=host_address,
3850 relaxed_timeout=relaxed_timeout,
3851 update_notification_hash=update_notification_hash,
3852 reset_host_address=reset_host_address,
3853 reset_relaxed_timeout=reset_relaxed_timeout,
3854 )
3856 if include_free_connections:
3857 for conn in self._get_free_connections():
3858 if self._should_update_connection(
3859 conn,
3860 matching_pattern,
3861 matching_address,
3862 matching_notification_hash,
3863 ):
3864 self.update_connection_settings(
3865 conn,
3866 state=state,
3867 maintenance_notification_hash=maintenance_notification_hash,
3868 host_address=host_address,
3869 relaxed_timeout=relaxed_timeout,
3870 update_notification_hash=update_notification_hash,
3871 reset_host_address=reset_host_address,
3872 reset_relaxed_timeout=reset_relaxed_timeout,
3873 )
3875 def update_connection_kwargs(
3876 self,
3877 **kwargs,
3878 ):
3879 """
3880 Update the connection kwargs for all future connections.
3882 This method updates the connection kwargs for all future connections created by the pool.
3883 Existing connections are not affected.
3884 """
3885 self.connection_kwargs.update(kwargs)
3887 def update_active_connections_for_reconnect(
3888 self,
3889 moving_address_src: Optional[str] = None,
3890 ):
3891 """
3892 Mark all active connections for reconnect.
3893 This is used when a cluster node is migrated to a different address.
3895 :param moving_address_src: The address of the node that is being moved.
3896 """
3897 debug = logger.isEnabledFor(logging.DEBUG)
3898 with self._get_pool_lock():
3899 for conn in self._get_in_use_connections():
3900 if self._should_update_connection(
3901 conn, "connected_address", moving_address_src
3902 ):
3903 if debug:
3904 logger.debug(
3905 f"Marking active connection for reconnect: {conn}, "
3906 f"{conn.extract_connection_details()}"
3907 )
3908 conn.mark_for_reconnect()
3910 def disconnect_free_connections(
3911 self,
3912 moving_address_src: Optional[str] = None,
3913 ):
3914 """
3915 Disconnect all free/available connections.
3916 This is used when a cluster node is migrated to a different address.
3918 :param moving_address_src: The address of the node that is being moved.
3919 """
3920 debug = logger.isEnabledFor(logging.DEBUG)
3921 with self._get_pool_lock():
3922 for conn in self._get_free_connections():
3923 if self._should_update_connection(
3924 conn, "connected_address", moving_address_src
3925 ):
3926 if debug:
3927 logger.debug(
3928 f"Disconnecting free connection: {conn}, "
3929 f"{conn.extract_connection_details()}"
3930 )
3931 conn.disconnect()
3934class ConnectionPool(MaintNotificationsAbstractConnectionPool, ConnectionPoolInterface):
3935 """
3936 Create a connection pool. ``If max_connections`` is set, then this
3937 object raises :py:class:`~redis.exceptions.ConnectionError` when the pool's
3938 limit is reached.
3940 By default, TCP connections are created unless ``connection_class``
3941 is specified. Use class:`.UnixDomainSocketConnection` for
3942 unix sockets.
3943 :py:class:`~redis.SSLConnection` can be used for SSL enabled connections.
3945 If ``maint_notifications_config`` is provided, the connection pool will support
3946 maintenance notifications.
3947 Maintenance notifications are supported only with RESP3.
3948 If the ``maint_notifications_config`` is not provided but the ``protocol`` is 3,
3949 the maintenance notifications will be enabled by default.
3951 If ``metadata_resolver`` is provided, it decides which commands are eligible for
3952 client-side caching - see `redis.commands.metadata.MetadataResolver`. It is handed to the
3953 cache configuration, so one resolver can serve cache eligibility and cluster routing
3954 alike. Defaults to the static command metadata this library ships, which the cache
3955 configuration resolves through on its own. A resolver built from a live ``COMMAND`` reply
3956 is a snapshot of the server it was read from, so give each pool its own rather than
3957 sharing one across pools on different servers.
3959 Any additional keyword arguments are passed to the constructor of
3960 ``connection_class``.
3961 """
3963 @classmethod
3964 def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
3965 """
3966 Return a connection pool configured from the given URL.
3968 For example::
3970 redis://[[username]:[password]]@localhost:6379/0
3971 rediss://[[username]:[password]]@localhost:6379/0
3972 unix://[username@]/path/to/socket.sock?db=0[&password=password]
3974 Three URL schemes are supported:
3976 - `redis://` creates a TCP socket connection. See more at:
3977 <https://www.iana.org/assignments/uri-schemes/prov/redis>
3978 - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
3979 <https://www.iana.org/assignments/uri-schemes/prov/rediss>
3980 - ``unix://``: creates a Unix Domain Socket connection.
3982 The username, password, hostname and path are passed through
3983 urllib.parse.unquote in order to replace any percent-encoded values
3984 with their corresponding characters. Querystring values are decoded
3985 by urllib.parse.parse_qs and are not unquoted again.
3987 There are several ways to specify a database number. The first value
3988 found will be used:
3990 1. A ``db`` querystring option, e.g. redis://localhost?db=0
3991 2. If using the redis:// or rediss:// schemes, the path argument
3992 of the url, e.g. redis://localhost/0
3993 3. A ``db`` keyword argument to this function.
3995 If none of these options are specified, the default db=0 is used.
3997 All querystring options are cast to their appropriate Python types.
3998 Boolean arguments can be specified with string values "True"/"False"
3999 or "Yes"/"No". Values that cannot be properly cast cause a
4000 ``ValueError`` to be raised. Once parsed, the querystring arguments
4001 and keyword arguments are passed to the ``ConnectionPool``'s
4002 class initializer. In the case of conflicting arguments, querystring
4003 arguments always win.
4004 """
4005 url_options = parse_url(url)
4007 if "connection_class" in kwargs:
4008 url_options["connection_class"] = kwargs["connection_class"]
4010 kwargs.update(url_options)
4011 return cls(**kwargs)
4013 def __init__(
4014 self,
4015 connection_class=Connection,
4016 max_connections: Optional[int] = None,
4017 cache_factory: Optional[CacheFactoryInterface] = None,
4018 maint_notifications_config: Optional[MaintNotificationsConfig] = None,
4019 metadata_resolver: Optional[MetadataResolver] = None,
4020 **connection_kwargs,
4021 ):
4022 max_connections = max_connections or 100
4023 if not isinstance(max_connections, int) or max_connections < 0:
4024 raise ValueError('"max_connections" must be a positive integer')
4026 self.connection_class = connection_class
4027 self._connection_kwargs = connection_kwargs
4028 self.max_connections = max_connections
4029 self.cache = None
4030 self._cache_factory = cache_factory
4031 self.metadata_resolver = metadata_resolver
4033 try:
4034 supports_maint_notifications = issubclass(
4035 connection_class, MaintNotificationsAbstractConnection
4036 )
4037 is_unix_domain_socket_connection = issubclass(
4038 connection_class, UnixDomainSocketConnection
4039 )
4040 except TypeError:
4041 supports_maint_notifications = False
4042 is_unix_domain_socket_connection = False
4044 if is_unix_domain_socket_connection or not supports_maint_notifications:
4045 if (
4046 maint_notifications_config
4047 and maint_notifications_config.enabled is True
4048 ):
4049 raise RedisError(
4050 "Maintenance notifications are not supported with "
4051 f"{connection_class}"
4052 )
4053 maint_notifications_config = MaintNotificationsConfig(enabled=False)
4055 self._event_dispatcher = self._connection_kwargs.get("event_dispatcher", None)
4056 if self._event_dispatcher is None:
4057 self._event_dispatcher = EventDispatcher()
4059 if connection_kwargs.get("cache_config") or connection_kwargs.get("cache"):
4060 if not check_protocol_version(self._connection_kwargs.get("protocol"), 3):
4061 raise RedisError("Client caching is only supported with RESP version 3")
4063 cache = self._connection_kwargs.get("cache")
4064 cache_config = self._connection_kwargs.get("cache_config")
4066 # Hand the client-level metadata resolver to the cache configuration, which is
4067 # where command eligibility is decided, so routing and caching read the same
4068 # records. Skipped when no resolver was configured, which leaves ``CacheConfig``
4069 # on the static default it builds for itself.
4070 #
4071 # Done on a copy rather than on the caller's object: a ``CacheConfig`` carries
4072 # only sizing and eviction settings, so reusing one across clients is reasonable,
4073 # and writing the resolver into it would give every one of them whichever
4074 # resolver was injected last. Every other setting is read-only after
4075 # construction, so the copy diverges from the caller's object in nothing but the
4076 # resolver - and a later ``set_metadata_resolver`` on the original does not reach
4077 # this pool, which is the intended direction: a pool decides eligibility by the
4078 # resolver its client was built with. Note that the ``cache=`` /
4079 # ``cache_factory=`` path below cannot copy, and so does write into the caller's
4080 # configuration; ``CacheConfig.set_metadata_resolver`` documents the difference.
4081 #
4082 # Guarded by ``isinstance`` rather than done through
4083 # ``CacheConfigurationInterface``: that ABC is public and implemented by third
4084 # parties, so a custom configuration keeps its own eligibility logic.
4085 if (
4086 metadata_resolver is not None
4087 and cache is None
4088 and self._cache_factory is None
4089 and isinstance(cache_config, CacheConfig)
4090 ):
4091 cache_config = copy.copy(cache_config)
4092 cache_config.set_metadata_resolver(metadata_resolver)
4094 if cache is not None:
4095 if not isinstance(cache, CacheInterface):
4096 raise ValueError("Cache must implement CacheInterface")
4098 self.cache = cache
4099 else:
4100 if self._cache_factory is not None:
4101 self.cache = CacheProxy(self._cache_factory.get_cache())
4102 else:
4103 self.cache = CacheFactory(cache_config).get_cache()
4105 # A caller who supplied a whole cache - ``cache=`` or ``cache_factory=`` - owns
4106 # the configuration inside it, and it cannot be swapped without rebuilding the
4107 # cache, so the resolver is set on it in place. This is the one path that writes
4108 # into the caller's configuration rather than into a copy of it, because a cache
4109 # reads its configuration on every lookup and ``CacheInterface`` exposes no way to
4110 # hand it a different one. Sharing one cache object across clients already shares
4111 # its entries, which couples them far more tightly than its eligibility does, so
4112 # the asymmetry with the ``cache_config=`` copy above is documented on
4113 # ``CacheConfig.set_metadata_resolver`` rather than removed.
4114 if metadata_resolver is not None and (
4115 cache is not None or self._cache_factory is not None
4116 ):
4117 own_config = self.cache.config
4118 if isinstance(own_config, CacheConfig):
4119 own_config.set_metadata_resolver(metadata_resolver)
4121 init_csc_items()
4122 register_csc_items_callback(
4123 callback=lambda: self.cache.size,
4124 pool_name=get_pool_name(self),
4125 )
4127 connection_kwargs.pop("cache", None)
4128 connection_kwargs.pop("cache_config", None)
4130 # Resolve the HIMPORT registry. A pre-built ``himport_registry`` (shared, e.g.
4131 # from the cluster client) takes precedence; otherwise build a fresh empty one.
4132 # A registry always exists so runtime ``himport_prepare`` mutates a single object
4133 # every connection already shares. The object stays in ``connection_kwargs`` so
4134 # it reaches every connection. It is injected unconditionally (like other
4135 # auto-added pool kwargs), so a custom ``connection_class`` must accept
4136 # ``**kwargs`` (or a ``himport_registry`` parameter), as built-ins do.
4137 himport_registry = connection_kwargs.get("himport_registry")
4138 if himport_registry is None:
4139 himport_registry = HImportRegistry()
4140 connection_kwargs["himport_registry"] = himport_registry
4141 self.himport_registry = himport_registry
4143 # a lock to protect the critical section in _checkpid().
4144 # this lock is acquired when the process id changes, such as
4145 # after a fork. during this time, multiple threads in the child
4146 # process could attempt to acquire this lock. the first thread
4147 # to acquire the lock will reset the data structures and lock
4148 # object of this pool. subsequent threads acquiring this lock
4149 # will notice the first thread already did the work and simply
4150 # release the lock.
4152 self._fork_lock = threading.RLock()
4153 self._lock = threading.RLock()
4155 # Generate unique pool ID for observability (matches go-redis behavior)
4156 self._pool_id = secrets.token_hex(4)
4158 MaintNotificationsAbstractConnectionPool.__init__(
4159 self,
4160 maint_notifications_config=maint_notifications_config,
4161 **connection_kwargs,
4162 )
4164 self.reset()
4166 # Keys that should be redacted in __repr__ to avoid exposing sensitive information
4167 SENSITIVE_REPR_KEYS = frozenset(
4168 {
4169 "password",
4170 "username",
4171 "ssl_password",
4172 "credential_provider",
4173 }
4174 )
4176 # Internal plumbing kwargs omitted from __repr__ (not user-facing config).
4177 OMIT_REPR_KEYS = frozenset({"himport_registry"})
4179 def __repr__(self) -> str:
4180 conn_kwargs = ",".join(
4181 [
4182 f"{k}={'<REDACTED>' if k in self.SENSITIVE_REPR_KEYS else v}"
4183 for k, v in self.connection_kwargs.items()
4184 if k not in self.OMIT_REPR_KEYS
4185 ]
4186 )
4187 return (
4188 f"<{self.__class__.__module__}.{self.__class__.__name__}"
4189 f"(<{self.connection_class.__module__}.{self.connection_class.__name__}"
4190 f"({conn_kwargs})>)>"
4191 )
4193 @property
4194 def connection_kwargs(self) -> Dict[str, Any]:
4195 return self._connection_kwargs
4197 @connection_kwargs.setter
4198 def connection_kwargs(self, value: Dict[str, Any]):
4199 self._connection_kwargs = value
4201 def get_protocol(self):
4202 """
4203 Returns:
4204 The RESP protocol version, or ``None`` if the protocol is not specified,
4205 in which case the server default will be used.
4206 """
4207 return self.connection_kwargs.get("protocol", None)
4209 def reset(self) -> None:
4210 is_fork = hasattr(self, "pid") and self.pid != os.getpid()
4211 if is_fork:
4212 # Inherited connections were counted by the parent, not this process.
4213 self._pool_id = secrets.token_hex(4)
4214 # A parent thread may have held the lock at fork time, and the
4215 # handler reset below takes it to revert an active MOVING.
4216 self._lock = threading.RLock()
4217 # The cached entries were filled on the parent's connections: their
4218 # invalidations go to the parent, and a hit would read the
4219 # parent's socket.
4220 if self.cache is not None:
4221 self.cache.flush()
4223 # Record metrics for connections being removed before clearing
4224 # (only if attributes exist - they won't during __init__)
4225 if (
4226 not is_fork
4227 and hasattr(self, "_available_connections")
4228 and hasattr(self, "_in_use_connections")
4229 ):
4230 with self._lock:
4231 idle_count = len(self._available_connections)
4232 in_use_count = len(self._in_use_connections)
4233 if idle_count > 0 or in_use_count > 0:
4234 pool_name = get_pool_name(self)
4235 if idle_count > 0:
4236 record_connection_count(
4237 pool_name=pool_name,
4238 connection_state=ConnectionState.IDLE,
4239 counter=-idle_count,
4240 )
4241 if in_use_count > 0:
4242 record_connection_count(
4243 pool_name=pool_name,
4244 connection_state=ConnectionState.USED,
4245 counter=-in_use_count,
4246 )
4248 self._created_connections = 0
4249 self._available_connections = []
4250 self._in_use_connections = set()
4252 self._on_reset_after_fork()
4254 # this must be the last operation in this method. while reset() is
4255 # called when holding _fork_lock, other threads in this process
4256 # can call _checkpid() which compares self.pid and os.getpid() without
4257 # holding any lock (for performance reasons). keeping this assignment
4258 # as the last operation ensures that those other threads will also
4259 # notice a pid difference and block waiting for the first thread to
4260 # release _fork_lock. when each of these threads eventually acquire
4261 # _fork_lock, they will notice that another thread already called
4262 # reset() and they will immediately release _fork_lock and continue on.
4263 self.pid = os.getpid()
4265 def __del__(self) -> None:
4266 """Clean up connection pool and record metrics when garbage collected."""
4267 try:
4268 if getattr(self, "pid", None) != os.getpid():
4269 return
4270 if not hasattr(self, "_available_connections") or not hasattr(
4271 self, "_in_use_connections"
4272 ):
4273 return
4274 # Record metrics for all connections being removed
4275 idle_count = len(self._available_connections)
4276 in_use_count = len(self._in_use_connections)
4277 if idle_count > 0 or in_use_count > 0:
4278 pool_name = get_pool_name(self)
4279 if idle_count > 0:
4280 record_connection_count(
4281 pool_name=pool_name,
4282 connection_state=ConnectionState.IDLE,
4283 counter=-idle_count,
4284 )
4285 if in_use_count > 0:
4286 record_connection_count(
4287 pool_name=pool_name,
4288 connection_state=ConnectionState.USED,
4289 counter=-in_use_count,
4290 )
4291 except Exception:
4292 pass
4294 def _checkpid(self) -> None:
4295 # _checkpid() attempts to keep ConnectionPool fork-safe on modern
4296 # systems. this is called by all ConnectionPool methods that
4297 # manipulate the pool's state such as get_connection() and release().
4298 #
4299 # _checkpid() determines whether the process has forked by comparing
4300 # the current process id to the process id saved on the ConnectionPool
4301 # instance. if these values are the same, _checkpid() simply returns.
4302 #
4303 # when the process ids differ, _checkpid() assumes that the process
4304 # has forked and that we're now running in the child process. the child
4305 # process cannot use the parent's file descriptors (e.g., sockets).
4306 # therefore, when _checkpid() sees the process id change, it calls
4307 # reset() in order to reinitialize the child's ConnectionPool. this
4308 # will cause the child to make all new connection objects.
4309 #
4310 # _checkpid() is protected by self._fork_lock to ensure that multiple
4311 # threads in the child process do not call reset() multiple times.
4312 #
4313 # there is an extremely small chance this could fail in the following
4314 # scenario:
4315 # 1. process A calls _checkpid() for the first time and acquires
4316 # self._fork_lock.
4317 # 2. while holding self._fork_lock, process A forks (the fork()
4318 # could happen in a different thread owned by process A)
4319 # 3. process B (the forked child process) inherits the
4320 # ConnectionPool's state from the parent. that state includes
4321 # a locked _fork_lock. process B will not be notified when
4322 # process A releases the _fork_lock and will thus never be
4323 # able to acquire the _fork_lock.
4324 #
4325 # to mitigate this possible deadlock, _checkpid() will only wait 5
4326 # seconds to acquire _fork_lock. if _fork_lock cannot be acquired in
4327 # that time it is assumed that the child is deadlocked and a
4328 # redis.ChildDeadlockedError error is raised.
4329 if self.pid != os.getpid():
4330 acquired = self._fork_lock.acquire(timeout=5)
4331 if not acquired:
4332 raise ChildDeadlockedError
4333 # reset() the instance for the new process if another thread
4334 # hasn't already done so
4335 try:
4336 if self.pid != os.getpid():
4337 self.reset()
4338 finally:
4339 self._fork_lock.release()
4341 @deprecated_args(
4342 args_to_warn=["*"],
4343 reason="Use get_connection() without args instead",
4344 version="5.3.0",
4345 )
4346 def get_connection(self, command_name=None, *keys, **options) -> "Connection":
4347 "Get a connection from the pool"
4349 # Start timing for observability
4350 self._checkpid()
4351 is_created = False
4353 with self._lock:
4354 try:
4355 connection = self._available_connections.pop()
4356 except IndexError:
4357 # Start timing for observability
4358 start_time_created = time.monotonic()
4360 connection = self.make_connection()
4361 is_created = True
4362 self._in_use_connections.add(connection)
4364 # Record state transition for observability
4365 pool_name = get_pool_name(self)
4366 if is_created:
4367 # New connection created and acquired: just USED +1
4368 # (connection was never idle in the pool)
4369 record_connection_count(
4370 pool_name=pool_name,
4371 connection_state=ConnectionState.USED,
4372 counter=1,
4373 )
4374 else:
4375 # Existing connection acquired from pool: IDLE -> USED
4376 record_connection_count(
4377 pool_name=pool_name,
4378 connection_state=ConnectionState.IDLE,
4379 counter=-1,
4380 )
4381 record_connection_count(
4382 pool_name=pool_name,
4383 connection_state=ConnectionState.USED,
4384 counter=1,
4385 )
4387 try:
4388 self.ensure_connection(connection)
4389 except BaseException:
4390 # release the connection back to the pool so that we don't
4391 # leak it
4392 self.release(connection)
4393 raise
4395 if is_created:
4396 record_connection_create_time(
4397 connection_pool=self,
4398 duration_seconds=time.monotonic() - start_time_created,
4399 )
4401 return connection
4403 def ensure_connection(self, connection: "Connection") -> None:
4404 """Ensure that the connection object is connected and valid"""
4405 connection.connect()
4406 # connections that the pool provides should be ready to send
4407 # a command. if not, the connection was either returned to the
4408 # pool before all data has been read or the socket has been
4409 # closed. either way, reconnect and verify everything is good.
4410 # With maintenance notifications enabled the pending data may be
4411 # push notifications that have to be applied rather than a reason
4412 # to reconnect; reading them is what tells the two apart, and it
4413 # raises for a socket the server has closed in the meantime.
4414 try:
4415 if connection.can_read():
4416 if self.maint_notifications_enabled():
4417 connection.handle_pending_push_notifications()
4418 elif self.cache is None:
4419 raise ConnectionError("Connection has data")
4420 except (ConnectionError, TimeoutError, OSError):
4421 connection.disconnect()
4422 connection.connect()
4423 if (
4424 connection.can_read()
4425 and self.cache is None
4426 and not self.maint_notifications_enabled()
4427 ):
4428 raise ConnectionError("Connection not ready")
4430 def get_encoder(self) -> Encoder:
4431 "Return an encoder based on encoding settings"
4432 kwargs = self.connection_kwargs
4433 return Encoder(
4434 encoding=kwargs.get("encoding", "utf-8"),
4435 encoding_errors=kwargs.get("encoding_errors", "strict"),
4436 decode_responses=kwargs.get("decode_responses", False),
4437 )
4439 def make_connection(self) -> "ConnectionInterface":
4440 "Create a new connection"
4441 if self._created_connections >= self.max_connections:
4442 raise MaxConnectionsError("Too many connections")
4444 kwargs = dict(self.connection_kwargs)
4446 # Create the connection first, then record metrics only on success
4447 if self.cache is not None:
4448 connection = CacheProxyConnection(
4449 self.connection_class(**kwargs), self.cache, self._lock
4450 )
4451 else:
4452 connection = self.connection_class(**kwargs)
4454 # Only a connection that exists can be released, so count it here.
4455 self._created_connections += 1
4457 return connection
4459 def release(self, connection: "Connection") -> None:
4460 "Releases the connection back to the pool"
4461 self._checkpid()
4462 # Run the listeners, such as a deferred AUTH, while the connection is
4463 # still in use, so no other thread can take it, and outside the pool
4464 # lock, so their I/O does not block the pool. A listener error is
4465 # raised once the connection is back.
4466 listener_error = None
4467 if connection in self._in_use_connections and self.owns_connection(connection):
4468 try:
4469 self._event_dispatcher.dispatch(
4470 AfterConnectionReleasedEvent(connection)
4471 )
4472 except BaseException as e:
4473 listener_error = e
4474 try:
4475 with self._lock:
4476 try:
4477 self._in_use_connections.remove(connection)
4478 except KeyError:
4479 # Gracefully fail when a connection is returned to this pool
4480 # that the pool doesn't actually own
4481 return
4483 if self.owns_connection(connection):
4484 if connection.should_reconnect():
4485 if logger.isEnabledFor(logging.DEBUG):
4486 logger.debug(
4487 "Disconnecting released connection marked for "
4488 f"reconnect: {connection}, "
4489 f"{connection.extract_connection_details()}"
4490 )
4491 connection.disconnect()
4492 self._available_connections.append(connection)
4494 # Record state transition: USED -> IDLE
4495 pool_name = get_pool_name(self)
4496 record_connection_count(
4497 pool_name=pool_name,
4498 connection_state=ConnectionState.USED,
4499 counter=-1,
4500 )
4501 record_connection_count(
4502 pool_name=pool_name,
4503 connection_state=ConnectionState.IDLE,
4504 counter=1,
4505 )
4506 else:
4507 # Pool doesn't own this connection, do not add it back
4508 # to the pool.
4509 connection.disconnect()
4510 # Subclasses such as SentinelConnectionPool can override
4511 # owns_connection() with a comparison different from local PID
4512 # ownership. When such a subclass rejects a connection, also require
4513 # connection.pid == self.pid before reclaiming its slot.
4514 if connection.pid == self.pid:
4515 self._created_connections -= 1
4516 # The connection was checked out by this process, so
4517 # decrement USED, which was counted in get_connection().
4518 # Connections inherited across a fork are skipped here,
4519 # their accounting belongs to the parent process.
4520 record_connection_count(
4521 pool_name=get_pool_name(self),
4522 connection_state=ConnectionState.USED,
4523 counter=-1,
4524 )
4525 return
4526 finally:
4527 if listener_error is not None:
4528 raise listener_error
4530 def owns_connection(self, connection: "Connection") -> int:
4531 return connection.pid == self.pid
4533 def disconnect(self, inuse_connections: bool = True) -> None:
4534 """
4535 Disconnects connections in the pool
4537 If ``inuse_connections`` is True, disconnect connections that are
4538 currently in use, potentially by other threads. Otherwise only disconnect
4539 connections that are idle in the pool.
4540 """
4541 self._checkpid()
4542 with self._lock:
4543 if inuse_connections:
4544 connections = chain(
4545 self._available_connections, self._in_use_connections
4546 )
4547 else:
4548 connections = self._available_connections
4550 for connection in connections:
4551 connection.disconnect()
4553 def close(self) -> None:
4554 """Close the pool, disconnecting all connections"""
4555 # A forked child must not touch the handler state inherited from the
4556 # parent: reset it first (the lock may be held by a parent thread).
4557 self._checkpid()
4558 try:
4559 self._on_close()
4560 finally:
4561 self.disconnect()
4563 def __enter__(self: _CP) -> _CP:
4564 return self
4566 def __exit__(self, exc_type, exc_value, traceback) -> None:
4567 self.close()
4569 def set_retry(self, retry: Retry) -> None:
4570 self.connection_kwargs.update({"retry": retry})
4571 for conn in self._available_connections:
4572 conn.retry = retry
4573 for conn in self._in_use_connections:
4574 conn.retry = retry
4576 def re_auth_callback(self, token: TokenInterface):
4577 """
4578 Send AUTH with ``token`` on every connected free connection, and defer
4579 it to the next release of every in-use one.
4581 A free connection whose AUTH fails keeps ``token`` pending, like an
4582 in-use one. The first error is raised after every connection is
4583 handled, an ``AuthenticationError`` first.
4584 """
4585 auth_error = None
4586 first_error = None
4587 with self._lock:
4588 # Send every AUTH before reading any reply, so the pool lock is
4589 # held for about one round trip instead of one per connection
4590 sent = []
4591 # Replies read so far, in send order
4592 done = 0
4593 try:
4594 for conn in self._available_connections:
4595 if not conn.is_connected:
4596 # It authenticates with current credentials when it
4597 # connects. Sending AUTH would connect it here, under the
4598 # pool lock.
4599 continue
4600 # Pending until the AUTH below succeeds
4601 conn.set_re_auth_token(token)
4602 try:
4603 conn.retry.call_with_retry(
4604 lambda: conn.send_command(
4605 "AUTH", token.try_get("oid"), token.get_value()
4606 ),
4607 lambda error: self._mock(error),
4608 )
4609 except Exception as e:
4610 if first_error is None:
4611 first_error = e
4612 else:
4613 sent.append(conn)
4614 for conn in sent:
4615 try:
4616 conn.retry.call_with_retry(
4617 lambda: conn.read_response(),
4618 lambda error: self._mock(error),
4619 is_retryable=lambda error: not isinstance(
4620 error, AuthenticationError
4621 ),
4622 )
4623 except AuthenticationError as e:
4624 if auth_error is None:
4625 auth_error = e
4626 except Exception as e:
4627 if first_error is None:
4628 first_error = e
4629 else:
4630 conn.set_re_auth_token(None)
4631 done += 1
4632 except BaseException:
4633 # Interrupted, for example cancelled: the replies not read yet
4634 # would be read by the next command on those connections
4635 for conn in sent[done:]:
4636 conn.disconnect()
4637 raise
4638 for conn in self._in_use_connections:
4639 conn.set_re_auth_token(token)
4640 if auth_error is not None:
4641 raise auth_error
4642 if first_error is not None:
4643 raise first_error
4645 def _get_pool_lock(self):
4646 return self._lock
4648 def _get_free_connections(self):
4649 with self._lock:
4650 return list(self._available_connections)
4652 def _get_in_use_connections(self):
4653 with self._lock:
4654 return set(self._in_use_connections)
4656 def _mock(self, error: RedisError):
4657 """
4658 Dummy functions, needs to be passed as error callback to retry object.
4659 :param error:
4660 :return:
4661 """
4662 pass
4664 def get_connection_count(self) -> List[tuple[int, dict]]:
4665 from redis.observability.attributes import get_pool_name
4667 attributes = AttributeBuilder.build_base_attributes()
4668 attributes[DB_CLIENT_CONNECTION_POOL_NAME] = get_pool_name(self)
4669 free_connections_attributes = attributes.copy()
4670 in_use_connections_attributes = attributes.copy()
4672 free_connections_attributes[DB_CLIENT_CONNECTION_STATE] = (
4673 ConnectionState.IDLE.value
4674 )
4675 in_use_connections_attributes[DB_CLIENT_CONNECTION_STATE] = (
4676 ConnectionState.USED.value
4677 )
4679 return [
4680 (len(self._get_free_connections()), free_connections_attributes),
4681 (len(self._get_in_use_connections()), in_use_connections_attributes),
4682 ]
4685class BlockingConnectionPool(ConnectionPool):
4686 """
4687 Thread-safe blocking connection pool::
4689 >>> from redis import Redis, BlockingConnectionPool
4690 >>> client = Redis(connection_pool=BlockingConnectionPool())
4692 It performs the same function as the default
4693 :py:class:`~redis.connection.ConnectionPool` implementation, in that,
4694 it maintains a pool of reusable connections that can be shared by
4695 multiple redis clients (safely across threads if required).
4697 The difference is that, in the event that a client tries to get a
4698 connection from the pool when all of connections are in use, rather than
4699 raising a :py:class:`~redis.exceptions.MaxConnectionsError` (as the default
4700 :py:class:`~redis.connection.ConnectionPool` implementation does), it
4701 makes the client wait ("blocks") for a specified number of seconds until
4702 a connection becomes available.
4704 Use ``max_connections`` to increase / decrease the pool size::
4706 >>> pool = BlockingConnectionPool(max_connections=10)
4708 Use ``timeout`` to tell it either how many seconds to wait for a connection
4709 to become available, or to block forever:
4711 >>> # Block forever.
4712 >>> pool = BlockingConnectionPool(timeout=None)
4714 >>> # Raise a ``ConnectionError`` after five seconds if a connection is
4715 >>> # not available.
4716 >>> pool = BlockingConnectionPool(timeout=5)
4717 """
4719 def __init__(
4720 self,
4721 max_connections=50,
4722 timeout=20,
4723 connection_class=Connection,
4724 queue_class=LifoQueue,
4725 **connection_kwargs,
4726 ):
4727 self.queue_class = queue_class
4728 self.timeout = timeout
4729 self._in_maintenance = False
4730 super().__init__(
4731 connection_class=connection_class,
4732 max_connections=max_connections,
4733 **connection_kwargs,
4734 )
4736 def reset(self):
4737 is_fork = hasattr(self, "pid") and self.pid != os.getpid()
4738 if is_fork:
4739 # Inherited connections were counted by the parent, not this process.
4740 self._pool_id = secrets.token_hex(4)
4741 # A parent thread may have held the lock at fork time, and the
4742 # handler reset below takes it to revert an active MOVING.
4743 self._lock = threading.RLock()
4744 # The thread applying a MOVING in the parent does not exist here
4745 # to clear these, and a stale flag makes a checkout nest on the
4746 # lock and leak it.
4747 self._in_maintenance = False
4748 # The cached entries were filled on the parent's connections: their
4749 # invalidations go to the parent, and a hit would read the
4750 # parent's socket.
4751 if self.cache is not None:
4752 self.cache.flush()
4754 # Create and fill up a thread safe queue with ``None`` values.
4755 locked = False
4756 try:
4757 if self._in_maintenance:
4758 self._lock.acquire()
4759 locked = True
4761 # Record metrics for connections being removed before clearing
4762 # Note: Access pool.queue directly to avoid deadlock since we may
4763 # already hold self._lock (which is non-reentrant)
4764 if (
4765 not is_fork
4766 and hasattr(self, "_connections")
4767 and self._connections
4768 and hasattr(self, "pool")
4769 ):
4770 with self._lock:
4771 connections_in_queue = {conn for conn in self.pool.queue if conn}
4772 idle_count = len(connections_in_queue)
4773 in_use_count = len(self._connections) - idle_count
4774 if idle_count > 0 or in_use_count > 0:
4775 pool_name = get_pool_name(self)
4776 if idle_count > 0:
4777 record_connection_count(
4778 pool_name=pool_name,
4779 connection_state=ConnectionState.IDLE,
4780 counter=-idle_count,
4781 )
4782 if in_use_count > 0:
4783 record_connection_count(
4784 pool_name=pool_name,
4785 connection_state=ConnectionState.USED,
4786 counter=-in_use_count,
4787 )
4789 self.pool = self.queue_class(self.max_connections)
4790 while True:
4791 try:
4792 self.pool.put_nowait(None)
4793 except Full:
4794 break
4796 # Keep a list of actual connection instances so that we can
4797 # disconnect them later.
4798 self._connections = []
4799 finally:
4800 if locked:
4801 self._lock.release()
4803 self._on_reset_after_fork()
4805 # this must be the last operation in this method. while reset() is
4806 # called when holding _fork_lock, other threads in this process
4807 # can call _checkpid() which compares self.pid and os.getpid() without
4808 # holding any lock (for performance reasons). keeping this assignment
4809 # as the last operation ensures that those other threads will also
4810 # notice a pid difference and block waiting for the first thread to
4811 # release _fork_lock. when each of these threads eventually acquire
4812 # _fork_lock, they will notice that another thread already called
4813 # reset() and they will immediately release _fork_lock and continue on.
4814 self.pid = os.getpid()
4816 def __del__(self) -> None:
4817 """Clean up connection pool and record metrics when garbage collected."""
4818 try:
4819 if getattr(self, "pid", None) != os.getpid():
4820 return
4821 # Note: Access pool.queue directly to avoid potential deadlock
4822 # if GC runs while the lock is held by the same thread
4823 if (
4824 hasattr(self, "_connections")
4825 and self._connections
4826 and hasattr(self, "pool")
4827 ):
4828 connections_in_queue = {conn for conn in self.pool.queue if conn}
4829 idle_count = len(connections_in_queue)
4830 in_use_count = len(self._connections) - idle_count
4831 if idle_count > 0 or in_use_count > 0:
4832 pool_name = get_pool_name(self)
4833 if idle_count > 0:
4834 record_connection_count(
4835 pool_name=pool_name,
4836 connection_state=ConnectionState.IDLE,
4837 counter=-idle_count,
4838 )
4839 if in_use_count > 0:
4840 record_connection_count(
4841 pool_name=pool_name,
4842 connection_state=ConnectionState.USED,
4843 counter=-in_use_count,
4844 )
4845 except Exception:
4846 pass
4848 def make_connection(self):
4849 "Make a fresh connection."
4850 locked = False
4851 try:
4852 if self._in_maintenance:
4853 self._lock.acquire()
4854 locked = True
4856 if self.cache is not None:
4857 connection = CacheProxyConnection(
4858 self.connection_class(**self.connection_kwargs),
4859 self.cache,
4860 self._lock,
4861 )
4862 else:
4863 connection = self.connection_class(**self.connection_kwargs)
4864 self._connections.append(connection)
4866 return connection
4867 finally:
4868 if locked:
4869 self._lock.release()
4871 @deprecated_args(
4872 args_to_warn=["*"],
4873 reason="Use get_connection() without args instead",
4874 version="5.3.0",
4875 )
4876 def get_connection(self, command_name=None, *keys, **options):
4877 """
4878 Get a connection, blocking for ``self.timeout`` until a connection
4879 is available from the pool.
4881 If the connection returned is ``None`` then creates a new connection.
4882 Because we use a last-in first-out queue, the existing connections
4883 (having been returned to the pool after the initial ``None`` values
4884 were added) will be returned before ``None`` values. This means we only
4885 create new connections when we need to, i.e.: the actual number of
4886 connections will only increase in response to demand.
4887 """
4888 start_time_acquired = time.monotonic()
4889 # Make sure we haven't changed process.
4890 self._checkpid()
4891 is_created = False
4893 # Try and get a connection from the pool. If one isn't available within
4894 # self.timeout then raise a ``ConnectionError``.
4895 connection = None
4896 locked = False
4897 try:
4898 if self._in_maintenance:
4899 self._lock.acquire()
4900 locked = True
4901 try:
4902 connection = self.pool.get(block=True, timeout=self.timeout)
4903 except Empty:
4904 record_connection_timeout(pool_name=get_pool_name(self))
4905 # Note that this is not caught by the redis client and will be
4906 # raised unless handled by application code. If you want never to
4907 raise ConnectionError("No connection available.")
4909 # If the ``connection`` is actually ``None`` then that's a cue to make
4910 # a new connection to add to the pool.
4911 if connection is None:
4912 # Start timing for observability
4913 start_time_created = time.monotonic()
4914 try:
4915 connection = self.make_connection()
4916 except BaseException:
4917 # Hand the slot back, or the pool shrinks on every failure.
4918 try:
4919 self.pool.put_nowait(None)
4920 except Full:
4921 pass
4922 raise
4923 is_created = True
4924 finally:
4925 if locked:
4926 self._lock.release()
4928 # Record state transition for observability
4929 pool_name = get_pool_name(self)
4930 if is_created:
4931 # New connection created and acquired: just USED +1
4932 # (connection was never idle in the pool)
4933 record_connection_count(
4934 pool_name=pool_name,
4935 connection_state=ConnectionState.USED,
4936 counter=1,
4937 )
4938 else:
4939 # Existing connection acquired from pool: IDLE -> USED
4940 record_connection_count(
4941 pool_name=pool_name,
4942 connection_state=ConnectionState.IDLE,
4943 counter=-1,
4944 )
4945 record_connection_count(
4946 pool_name=pool_name,
4947 connection_state=ConnectionState.USED,
4948 counter=1,
4949 )
4951 try:
4952 self.ensure_connection(connection)
4953 except BaseException:
4954 # release the connection back to the pool so that we don't leak it
4955 self.release(connection)
4956 raise
4958 if is_created:
4959 record_connection_create_time(
4960 connection_pool=self,
4961 duration_seconds=time.monotonic() - start_time_created,
4962 )
4964 record_connection_wait_time(
4965 pool_name=pool_name,
4966 duration_seconds=time.monotonic() - start_time_acquired,
4967 )
4969 return connection
4971 def release(self, connection):
4972 "Releases the connection back to the pool."
4973 # Make sure we haven't changed process.
4974 self._checkpid()
4976 locked = False
4977 try:
4978 if self._in_maintenance:
4979 self._lock.acquire()
4980 locked = True
4981 if not self.owns_connection(connection):
4982 # pool doesn't own this connection. do not add it back
4983 # to the pool. instead add a None value which is a placeholder
4984 # that will cause the pool to recreate the connection if
4985 # its needed.
4986 connection.disconnect()
4987 self.pool.put_nowait(None)
4988 # Subclasses can override owns_connection() with a comparison
4989 # different from local PID ownership. When such a subclass
4990 # rejects a connection checked out by this process, stop
4991 # tracking it and decrement USED, which was counted in
4992 # get_connection(). Connections inherited across a fork are
4993 # skipped here, their accounting belongs to the parent process.
4994 if connection.pid == self.pid:
4995 try:
4996 self._connections.remove(connection)
4997 except ValueError:
4998 pass
4999 record_connection_count(
5000 pool_name=get_pool_name(self),
5001 connection_state=ConnectionState.USED,
5002 counter=-1,
5003 )
5004 return
5005 if connection.should_reconnect():
5006 if logger.isEnabledFor(logging.DEBUG):
5007 logger.debug(
5008 "Disconnecting released connection marked for reconnect: "
5009 f"{connection}, {connection.extract_connection_details()}"
5010 )
5011 connection.disconnect()
5012 # Put the connection back into the pool.
5013 pool_name = get_pool_name(self)
5014 try:
5015 self.pool.put_nowait(connection)
5017 # Record state transition: USED -> IDLE
5018 record_connection_count(
5019 pool_name=pool_name,
5020 connection_state=ConnectionState.USED,
5021 counter=-1,
5022 )
5023 record_connection_count(
5024 pool_name=pool_name,
5025 connection_state=ConnectionState.IDLE,
5026 counter=1,
5027 )
5028 except Full:
5029 pass
5030 finally:
5031 if locked:
5032 self._lock.release()
5034 def disconnect(self, inuse_connections: bool = True):
5035 """
5036 Disconnects either all connections in the pool or just the free connections.
5037 """
5038 self._checkpid()
5039 locked = False
5040 try:
5041 if self._in_maintenance:
5042 self._lock.acquire()
5043 locked = True
5045 if inuse_connections:
5046 connections = self._connections
5047 else:
5048 connections = self._get_free_connections()
5050 for connection in connections:
5051 connection.disconnect()
5052 finally:
5053 if locked:
5054 self._lock.release()
5056 def _get_free_connections(self):
5057 with self._lock:
5058 return {conn for conn in self.pool.queue if conn}
5060 def _get_in_use_connections(self):
5061 with self._lock:
5062 # free connections
5063 connections_in_queue = {conn for conn in self.pool.queue if conn}
5064 # in self._connections we keep all created connections
5065 # so the ones that are not in the queue are the in use ones
5066 return {
5067 conn for conn in self._connections if conn not in connections_in_queue
5068 }
5070 def set_in_maintenance(self, in_maintenance: bool):
5071 """
5072 Sets a flag that this Blocking ConnectionPool is in maintenance mode.
5074 This is used to prevent new connections from being created while we are in maintenance mode.
5075 The pool will be in maintenance mode only when we are processing a MOVING notification.
5076 """
5077 self._in_maintenance = in_maintenance
5080def __getattr__(name: str):
5081 """
5082 Serve the deprecated ``SYM_STAR`` and ``SYM_DOLLAR`` constants, warning on the way.
5084 A module attribute cannot be deprecated by decoration, so the constants are bound to
5085 private names above and resolved here instead - which is only reached because no module
5086 attribute of that name exists.
5087 """
5088 if name == "SYM_STAR":
5089 value = _DEPRECATED_SYM_STAR
5090 elif name == "SYM_DOLLAR":
5091 value = _DEPRECATED_SYM_DOLLAR
5092 else:
5093 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
5094 warn_deprecated(
5095 name,
5096 reason="Nothing in this library uses it any more",
5097 version="8.2.0",
5098 stacklevel=3,
5099 )
5100 return value