Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/client.py: 19%
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 logging
3import re
4import threading
5import time
6from functools import cached_property, lru_cache
7from itertools import chain
8from typing import (
9 TYPE_CHECKING,
10 Any,
11 Callable,
12 Dict,
13 Iterable,
14 List,
15 Literal,
16 Mapping,
17 Optional,
18 Self,
19 Sequence,
20 Set,
21 Type,
22 Union,
23)
25from redis import _himport_exec
26from redis._defaults import (
27 DEFAULT_RETRY_BASE,
28 DEFAULT_RETRY_CAP,
29 DEFAULT_RETRY_COUNT,
30 DEFAULT_SOCKET_CONNECT_TIMEOUT,
31 DEFAULT_SOCKET_READ_SIZE,
32 DEFAULT_SOCKET_TIMEOUT,
33)
34from redis._parsers.encoders import Encoder
35from redis._parsers.helpers import bool_ok, decode_info, get_response_callbacks
36from redis._parsers.response_callbacks import _get_response_callback
37from redis.backoff import ExponentialWithJitterBackoff
38from redis.cache import CacheConfig, CacheInterface
39from redis.commands import (
40 CoreCommands,
41 RedisModuleCommands,
42 SentinelCommands,
43 list_or_args,
44)
45from redis.commands.core import Script
46from redis.commands.helpers import parse_pubsub_subscriptions, pubsub_subscription_args
47from redis.commands.metadata import MetadataResolver
48from redis.connection import (
49 AbstractConnection,
50 Connection,
51 ConnectionPool,
52 SSLConnection,
53 UnixDomainSocketConnection,
54)
55from redis.credentials import CredentialProvider, StreamingCredentialProvider
56from redis.driver_info import DriverInfo, resolve_driver_info
57from redis.event import (
58 AfterPooledConnectionsInstantiationEvent,
59 AfterPubSubConnectionInstantiationEvent,
60 AfterSingleConnectionInstantiationEvent,
61 ClientType,
62 EventDispatcher,
63)
64from redis.exceptions import (
65 ConnectionError,
66 ExecAbortError,
67 PubSubError,
68 RedisError,
69 ResponseError,
70 TimeoutError,
71 WatchError,
72)
73from redis.himport import HImportRegistry, parse_himport_set_args
74from redis.lock import Lock
75from redis.maint_notifications import (
76 MaintNotificationsConfig,
77 OSSMaintNotificationsHandler,
78)
79from redis.observability.attributes import PubSubDirection
80from redis.observability.recorder import (
81 record_error_count,
82 record_operation_duration,
83 record_pubsub_message,
84)
85from redis.retry import Retry
86from redis.typing import (
87 ChannelT,
88 FieldT,
89 PubSubHandler,
90 Subscription,
91)
92from redis.utils import (
93 SENTINEL,
94 _set_info_logger,
95 check_protocol_version,
96 command_text,
97 deprecated_args,
98 experimental_method,
99 safe_str,
100 str_if_bytes,
101 truncate_text,
102)
104if TYPE_CHECKING:
105 import ssl
107 import OpenSSL
109 from redis.keyspace_notifications import KeyspaceNotifications
111SYM_EMPTY = b""
112EMPTY_RESPONSE = "EMPTY_RESPONSE"
114# some responses (ie. dump) are binary, and just meant to never be decoded
115NEVER_DECODE = "NEVER_DECODE"
118logger = logging.getLogger(__name__)
121def is_debug_log_enabled():
122 return logger.isEnabledFor(logging.DEBUG)
125def add_debug_log_for_operation_failure(
126 connection: AbstractConnection,
127 error: BaseException | None = None,
128 args: Sequence[Any] | None = None,
129):
130 details = connection.extract_connection_details() if connection else "no connection"
131 prefix = (
132 f"{type(error).__name__} received" if error is not None else "Operation failed"
133 )
134 # Log only the command name - argument values can carry secrets
135 # (AUTH, CONFIG SET requirepass, ACL SETUSER) or user data.
136 command = f" for command {safe_str(args[0])}" if args else ""
137 suffix = f", error: {error}" if error is not None else ""
138 logger.debug(
139 f"{prefix}{command}, with connection: {connection}, details: {details}{suffix}",
140 )
143class CaseInsensitiveDict(dict):
144 "Case insensitive dict implementation. Assumes string keys only."
146 def __init__(self, data: Dict[str, str]) -> None:
147 for k, v in data.items():
148 self[k.upper()] = v
150 def __contains__(self, k):
151 return super().__contains__(k.upper())
153 def __delitem__(self, k):
154 super().__delitem__(k.upper())
156 def __getitem__(self, k):
157 return super().__getitem__(k.upper())
159 def get(self, k, default=None):
160 return super().get(k.upper(), default)
162 def __setitem__(self, k, v):
163 super().__setitem__(k.upper(), v)
165 def update(self, data):
166 data = CaseInsensitiveDict(data)
167 super().update(data)
169 def copy(self) -> "CaseInsensitiveDict":
170 # Keys are already upper-cased; bypass __init__/__setitem__ so the
171 # copy does not re-run ``str.upper`` on every entry.
172 new = type(self).__new__(type(self))
173 dict.update(new, self)
174 return new
177@lru_cache(maxsize=None)
178def _cached_default_response_callbacks(
179 user_protocol: int | str | None,
180 legacy_responses: bool,
181) -> CaseInsensitiveDict:
182 """Build the canonical response-callback table for a given
183 ``(protocol, legacy_responses)`` combination exactly once.
185 The returned mapping is shared by every caller and MUST NOT be mutated or
186 handed to a client directly. Clients must use
187 :func:`default_response_callbacks`, which returns a per-client copy.
188 """
189 return CaseInsensitiveDict(
190 get_response_callbacks(
191 user_protocol=user_protocol,
192 legacy_responses=legacy_responses,
193 )
194 )
197def default_response_callbacks(
198 user_protocol: int | str | None,
199 legacy_responses: bool,
200) -> CaseInsensitiveDict:
201 """Return the default response-callback table for a given
202 ``(protocol, legacy_responses)`` combination.
204 This is the helper clients should use. It returns an independent, mutable
205 per-client table copied from the cached canonical one, so the table is not
206 rebuilt and re-upper-cased on every client construction, and changes such
207 as :meth:`Redis.set_response_callback` stay local to the client.
208 """
209 return _cached_default_response_callbacks(user_protocol, legacy_responses).copy()
212class AbstractRedis:
213 pass
216class Redis(RedisModuleCommands, CoreCommands, SentinelCommands):
217 """
218 Implementation of the Redis protocol.
220 This abstract class provides a Python interface to all Redis commands
221 and an implementation of the Redis protocol.
223 Pipelines derive from this, implementing how
224 the commands are sent and received to the Redis server. Based on
225 configuration, an instance will either use a ConnectionPool, or
226 Connection object to talk to redis.
228 It is not safe to pass PubSub or Pipeline objects between threads.
229 """
231 # Type discrimination marker for @overload self-type pattern
232 _is_async_client: Literal[False] = False
234 @classmethod
235 def from_url(cls, url: str, **kwargs) -> "Redis":
236 """
237 Return a Redis client object configured from the given URL
239 For example::
241 redis://[[username]:[password]]@localhost:6379/0
242 rediss://[[username]:[password]]@localhost:6379/0
243 unix://[username@]/path/to/socket.sock?db=0[&password=password]
245 Three URL schemes are supported:
247 - `redis://` creates a TCP socket connection. See more at:
248 <https://www.iana.org/assignments/uri-schemes/prov/redis>
249 - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
250 <https://www.iana.org/assignments/uri-schemes/prov/rediss>
251 - ``unix://``: creates a Unix Domain Socket connection.
253 The username, password, hostname and path are passed through
254 urllib.parse.unquote in order to replace any percent-encoded values
255 with their corresponding characters. Querystring values are decoded
256 by urllib.parse.parse_qs and are not unquoted again.
258 There are several ways to specify a database number. The first value
259 found will be used:
261 1. A ``db`` querystring option, e.g. redis://localhost?db=0
262 2. If using the redis:// or rediss:// schemes, the path argument
263 of the url, e.g. redis://localhost/0
264 3. A ``db`` keyword argument to this function.
266 If none of these options are specified, the default db=0 is used.
268 All querystring options are cast to their appropriate Python types.
269 Boolean arguments can be specified with string values "True"/"False"
270 or "Yes"/"No". Values that cannot be properly cast cause a
271 ``ValueError`` to be raised. Once parsed, the querystring arguments
272 and keyword arguments are passed to the ``ConnectionPool``'s
273 class initializer. In the case of conflicting arguments, querystring
274 arguments always win.
276 """
277 single_connection_client = kwargs.pop("single_connection_client", False)
278 connection_pool = ConnectionPool.from_url(url, **kwargs)
279 client = cls(
280 connection_pool=connection_pool,
281 single_connection_client=single_connection_client,
282 )
283 client.auto_close_connection_pool = True
284 return client
286 @classmethod
287 def from_pool(
288 cls: Type["Redis"],
289 connection_pool: ConnectionPool,
290 ) -> "Redis":
291 """
292 Return a Redis client from the given connection pool.
293 The Redis client will take ownership of the connection pool and
294 close it when the Redis client is closed.
296 Because the client closes (disconnects all connections in) the pool
297 when it is closed or garbage-collected, the pool must not be shared
298 with other clients. Constructing multiple clients from the same pool
299 via ``from_pool`` -- for example one per request across threads -- is
300 not thread safe: when one client is closed it will disconnect
301 connections still in use by the others.
303 To share a single pool across clients, construct the pool explicitly
304 and manage its lifecycle instead. Unlike ``from_pool``, the plain
305 ``Redis(connection_pool=pool)`` constructor does not take ownership of
306 the pool and will not close it, so a pool created this way can be
307 safely shared across clients. ``ConnectionPool`` supports the context
308 manager protocol for this::
310 with ConnectionPool.from_url(url) as pool:
311 r = Redis(connection_pool=pool)
312 """
313 client = cls(
314 connection_pool=connection_pool,
315 )
316 client.auto_close_connection_pool = True
317 return client
319 @deprecated_args(
320 args_to_warn=["retry_on_timeout"],
321 reason="TimeoutError is included by default.",
322 version="6.0.0",
323 )
324 @deprecated_args(
325 args_to_warn=["lib_name", "lib_version"],
326 reason="Use 'driver_info' parameter instead. "
327 "lib_name and lib_version will be removed in a future version.",
328 )
329 def __init__(
330 self,
331 host: str = "localhost",
332 port: int = 6379,
333 db: int = 0,
334 password: str | None = None,
335 socket_timeout: float | None = DEFAULT_SOCKET_TIMEOUT,
336 socket_connect_timeout: float | None = DEFAULT_SOCKET_CONNECT_TIMEOUT,
337 socket_read_size: int = DEFAULT_SOCKET_READ_SIZE,
338 socket_keepalive: bool | None = True,
339 socket_keepalive_options: Mapping[int, int | bytes] | object | None = SENTINEL,
340 connection_pool: ConnectionPool | None = None,
341 unix_socket_path: str | None = None,
342 encoding: str = "utf-8",
343 encoding_errors: str = "strict",
344 decode_responses: bool = False,
345 retry_on_timeout: bool = False,
346 retry: Retry = Retry(
347 backoff=ExponentialWithJitterBackoff(
348 base=DEFAULT_RETRY_BASE, cap=DEFAULT_RETRY_CAP
349 ),
350 retries=DEFAULT_RETRY_COUNT,
351 ),
352 retry_on_error: List[Type[Exception]] | None = None,
353 ssl: bool = False,
354 ssl_keyfile: str | None = None,
355 ssl_certfile: str | None = None,
356 ssl_cert_reqs: "str | ssl.VerifyMode" = "required",
357 ssl_include_verify_flags: List["ssl.VerifyFlags"] | None = None,
358 ssl_exclude_verify_flags: List["ssl.VerifyFlags"] | None = None,
359 ssl_ca_certs: str | None = None,
360 ssl_ca_path: str | None = None,
361 ssl_ca_data: str | None = None,
362 ssl_check_hostname: bool = True,
363 ssl_password: str | None = None,
364 ssl_validate_ocsp: bool = False,
365 ssl_validate_ocsp_stapled: bool = False,
366 ssl_ocsp_context: "OpenSSL.SSL.Context | None" = None,
367 ssl_ocsp_expected_cert: str | None = None,
368 ssl_min_version: "ssl.TLSVersion | None" = None,
369 ssl_ciphers: str | None = None,
370 max_connections: int | None = None,
371 single_connection_client: bool = False,
372 health_check_interval: int = 0,
373 client_name: str | None = None,
374 lib_name: str | object | None = SENTINEL,
375 lib_version: str | object | None = SENTINEL,
376 driver_info: DriverInfo | object | None = SENTINEL,
377 username: str | None = None,
378 redis_connect_func: Callable[[], None] | None = None,
379 credential_provider: CredentialProvider | None = None,
380 protocol: int | None = None,
381 legacy_responses: bool = True,
382 cache: CacheInterface | None = None,
383 cache_config: CacheConfig | None = None,
384 event_dispatcher: EventDispatcher | None = None,
385 maint_notifications_config: MaintNotificationsConfig | None = None,
386 oss_cluster_maint_notifications_handler: OSSMaintNotificationsHandler
387 | None = None,
388 metadata_resolver: MetadataResolver | None = None,
389 ) -> None:
390 """
391 Initialize a new Redis client.
393 To specify a retry policy for specific errors, you have two options:
395 1. Set the `retry_on_error` to a list of the error/s to retry on, and
396 you can also set `retry` to a valid `Retry` object(in case the default
397 one is not appropriate) - with this approach the retries will be triggered
398 on the default errors specified in the Retry object enriched with the
399 errors specified in `retry_on_error`.
401 2. Define a `Retry` object with configured 'supported_errors' and set
402 it to the `retry` parameter - with this approach you completely redefine
403 the errors on which retries will happen.
405 `retry_on_timeout` is deprecated - please include the TimeoutError
406 either in the Retry object or in the `retry_on_error` list.
408 When 'connection_pool' is provided - the retry configuration of the
409 provided pool will be used.
411 Args:
413 socket_keepalive:
414 if `True`, TCP keepalive is enabled for TCP socket connections.
415 Argument is ignored when connection_pool is provided.
416 socket_keepalive_options:
417 mapping of TCP keepalive socket option constants to values, for
418 example `{socket.TCP_KEEPIDLE: 30}`. If left unspecified, redis-py
419 uses TCP keepalive defaults when `socket_keepalive` is enabled:
420 idle 30 seconds, interval 5 seconds, and 3 probes. Platform-specific
421 options that are not available are skipped. Pass `None` or `{}` to
422 avoid setting additional TCP keepalive options. Argument is ignored
423 when connection_pool is provided.
424 single_connection_client:
425 if `True`, connection pool is not used. In that case `Redis`
426 instance use is not thread safe.
427 decode_responses:
428 if `True`, the response will be decoded to utf-8.
429 Argument is ignored when connection_pool is provided.
430 driver_info:
431 Optional DriverInfo object to identify upstream libraries.
432 If provided, lib_name and lib_version are ignored.
433 If not provided, a DriverInfo will be created from lib_name and lib_version.
434 Explicit None disables CLIENT SETINFO.
435 Argument is ignored when connection_pool is provided.
436 lib_name:
437 **Deprecated.** Use driver_info instead. Library name for CLIENT SETINFO.
438 lib_version:
439 **Deprecated.** Use driver_info instead. Library version for CLIENT SETINFO.
440 maint_notifications_config:
441 configures the pool to support maintenance notifications - see
442 `redis.maint_notifications.MaintNotificationsConfig` for details.
443 Only supported with RESP3
444 If not provided and protocol is RESP3, the maintenance notifications
445 will be enabled by default (logic is included in the connection pool
446 initialization).
447 Argument is ignored when connection_pool is provided.
448 oss_cluster_maint_notifications_handler:
449 handler for OSS cluster notifications - see
450 `redis.maint_notifications.OSSMaintNotificationsHandler` for details.
451 Only supported with RESP3
452 Argument is ignored when connection_pool is provided.
453 metadata_resolver:
454 decides which commands are eligible for client-side caching - see
455 `redis.commands.metadata.MetadataResolver`. Defaults to the static command
456 metadata this library ships. Resolvers chain through `with_fallback`, first match
457 wins, so one placed in front of `StaticMetadataResolver` overrides the commands it
458 carries while the static records answer for everything else.
459 The library never reads `COMMAND` on its own behalf for this, so the default adds
460 no round trips. To decide eligibility from the connected server, pass a
461 `DynamicMetadataResolver` built from a live `COMMAND` reply - use it with care,
462 because reading that reply relies on a class in the private `redis._parsers`
463 package.
464 Argument is ignored when connection_pool is provided - configure it on the pool
465 instead.
466 """
467 if event_dispatcher is not None:
468 self._event_dispatcher = event_dispatcher
469 if not connection_pool:
470 if not retry_on_error:
471 retry_on_error = []
473 # Handle driver_info: if provided, use it; otherwise create from lib_name/lib_version.
474 computed_driver_info = resolve_driver_info(
475 driver_info, lib_name, lib_version
476 )
478 kwargs = {
479 "db": db,
480 "username": username,
481 "password": password,
482 "socket_timeout": socket_timeout,
483 "socket_read_size": socket_read_size,
484 "encoding": encoding,
485 "encoding_errors": encoding_errors,
486 "decode_responses": decode_responses,
487 "retry_on_error": retry_on_error,
488 "retry": copy.deepcopy(retry),
489 "max_connections": max_connections,
490 "health_check_interval": health_check_interval,
491 "client_name": client_name,
492 "driver_info": computed_driver_info,
493 "redis_connect_func": redis_connect_func,
494 "credential_provider": credential_provider,
495 "protocol": protocol,
496 "legacy_responses": legacy_responses,
497 }
498 # based on input, setup appropriate connection args
499 if unix_socket_path is not None:
500 if (
501 maint_notifications_config
502 and maint_notifications_config.enabled is True
503 ):
504 raise RedisError(
505 "Maintenance notifications are not supported with Unix "
506 "domain socket connections"
507 )
508 kwargs.update(
509 {
510 "path": unix_socket_path,
511 "connection_class": UnixDomainSocketConnection,
512 "maint_notifications_config": MaintNotificationsConfig(
513 enabled=False
514 ),
515 }
516 )
517 else:
518 # TCP specific options
519 kwargs.update(
520 {
521 "host": host,
522 "port": port,
523 "socket_connect_timeout": socket_connect_timeout,
524 "socket_keepalive": socket_keepalive,
525 "socket_keepalive_options": socket_keepalive_options,
526 }
527 )
529 if ssl:
530 kwargs.update(
531 {
532 "connection_class": SSLConnection,
533 "ssl_keyfile": ssl_keyfile,
534 "ssl_certfile": ssl_certfile,
535 "ssl_cert_reqs": ssl_cert_reqs,
536 "ssl_include_verify_flags": ssl_include_verify_flags,
537 "ssl_exclude_verify_flags": ssl_exclude_verify_flags,
538 "ssl_ca_certs": ssl_ca_certs,
539 "ssl_ca_data": ssl_ca_data,
540 "ssl_check_hostname": ssl_check_hostname,
541 "ssl_password": ssl_password,
542 "ssl_ca_path": ssl_ca_path,
543 "ssl_validate_ocsp_stapled": ssl_validate_ocsp_stapled,
544 "ssl_validate_ocsp": ssl_validate_ocsp,
545 "ssl_ocsp_context": ssl_ocsp_context,
546 "ssl_ocsp_expected_cert": ssl_ocsp_expected_cert,
547 "ssl_min_version": ssl_min_version,
548 "ssl_ciphers": ssl_ciphers,
549 }
550 )
551 maint_notifications_enabled = (
552 maint_notifications_config and maint_notifications_config.enabled
553 )
554 if maint_notifications_enabled and not check_protocol_version(
555 protocol, 3
556 ):
557 raise RedisError(
558 "Maintenance notifications handlers on connection are only supported with RESP version 3"
559 )
560 if maint_notifications_config:
561 kwargs.update(
562 {
563 "maint_notifications_config": maint_notifications_config,
564 }
565 )
566 if oss_cluster_maint_notifications_handler:
567 kwargs.update(
568 {
569 "oss_cluster_maint_notifications_handler": oss_cluster_maint_notifications_handler,
570 }
571 )
572 if (cache_config or cache) and check_protocol_version(protocol, 3):
573 kwargs.update(
574 {
575 "cache": cache,
576 "cache_config": cache_config,
577 }
578 )
579 if metadata_resolver is not None:
580 # A named ``ConnectionPool`` parameter, not a connection kwarg, so it
581 # reaches the pool without also being forwarded to every connection.
582 kwargs.update(
583 {
584 "metadata_resolver": metadata_resolver,
585 }
586 )
587 connection_pool = ConnectionPool(**kwargs)
588 self.auto_close_connection_pool = True
589 else:
590 self.auto_close_connection_pool = False
592 # A user-supplied dispatcher always gets the event, for its own
593 # listeners. The default one is private to this client, so its only
594 # listener is the built-in re-auth one, which acts on a
595 # StreamingCredentialProvider alone: skip the no-op dispatch (and
596 # building the dispatcher) for any other provider.
597 if event_dispatcher is not None or (
598 credential_provider is not None
599 and isinstance(credential_provider, StreamingCredentialProvider)
600 ):
601 self._event_dispatcher.dispatch(
602 AfterPooledConnectionsInstantiationEvent(
603 [connection_pool], ClientType.SYNC, credential_provider
604 )
605 )
607 self.connection_pool = connection_pool
609 if (cache_config or cache) and not check_protocol_version(
610 self.connection_pool.get_protocol(), 3
611 ):
612 raise RedisError("Client caching is only supported with RESP version 3")
614 self.single_connection_lock = threading.RLock()
615 self.connection = None
616 self._single_connection_client = single_connection_client
617 if self._single_connection_client:
618 self.connection = self.connection_pool.get_connection()
619 self._event_dispatcher.dispatch(
620 AfterSingleConnectionInstantiationEvent(
621 self.connection, ClientType.SYNC, self.single_connection_lock
622 )
623 )
625 connection_kwargs = self.connection_pool.connection_kwargs
626 self.response_callbacks = default_response_callbacks(
627 connection_kwargs.get("protocol"),
628 connection_kwargs.get("legacy_responses", True),
629 )
631 @cached_property
632 def _event_dispatcher(self) -> EventDispatcher:
633 # Built on first use when the client was given no dispatcher; a
634 # dispatcher passed to __init__ is stored on the instance instead.
635 return EventDispatcher()
637 def __repr__(self) -> str:
638 return (
639 f"<{type(self).__module__}.{type(self).__name__}"
640 f"({repr(self.connection_pool)})>"
641 )
643 def get_encoder(self) -> "Encoder":
644 """Get the connection pool's encoder"""
645 return self.connection_pool.get_encoder()
647 def get_connection_kwargs(self) -> Dict:
648 """Get the connection's key-word arguments"""
649 return self.connection_pool.connection_kwargs
651 @property
652 def himport_registry(self) -> HImportRegistry:
653 """The client's HIMPORT fieldset registry (contains empty
654 schema registry if none was declared).
656 Read-only: the registry is mutated only through the HIMPORT command methods.
657 """
658 return self.connection_pool.himport_registry
660 def get_retry(self) -> Optional[Retry]:
661 return self.get_connection_kwargs().get("retry")
663 def set_retry(self, retry: Retry) -> None:
664 self.get_connection_kwargs().update({"retry": retry})
665 self.connection_pool.set_retry(retry)
667 def set_response_callback(self, command: str, callback: Callable) -> None:
668 """Set a custom Response Callback"""
669 self.response_callbacks[command] = callback
671 def load_external_module(self, funcname, func) -> None:
672 """
673 This function can be used to add externally defined redis modules,
674 and their namespaces to the redis client.
676 funcname - A string containing the name of the function to create
677 func - The function, being added to this class.
679 ex: Assume that one has a custom redis module named foomod that
680 creates command named 'foo.dothing' and 'foo.anotherthing' in redis.
681 To load function functions into this namespace:
683 from redis import Redis
684 from foomodule import F
685 r = Redis()
686 r.load_external_module("foo", F)
687 r.foo().dothing('your', 'arguments')
689 For a concrete example see the reimport of the redisjson module in
690 tests/test_connection.py::test_loading_external_modules
691 """
692 setattr(self, funcname, func)
694 def pipeline(self, transaction=True, shard_hint=None) -> "Pipeline":
695 """
696 Return a new pipeline object that can queue multiple commands for
697 later execution. ``transaction`` indicates whether all commands
698 should be executed atomically. Apart from making a group of operations
699 atomic, pipelines are useful for reducing the back-and-forth overhead
700 between the client and server.
701 """
702 return Pipeline(
703 self.connection_pool, self.response_callbacks, transaction, shard_hint
704 )
706 def transaction(
707 self, func: Callable[["Pipeline"], None], *watches, **kwargs
708 ) -> Union[List[Any], Any, None]:
709 """
710 Convenience method for executing the callable `func` as a transaction
711 while watching all keys specified in `watches`. The 'func' callable
712 should expect a single argument which is a Pipeline object.
713 """
714 shard_hint = kwargs.pop("shard_hint", None)
715 value_from_callable = kwargs.pop("value_from_callable", False)
716 watch_delay = kwargs.pop("watch_delay", None)
717 with self.pipeline(True, shard_hint) as pipe:
718 while True:
719 try:
720 if watches:
721 pipe.watch(*watches)
722 func_value = func(pipe)
723 exec_value = pipe.execute()
724 return func_value if value_from_callable else exec_value
725 except WatchError:
726 if watch_delay is not None and watch_delay > 0:
727 time.sleep(watch_delay)
728 continue
730 def lock(
731 self,
732 name: str,
733 timeout: Optional[float] = None,
734 sleep: float = 0.1,
735 blocking: bool = True,
736 blocking_timeout: Optional[float] = None,
737 lock_class: Union[None, Any] = None,
738 thread_local: bool = True,
739 raise_on_release_error: bool = True,
740 ):
741 """
742 Return a new Lock object using key ``name`` that mimics
743 the behavior of threading.Lock.
745 If specified, ``timeout`` indicates a maximum life for the lock.
746 By default, it will remain locked until release() is called.
748 ``sleep`` indicates the amount of time to sleep per loop iteration
749 when the lock is in blocking mode and another client is currently
750 holding the lock.
752 ``blocking`` indicates whether calling ``acquire`` should block until
753 the lock has been acquired or to fail immediately, causing ``acquire``
754 to return False and the lock not being acquired. Defaults to True.
755 Note this value can be overridden by passing a ``blocking``
756 argument to ``acquire``.
758 ``blocking_timeout`` indicates the maximum amount of time in seconds to
759 spend trying to acquire the lock. A value of ``None`` indicates
760 continue trying forever. ``blocking_timeout`` can be specified as a
761 float or integer, both representing the number of seconds to wait.
763 ``lock_class`` forces the specified lock implementation. Note that as
764 of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
765 a Lua-based lock). So, it's unlikely you'll need this parameter, unless
766 you have created your own custom lock class.
768 ``thread_local`` indicates whether the lock token is placed in
769 thread-local storage. By default, the token is placed in thread local
770 storage so that a thread only sees its token, not a token set by
771 another thread. Consider the following timeline:
773 time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
774 thread-1 sets the token to "abc"
775 time: 1, thread-2 blocks trying to acquire `my-lock` using the
776 Lock instance.
777 time: 5, thread-1 has not yet completed. redis expires the lock
778 key.
779 time: 5, thread-2 acquired `my-lock` now that it's available.
780 thread-2 sets the token to "xyz"
781 time: 6, thread-1 finishes its work and calls release(). if the
782 token is *not* stored in thread local storage, then
783 thread-1 would see the token value as "xyz" and would be
784 able to successfully release the thread-2's lock.
786 ``raise_on_release_error`` indicates whether to raise an exception when
787 the lock is no longer owned when exiting the context manager. By default,
788 this is True, meaning an exception will be raised. If False, the warning
789 will be logged and the exception will be suppressed.
791 In some use cases it's necessary to disable thread local storage. For
792 example, if you have code where one thread acquires a lock and passes
793 that lock instance to a worker thread to release later. If thread
794 local storage isn't disabled in this case, the worker thread won't see
795 the token set by the thread that acquired the lock. Our assumption
796 is that these cases aren't common and as such default to using
797 thread local storage."""
798 if lock_class is None:
799 lock_class = Lock
800 return lock_class(
801 self,
802 name,
803 timeout=timeout,
804 sleep=sleep,
805 blocking=blocking,
806 blocking_timeout=blocking_timeout,
807 thread_local=thread_local,
808 raise_on_release_error=raise_on_release_error,
809 )
811 def pubsub(self, **kwargs) -> "PubSub":
812 """
813 Return a Publish/Subscribe object. With this object, you can
814 subscribe to channels and listen for messages that get published to
815 them.
816 """
817 return PubSub(
818 self.connection_pool, event_dispatcher=self._event_dispatcher, **kwargs
819 )
821 def keyspace_notifications(
822 self,
823 key_prefix: Union[str, bytes, None] = None,
824 ignore_subscribe_messages: bool = True,
825 ) -> "KeyspaceNotifications":
826 """
827 Return a :class:`~redis.keyspace_notifications.KeyspaceNotifications`
828 object for subscribing to keyspace and keyevent notifications.
830 Note: Keyspace notifications must be enabled on the Redis server via
831 the ``notify-keyspace-events`` configuration option.
833 Args:
834 key_prefix: Optional prefix to filter and strip from keys in
835 notifications.
836 ignore_subscribe_messages: If True, subscribe/unsubscribe
837 confirmations are not returned by
838 get_message/listen.
839 """
840 from redis.keyspace_notifications import KeyspaceNotifications
842 return KeyspaceNotifications(
843 self,
844 key_prefix=key_prefix,
845 ignore_subscribe_messages=ignore_subscribe_messages,
846 )
848 def monitor(self):
849 return Monitor(self.connection_pool)
851 def client(self):
852 return self.__class__(
853 connection_pool=self.connection_pool,
854 single_connection_client=True,
855 )
857 def __enter__(self):
858 return self
860 def __exit__(self, exc_type, exc_value, traceback):
861 self.close()
863 def __del__(self):
864 try:
865 self.close()
866 except Exception:
867 pass
869 def close(self) -> None:
870 # In case a connection property does not yet exist
871 # (due to a crash earlier in the Redis() constructor), return
872 # immediately as there is nothing to clean-up.
873 if not hasattr(self, "connection"):
874 return
876 conn = self.connection
877 if conn:
878 self.connection = None
879 self.connection_pool.release(conn)
881 if self.auto_close_connection_pool:
882 self.connection_pool.close()
884 def _send_command_parse_response(self, conn, command_name, *args, **options):
885 """
886 Send a command and parse the response
887 """
888 # HIMPORT SET is the one command whose wire form depends on per-connection
889 # state: the fieldset must be PREPAREd on this connection first, and any
890 # fieldset discarded since this connection last reconciled must be dropped.
891 # Handling it here (rather than in himport_set) lets himport_set reuse the
892 # full execute_command machinery — retry, disconnect-on-error, pooling — so
893 # a failed HIMPORT SET disconnects the connection like any other command.
894 # This per-command branch in the hot dispatch path is deliberate and has no
895 # cleaner alternative: this is the only seam where the concrete borrowed
896 # connection is known, and connection-scoped session setup can only happen
897 # once that connection is chosen. The overhead is one string compare per
898 # command.
899 himport_set = parse_himport_set_args(args)
900 if himport_set is not None:
901 # ``args`` is an HIMPORT SET in either the joined ("HIMPORT SET", key,
902 # ...) or split ("HIMPORT", "SET", key, ...) raw form; the operands come
903 # back at the right offsets for the form. A command with too few operands
904 # returns None and falls through to the normal send path so the server
905 # returns its arity error instead of a client-side IndexError here.
906 key, fieldset_name, values = himport_set
907 return self._himport_execute_set(conn, key, fieldset_name, values)
908 conn.send_command(*args, **options)
909 return self.parse_response(conn, command_name, **options)
911 def _himport_reconcile_discards(self, conn):
912 """Delegate to the shared sync HIMPORT executor."""
913 return _himport_exec.reconcile_discards(self, conn)
915 def _himport_prepare_and_set(self, conn, key, fieldset_name, values, fieldset):
916 """Delegate to the shared sync HIMPORT executor."""
917 return _himport_exec.prepare_and_set(
918 self, conn, key, fieldset_name, values, fieldset
919 )
921 def _himport_execute_set(self, conn, key, fieldset_name, values):
922 """Delegate to the shared sync HIMPORT executor."""
923 return _himport_exec.execute_set(self, conn, key, fieldset_name, values)
925 def _close_connection(
926 self,
927 conn,
928 error: Optional[Exception] = None,
929 failure_count: Optional[int] = None,
930 start_time: Optional[float] = None,
931 command_name: Optional[str] = None,
932 ) -> None:
933 """
934 Close the connection before retrying.
936 The supported exceptions are already checked in the
937 retry object so we don't need to do it here.
939 After we disconnect the connection, it will try to reconnect and
940 do a health check as part of the send_command logic(on connection level).
941 """
942 if error and failure_count <= conn.retry.get_retries():
943 record_operation_duration(
944 command_name=command_name,
945 duration_seconds=time.monotonic() - start_time,
946 server_address=getattr(conn, "host", None),
947 server_port=getattr(conn, "port", None),
948 db_namespace=str(conn.db),
949 error=error,
950 retry_attempts=failure_count,
951 )
953 conn.disconnect()
955 # COMMAND EXECUTION AND PROTOCOL PARSING
956 def execute_command(self, *args, **options):
957 return self._execute_command(*args, **options)
959 def _execute_command(self, *args, **options):
960 """Execute a command and return a parsed response"""
961 pool = self.connection_pool
962 command_name = args[0]
963 conn = self.connection or pool.get_connection()
965 # Start timing for observability
966 start_time = time.monotonic()
967 # Track actual retry attempts for error reporting
968 actual_retry_attempts = [0]
970 def failure_callback(error, failure_count):
971 if is_debug_log_enabled():
972 add_debug_log_for_operation_failure(conn, error, args)
973 actual_retry_attempts[0] = failure_count
974 self._close_connection(conn, error, failure_count, start_time, command_name)
976 if self._single_connection_client:
977 self.single_connection_lock.acquire()
978 try:
979 result = conn.retry.call_with_retry(
980 lambda: self._send_command_parse_response(
981 conn, command_name, *args, **options
982 ),
983 failure_callback,
984 with_failure_count=True,
985 )
987 record_operation_duration(
988 command_name=command_name,
989 duration_seconds=time.monotonic() - start_time,
990 server_address=getattr(conn, "host", None),
991 server_port=getattr(conn, "port", None),
992 db_namespace=str(conn.db),
993 )
994 return result
995 except Exception as e:
996 record_error_count(
997 server_address=getattr(conn, "host", None),
998 server_port=getattr(conn, "port", None),
999 network_peer_address=getattr(conn, "host", None),
1000 network_peer_port=getattr(conn, "port", None),
1001 error_type=e,
1002 retry_attempts=actual_retry_attempts[0],
1003 is_internal=False,
1004 )
1005 raise
1007 finally:
1008 try:
1009 if conn and conn.should_reconnect():
1010 self._close_connection(conn)
1011 conn.connect()
1012 finally:
1013 if self._single_connection_client:
1014 self.single_connection_lock.release()
1015 if not self.connection:
1016 pool.release(conn)
1018 def parse_response(self, connection, command_name, **options):
1019 """Parses a response from the Redis server"""
1020 try:
1021 if NEVER_DECODE in options:
1022 response = connection.read_response(disable_decoding=True)
1023 options.pop(NEVER_DECODE)
1024 if command_name == "INFO":
1025 response = decode_info(response, self.get_encoder())
1026 else:
1027 response = connection.read_response()
1028 except ResponseError:
1029 if EMPTY_RESPONSE in options:
1030 return options[EMPTY_RESPONSE]
1031 raise
1033 if EMPTY_RESPONSE in options:
1034 options.pop(EMPTY_RESPONSE)
1036 # Remove keys entry, it needs only for cache.
1037 options.pop("keys", None)
1039 if connection._resp2_fallback:
1040 callback = _get_response_callback(
1041 self.response_callbacks, command_name, connection
1042 )
1043 else:
1044 callback = self.response_callbacks.get(command_name)
1045 if callback is not None:
1046 return callback(response, **options)
1047 return response
1049 def get_cache(self) -> Optional[CacheInterface]:
1050 return self.connection_pool.cache
1052 # HIMPORT orchestration. The registry lives on the shared HImportRegistry; the
1053 # server-side effect is applied lazily per connection (PREPARE bundled into the
1054 # first himport_set; DISCARD reconciled when a connection is next borrowed for a
1055 # himport_set). The connection carries the per-connection HIMPORT state; a
1056 # CacheProxyConnection transparently delegates it to the wrapped connection, so
1057 # this code never needs to know which connection type it holds.
1059 @experimental_method()
1060 def himport_prepare(self, fieldset_name: str, fields: Iterable[FieldT]) -> bool:
1061 """Declare an HIMPORT fieldset for use by :meth:`himport_set`.
1063 Registers ``fieldset_name`` (ordered ``fields``, verbatim) in the client's
1064 shared registry. On a pooled client the server-side ``PREPARE`` is deferred
1065 and bundled into the next ``himport_set`` per connection. On a single
1066 connection client it is run immediately when the pinned connection is live;
1067 while that connection is not connected there is no session state to prepare,
1068 so the next ``himport_set`` prepares it lazily instead.
1069 """
1070 fieldset = self.himport_registry.prepare(fieldset_name, fields)
1071 conn = self.connection
1072 if self._single_connection_client and conn is not None and conn.is_connected:
1073 self.himport_prepare_internal(fieldset_name, fieldset.fields)
1074 conn._himport_prepared[fieldset_name] = fieldset.version
1075 return True
1077 @experimental_method()
1078 def himport_discard(self, fieldset_name: str) -> int:
1079 """Remove a fieldset from the registry.
1081 Returns ``1`` if it was registered, ``0`` otherwise. On a pooled client the
1082 server-side ``DISCARD`` is reconciled lazily when each connection is next
1083 used for ``himport_set``. On a single connection client it runs immediately
1084 on the pinned connection when it is live; while that connection is not
1085 connected there is nothing prepared on the server to discard (its tracking is
1086 reset on connect), so no server call is made.
1087 """
1088 removed = self.himport_registry.discard(fieldset_name)
1089 conn = self.connection
1090 if self._single_connection_client and conn is not None and conn.is_connected:
1091 if removed:
1092 self.himport_discard_internal(fieldset_name)
1093 conn._himport_prepared.pop(fieldset_name, None)
1094 conn._himport_reconciled_revision = self.himport_registry.revision
1095 return 1 if removed else 0
1097 @experimental_method()
1098 def himport_discard_all(self) -> int:
1099 """Remove all fieldsets from the registry.
1101 Returns the number removed from the registry. Server-side removal follows the
1102 same live/lazy rule as :meth:`himport_discard`.
1103 """
1104 count = self.himport_registry.discard_all()
1105 conn = self.connection
1106 if self._single_connection_client and conn is not None and conn.is_connected:
1107 if count:
1108 self.himport_discard_all_internal()
1109 conn._himport_prepared.clear()
1110 conn._himport_reconciled_revision = self.himport_registry.revision
1111 return count
1114StrictRedis = Redis
1117class Monitor:
1118 """
1119 Monitor is useful for handling the MONITOR command to the redis server.
1120 next_command() method returns one command from monitor
1121 listen() method yields commands from monitor.
1122 """
1124 monitor_re = re.compile(r"\[(\d+) (.*?)\] (.*)")
1125 # Each argument is quoted with its backslashes and quotes escaped, so an
1126 # argument ending in a backslash ends in an escaped backslash, not an
1127 # escaped quote.
1128 command_re = re.compile(r'"([^"\\]*+(?:\\.[^"\\]*+)*+)"')
1130 def __init__(self, connection_pool):
1131 self.connection_pool = connection_pool
1132 self.connection = self.connection_pool.get_connection()
1134 def __enter__(self):
1135 if self.connection is None:
1136 self.connection = self.connection_pool.get_connection()
1137 try:
1138 self._start_monitor()
1139 except BaseException:
1140 try:
1141 self.__exit__()
1142 except Exception:
1143 pass
1144 raise
1145 return self
1147 def __exit__(self, *args):
1148 connection, self.connection = self.connection, None
1149 if connection is None:
1150 return
1151 try:
1152 connection.disconnect()
1153 finally:
1154 self.connection_pool.release(connection)
1156 def next_command(self):
1157 """Parse the response from a monitor command"""
1158 response = self.connection.read_response()
1160 if response is None:
1161 return None
1163 if isinstance(response, bytes):
1164 response = self.connection.encoder.decode(response, force=True)
1166 command_time, command_data = response.split(" ", 1)
1167 m = self.monitor_re.match(command_data)
1168 db_id, client_info, command = m.groups()
1169 command = " ".join(self.command_re.findall(command))
1170 # Redis escapes double quotes because each piece of the command
1171 # string is surrounded by double quotes. We don't have that
1172 # requirement so remove the escaping and leave the quote.
1173 command = command.replace('\\"', '"')
1175 if client_info == "lua":
1176 client_address = "lua"
1177 client_port = ""
1178 client_type = "lua"
1179 elif client_info.startswith("unix"):
1180 client_address = "unix"
1181 client_port = client_info[5:]
1182 client_type = "unix"
1183 else:
1184 if client_info == "":
1185 client_address = ""
1186 client_port = ""
1187 client_type = "unknown"
1188 else:
1189 # use rsplit as ipv6 addresses contain colons
1190 client_address, client_port = client_info.rsplit(":", 1)
1191 client_type = "tcp"
1192 return {
1193 "time": float(command_time),
1194 "db": int(db_id),
1195 "client_address": client_address,
1196 "client_port": client_port,
1197 "client_type": client_type,
1198 "command": command,
1199 }
1201 def listen(self):
1202 """Listen for commands coming to the server."""
1203 while True:
1204 yield self.next_command()
1206 def _start_monitor(self):
1207 self.connection.send_command("MONITOR")
1208 # check that monitor returns 'OK', but don't return it to user
1209 response = self.connection.read_response()
1211 if not bool_ok(response):
1212 raise RedisError(f"MONITOR failed: {response}")
1215class PubSub:
1216 """
1217 PubSub provides publish, subscribe and listen support to Redis channels.
1219 After subscribing to one or more channels, the listen() method will block
1220 until a message arrives on one of the subscribed channels. That message
1221 will be returned and it's safe to start listening again.
1222 """
1224 PUBLISH_MESSAGE_TYPES = ("message", "pmessage", "smessage")
1225 UNSUBSCRIBE_MESSAGE_TYPES = ("unsubscribe", "punsubscribe", "sunsubscribe")
1226 HEALTH_CHECK_MESSAGE = "redis-py-health-check"
1228 def __init__(
1229 self,
1230 connection_pool,
1231 shard_hint=None,
1232 ignore_subscribe_messages: bool = False,
1233 encoder: Optional["Encoder"] = None,
1234 push_handler_func: Union[None, Callable[[str], None]] = None,
1235 event_dispatcher: Optional["EventDispatcher"] = None,
1236 ):
1237 self.connection_pool = connection_pool
1238 self.shard_hint = shard_hint
1239 self.ignore_subscribe_messages = ignore_subscribe_messages
1240 self.connection = None
1241 self.subscribed_event = threading.Event()
1242 # we need to know the encoding options for this connection in order
1243 # to lookup channel and pattern names for callback handlers.
1244 self.encoder = encoder
1245 self.push_handler_func = push_handler_func
1246 if event_dispatcher is None:
1247 self._event_dispatcher = EventDispatcher()
1248 else:
1249 self._event_dispatcher = event_dispatcher
1251 self._lock = threading.RLock()
1252 if self.encoder is None:
1253 self.encoder = self.connection_pool.get_encoder()
1254 self.health_check_response_b = self.encoder.encode(self.HEALTH_CHECK_MESSAGE)
1255 if self.encoder.decode_responses:
1256 self.health_check_response = ["pong", self.HEALTH_CHECK_MESSAGE]
1257 else:
1258 self.health_check_response = [b"pong", self.health_check_response_b]
1259 if self.push_handler_func is None:
1260 _set_info_logger()
1261 self.reset()
1263 def __enter__(self) -> Self:
1264 return self
1266 def __exit__(self, exc_type, exc_value, traceback) -> None:
1267 self.reset()
1269 def __del__(self) -> None:
1270 try:
1271 # if this object went out of scope prior to shutting down
1272 # subscriptions, close the connection manually before
1273 # returning it to the connection pool
1274 self.reset()
1275 except Exception:
1276 pass
1278 def reset(self) -> None:
1279 if self.connection:
1280 self.connection.disconnect()
1281 self.connection.deregister_connect_callback(self.on_connect)
1282 if self.push_handler_func is not None:
1283 # The handler is set on the parser of a pooled connection: put
1284 # the parser's own back, or the next PubSub that gets this
1285 # connection has its messages handed to ours
1286 parser = self.connection._get_parser()
1287 if (
1288 getattr(parser, "pubsub_push_handler_func", None)
1289 is self.push_handler_func
1290 ):
1291 parser.set_pubsub_push_handler(parser.handle_pubsub_push_response)
1292 self.connection_pool.release(self.connection)
1293 self.connection = None
1294 self.health_check_response_counter = 0
1295 self.channels = {}
1296 self.pending_unsubscribe_channels = set()
1297 self.shard_channels = {}
1298 self.pending_unsubscribe_shard_channels = set()
1299 self.patterns = {}
1300 self.pending_unsubscribe_patterns = set()
1301 self.subscribed_event.clear()
1303 def close(self) -> None:
1304 self.reset()
1306 def _resubscribe(self, subscribed, subscribe_fn) -> None:
1307 # Replay handler-backed subscriptions as positional Subscription objects
1308 # so binary names never need to be decoded into keyword argument keys.
1309 subscriptions = pubsub_subscription_args(subscribed)
1310 if subscriptions:
1311 subscribe_fn(*subscriptions)
1313 def _resubscribe_shard_channels(self) -> None:
1314 self._resubscribe(self.shard_channels, self.ssubscribe)
1316 def on_connect(self, connection) -> None:
1317 "Re-subscribe to any channels and patterns previously subscribed to"
1318 self.pending_unsubscribe_channels.clear()
1319 self.pending_unsubscribe_patterns.clear()
1320 self.pending_unsubscribe_shard_channels.clear()
1321 if self.channels:
1322 self._resubscribe(self.channels, self.subscribe)
1323 if self.patterns:
1324 self._resubscribe(self.patterns, self.psubscribe)
1325 if self.shard_channels:
1326 self._resubscribe_shard_channels()
1328 @property
1329 def subscribed(self) -> bool:
1330 """Indicates if there are subscriptions to any channels or patterns"""
1331 return self.subscribed_event.is_set()
1333 def execute_command(self, *args):
1334 """Execute a publish/subscribe command"""
1336 # NOTE: don't parse the response in this function -- it could pull a
1337 # legitimate message off the stack if the connection is already
1338 # subscribed to one or more channels
1340 if self.connection is None:
1341 self.connection = self.connection_pool.get_connection()
1342 # register a callback that re-subscribes to any channels we
1343 # were listening to when we were disconnected
1344 self.connection.register_connect_callback(self.on_connect)
1345 if self.push_handler_func is not None:
1346 self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
1347 self._event_dispatcher.dispatch(
1348 AfterPubSubConnectionInstantiationEvent(
1349 self.connection, self.connection_pool, ClientType.SYNC, self._lock
1350 )
1351 )
1352 connection = self.connection
1353 kwargs = {"check_health": not self.subscribed}
1354 if not self.subscribed:
1355 self.clean_health_check_responses()
1356 with self._lock:
1357 self._execute(connection, connection.send_command, *args, **kwargs)
1359 def clean_health_check_responses(self) -> None:
1360 """
1361 If any health check responses are present, clean them
1362 """
1363 ttl = 10
1364 conn = self.connection
1365 while conn and self.health_check_response_counter > 0 and ttl > 0:
1366 if self._execute(conn, conn.can_read, timeout=conn.socket_timeout):
1367 response = self._execute(conn, conn.read_response)
1368 if self.is_health_check_response(response):
1369 self.health_check_response_counter -= 1
1370 else:
1371 raise PubSubError(
1372 "A non health check response was cleaned by "
1373 "execute_command: {}".format(response)
1374 )
1375 ttl -= 1
1377 def _reconnect(
1378 self,
1379 conn,
1380 error: Optional[Exception] = None,
1381 failure_count: Optional[int] = None,
1382 start_time: Optional[float] = None,
1383 command_name: Optional[str] = None,
1384 ) -> None:
1385 """
1386 The supported exceptions are already checked in the
1387 retry object so we don't need to do it here.
1389 In this error handler we are trying to reconnect to the server.
1390 """
1391 if error and failure_count <= conn.retry.get_retries():
1392 if command_name:
1393 record_operation_duration(
1394 command_name=command_name,
1395 duration_seconds=time.monotonic() - start_time,
1396 server_address=getattr(conn, "host", None),
1397 server_port=getattr(conn, "port", None),
1398 db_namespace=str(conn.db),
1399 error=error,
1400 retry_attempts=failure_count,
1401 )
1402 conn.disconnect()
1403 conn.connect()
1405 def _execute(self, conn, command, *args, **kwargs):
1406 """
1407 Connect manually upon disconnection. If the Redis server is down,
1408 this will fail and raise a ConnectionError as desired.
1409 After reconnection, the ``on_connect`` callback should have been
1410 called by the # connection to resubscribe us to any channels and
1411 patterns we were previously listening to
1412 """
1414 if conn.should_reconnect():
1415 self._reconnect(conn)
1417 if not len(args) == 0:
1418 command_name = args[0]
1419 else:
1420 command_name = None
1422 # Start timing for observability
1423 start_time = time.monotonic()
1424 # Track actual retry attempts for error reporting
1425 actual_retry_attempts = [0]
1427 def failure_callback(error, failure_count):
1428 if is_debug_log_enabled():
1429 add_debug_log_for_operation_failure(conn, error, args)
1430 actual_retry_attempts[0] = failure_count
1431 self._reconnect(conn, error, failure_count, start_time, command_name)
1433 try:
1434 response = conn.retry.call_with_retry(
1435 lambda: command(*args, **kwargs),
1436 failure_callback,
1437 with_failure_count=True,
1438 )
1440 if command_name:
1441 record_operation_duration(
1442 command_name=command_name,
1443 duration_seconds=time.monotonic() - start_time,
1444 server_address=getattr(conn, "host", None),
1445 server_port=getattr(conn, "port", None),
1446 db_namespace=str(conn.db),
1447 )
1449 return response
1450 except Exception as e:
1451 record_error_count(
1452 server_address=getattr(conn, "host", None),
1453 server_port=getattr(conn, "port", None),
1454 network_peer_address=getattr(conn, "host", None),
1455 network_peer_port=getattr(conn, "port", None),
1456 error_type=e,
1457 retry_attempts=actual_retry_attempts[0],
1458 is_internal=False,
1459 )
1460 raise
1462 def parse_response(self, block=True, timeout=0):
1463 """
1464 Parse the response from a publish/subscribe command.
1466 Args:
1467 block: If True, block indefinitely until a message is available.
1468 If False, return immediately if no message is available.
1469 Default: True
1470 timeout: The timeout in seconds for reading a response when block=False.
1471 This parameter is ignored when block=True.
1472 Default: 0 (return immediately if no data available)
1474 Returns:
1475 The parsed response from the server, or None if no message is available
1476 within the timeout period (when block=False).
1478 Important:
1479 The block and timeout parameters work together:
1480 - When block=True: timeout is IGNORED, method blocks indefinitely
1481 - When block=False: timeout is USED, method returns after timeout expires
1483 Typically, you should use get_message(timeout=X) instead of calling
1484 parse_response() directly. The get_message() method automatically sets
1485 block=False when a timeout is provided, and block=True when timeout=None.
1487 Example:
1488 # Block indefinitely (timeout is ignored)
1489 response = pubsub.parse_response(block=True, timeout=0.1)
1491 # Non-blocking with 0.1 second timeout
1492 response = pubsub.parse_response(block=False, timeout=0.1)
1494 # Non-blocking, return immediately
1495 response = pubsub.parse_response(block=False, timeout=0)
1497 # Recommended: use get_message() instead
1498 msg = pubsub.get_message(timeout=0.1) # automatically sets block=False
1499 msg = pubsub.get_message(timeout=None) # automatically sets block=True
1500 """
1501 conn = self.connection
1502 if conn is None:
1503 raise RuntimeError(
1504 "pubsub connection not set: "
1505 "did you forget to call subscribe() or psubscribe()?"
1506 )
1508 self.check_health()
1510 def try_read():
1511 if not block:
1512 if not conn.can_read(timeout=timeout):
1513 return None
1514 read_timeout = timeout
1515 else:
1516 conn.connect()
1517 # Block indefinitely waiting for a pubsub message. timeout=None
1518 # makes the socket layer call sock.settimeout(None) for this read
1519 # (and restore the original socket_timeout afterwards), so the
1520 # configured socket_timeout does not abort the read.
1521 read_timeout = None
1522 try:
1523 return conn.read_response(
1524 disconnect_on_error=False, push_request=True, timeout=read_timeout
1525 )
1526 except TimeoutError:
1527 # Only part of a message arrived in time. The parser keeps it,
1528 # so the next call resumes it, while the retry layer would
1529 # reconnect and drop it. A push handler can raise TimeoutError
1530 # itself, so that case still goes to the retry layer.
1531 if block or self.push_handler_func is not None:
1532 raise
1533 return None
1535 response = self._execute(conn, try_read)
1537 if self.is_health_check_response(response):
1538 # ignore the health check message as user might not expect it
1539 self.health_check_response_counter -= 1
1540 return None
1541 return response
1543 def is_health_check_response(self, response) -> bool:
1544 """
1545 Check if the response is a health check response.
1546 If there are no subscriptions redis responds to PING command with a
1547 bulk response, instead of a multi-bulk with "pong" and the response.
1548 """
1549 if self.encoder.decode_responses:
1550 return (
1551 response
1552 in [
1553 self.health_check_response, # If there is a subscription
1554 self.HEALTH_CHECK_MESSAGE, # If there are no subscriptions and decode_responses=True
1555 ]
1556 )
1557 else:
1558 return (
1559 response
1560 in [
1561 self.health_check_response, # If there is a subscription
1562 self.health_check_response_b, # If there isn't a subscription and decode_responses=False
1563 ]
1564 )
1566 def check_health(self) -> None:
1567 conn = self.connection
1568 if conn is None:
1569 raise RuntimeError(
1570 "pubsub connection not set: "
1571 "did you forget to call subscribe() or psubscribe()?"
1572 )
1574 if conn.health_check_interval and time.monotonic() > conn.next_health_check:
1575 conn.send_command("PING", self.HEALTH_CHECK_MESSAGE, check_health=False)
1576 self.health_check_response_counter += 1
1578 def _normalize_keys(self, data) -> Dict:
1579 """
1580 normalize channel/pattern names to be either bytes or strings
1581 based on whether responses are automatically decoded. this saves us
1582 from coercing the value for each message coming in.
1583 """
1584 encode = self.encoder.encode
1585 decode = self.encoder.decode
1586 return {decode(encode(k)): v for k, v in data.items()}
1588 def psubscribe(
1589 self, *args: ChannelT | Subscription, **kwargs: PubSubHandler
1590 ) -> None:
1591 """
1592 Subscribe to channel patterns.
1593 Patterns supplied as keyword arguments expect a pattern name as the
1594 key and a callable as the value.
1595 ``Subscription`` objects can also be supplied positionally with an
1596 optional handler.
1597 A pattern's callable will be invoked automatically
1598 when a message is received on that pattern rather than producing a
1599 message via ``listen()``.
1600 """
1601 new_patterns = parse_pubsub_subscriptions(args, kwargs)
1602 ret_val = self.execute_command("PSUBSCRIBE", *new_patterns.keys())
1603 # update the patterns dict AFTER we send the command. we don't want to
1604 # subscribe twice to these patterns, once for the command and again
1605 # for the reconnection.
1606 new_patterns = self._normalize_keys(new_patterns)
1607 self.patterns.update(new_patterns)
1608 if not self.subscribed:
1609 # Set the subscribed_event flag to True
1610 self.subscribed_event.set()
1611 # Clear the health check counter
1612 self.health_check_response_counter = 0
1613 self.pending_unsubscribe_patterns.difference_update(new_patterns)
1614 return ret_val
1616 def punsubscribe(self, *args):
1617 """
1618 Unsubscribe from the supplied patterns. If empty, unsubscribe from
1619 all patterns.
1620 """
1621 if args:
1622 args = list_or_args(args[0], args[1:])
1623 patterns = self._normalize_keys(dict.fromkeys(args))
1624 else:
1625 patterns = self.patterns
1626 self.pending_unsubscribe_patterns.update(patterns)
1627 return self.execute_command("PUNSUBSCRIBE", *args)
1629 def subscribe(
1630 self, *args: ChannelT | Subscription, **kwargs: PubSubHandler
1631 ) -> None:
1632 """
1633 Subscribe to channels.
1634 Channels supplied as keyword arguments expect
1635 a channel name as the key and a callable as the value.
1636 ``Subscription`` objects can also be supplied positionally with an
1637 optional handler.
1638 A channel's callable will be invoked automatically
1639 when a message is received on that channel rather than producing a
1640 message via ``listen()`` or ``get_message()``.
1641 """
1642 new_channels = parse_pubsub_subscriptions(args, kwargs)
1643 ret_val = self.execute_command("SUBSCRIBE", *new_channels.keys())
1644 # update the channels dict AFTER we send the command. we don't want to
1645 # subscribe twice to these channels, once for the command and again
1646 # for the reconnection.
1647 new_channels = self._normalize_keys(new_channels)
1648 self.channels.update(new_channels)
1649 if not self.subscribed:
1650 # Set the subscribed_event flag to True
1651 self.subscribed_event.set()
1652 # Clear the health check counter
1653 self.health_check_response_counter = 0
1654 self.pending_unsubscribe_channels.difference_update(new_channels)
1655 return ret_val
1657 def unsubscribe(self, *args):
1658 """
1659 Unsubscribe from the supplied channels. If empty, unsubscribe from
1660 all channels
1661 """
1662 if args:
1663 args = list_or_args(args[0], args[1:])
1664 channels = self._normalize_keys(dict.fromkeys(args))
1665 else:
1666 channels = self.channels
1667 self.pending_unsubscribe_channels.update(channels)
1668 return self.execute_command("UNSUBSCRIBE", *args)
1670 def ssubscribe(
1671 self,
1672 *args: ChannelT | Subscription,
1673 target_node: Any = None,
1674 **kwargs: PubSubHandler,
1675 ) -> None:
1676 """
1677 Subscribes the client to the specified shard channels.
1678 Channels supplied as keyword arguments expect a channel name as the key
1679 and a callable as the value.
1680 ``Subscription`` objects can also be supplied positionally
1681 with an optional handler.
1682 A channel's callable will be invoked automatically when a message
1683 is received on that channel rather than producing a message
1684 via ``listen()`` or ``get_sharded_message()``.
1685 """
1686 new_s_channels = parse_pubsub_subscriptions(args, kwargs)
1687 ret_val = self.execute_command("SSUBSCRIBE", *new_s_channels.keys())
1688 # update the s_channels dict AFTER we send the command. we don't want to
1689 # subscribe twice to these channels, once for the command and again
1690 # for the reconnection.
1691 new_s_channels = self._normalize_keys(new_s_channels)
1692 self.shard_channels.update(new_s_channels)
1693 if not self.subscribed:
1694 # Set the subscribed_event flag to True
1695 self.subscribed_event.set()
1696 # Clear the health check counter
1697 self.health_check_response_counter = 0
1698 self.pending_unsubscribe_shard_channels.difference_update(new_s_channels)
1699 return ret_val
1701 def sunsubscribe(self, *args, target_node=None):
1702 """
1703 Unsubscribe from the supplied shard_channels. If empty, unsubscribe from
1704 all shard_channels
1705 """
1706 if args:
1707 args = list_or_args(args[0], args[1:])
1708 s_channels = self._normalize_keys(dict.fromkeys(args))
1709 else:
1710 s_channels = self.shard_channels
1711 self.pending_unsubscribe_shard_channels.update(s_channels)
1712 return self.execute_command("SUNSUBSCRIBE", *args)
1714 def listen(self):
1715 """Listen for messages on channels this client has been subscribed to.
1717 Iteration ends once every channel and pattern has been unsubscribed
1718 from. If nothing is subscribed when iteration begins it ends
1719 immediately rather than waiting, so subscribe first: a listener
1720 started before any subscription finishes without yielding anything.
1721 """
1722 while self.subscribed:
1723 response = self.handle_message(self.parse_response(block=True))
1724 if response is not None:
1725 yield response
1727 def get_message(
1728 self, ignore_subscribe_messages: bool = False, timeout: float = 0.0
1729 ):
1730 """
1731 Get the next message if one is available, otherwise None.
1733 If timeout is specified, the system will wait for `timeout` seconds
1734 before returning. Timeout should be specified as a floating point
1735 number, or None, to wait indefinitely.
1736 """
1737 if not self.subscribed:
1738 # Wait for subscription
1739 start_time = time.monotonic()
1740 if self.subscribed_event.wait(timeout) is True:
1741 # The connection was subscribed during the timeout time frame.
1742 # The timeout should be adjusted based on the time spent
1743 # waiting for the subscription. timeout=None means "block
1744 # indefinitely" and has nothing to charge against, so leave it
1745 # alone rather than raising TypeError on the subtraction.
1746 if timeout is not None:
1747 time_spent = time.monotonic() - start_time
1748 timeout = max(0.0, timeout - time_spent)
1749 else:
1750 # The connection isn't subscribed to any channels or patterns,
1751 # so no messages are available
1752 return None
1754 response = self.parse_response(block=(timeout is None), timeout=timeout)
1756 if response:
1757 return self.handle_message(response, ignore_subscribe_messages)
1758 return None
1760 get_sharded_message = get_message
1762 def ping(self, message: Union[str, None] = None) -> bool:
1763 """
1764 Ping the Redis server to test connectivity.
1766 Sends a PING command to the Redis server and returns True if the server
1767 responds with "PONG".
1768 """
1769 args = ["PING", message] if message is not None else ["PING"]
1770 return self.execute_command(*args)
1772 def handle_message(self, response, ignore_subscribe_messages=False):
1773 """
1774 Parses a pub/sub message. If the channel or pattern was subscribed to
1775 with a message handler, the handler is invoked instead of a parsed
1776 message being returned.
1777 """
1778 if response is None:
1779 return None
1780 if isinstance(response, bytes):
1781 response = [b"pong", response] if response != b"PONG" else [b"pong", b""]
1782 elif isinstance(response, str):
1783 response = ["pong", response] if response != "PONG" else ["pong", ""]
1785 message_type = str_if_bytes(response[0])
1786 if message_type == "pmessage":
1787 message = {
1788 "type": message_type,
1789 "pattern": response[1],
1790 "channel": response[2],
1791 "data": response[3],
1792 }
1793 elif message_type == "pong":
1794 message = {
1795 "type": message_type,
1796 "pattern": None,
1797 "channel": None,
1798 "data": response[1],
1799 }
1800 else:
1801 message = {
1802 "type": message_type,
1803 "pattern": None,
1804 "channel": response[1],
1805 "data": response[2],
1806 }
1808 if message_type in ["message", "pmessage"]:
1809 channel = str_if_bytes(message["channel"])
1810 record_pubsub_message(
1811 direction=PubSubDirection.RECEIVE,
1812 channel=channel,
1813 )
1814 elif message_type == "smessage":
1815 channel = str_if_bytes(message["channel"])
1816 record_pubsub_message(
1817 direction=PubSubDirection.RECEIVE,
1818 channel=channel,
1819 sharded=True,
1820 )
1822 # if this is an unsubscribe message, remove it from memory.
1823 # ``discard`` rather than ``remove``: the guard above already makes the
1824 # removal conditional, so the two are equivalent for a single caller -
1825 # but another writer can drop the same entry between the check and the
1826 # removal, and ``remove`` would then raise ``KeyError`` out of a pubsub
1827 # read that no caller catches. ``ClusterPubSub._detach_shard_channel``
1828 # is such a writer: it forgets a migrating shard channel locally,
1829 # deliberately without the per-node I/O lock this bookkeeping runs
1830 # under, because waiting for that lock stalls reconciliation behind a
1831 # poll's whole retry budget on the node being migrated away from.
1832 if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
1833 if message_type == "punsubscribe":
1834 pattern = response[1]
1835 if pattern in self.pending_unsubscribe_patterns:
1836 self.pending_unsubscribe_patterns.discard(pattern)
1837 self.patterns.pop(pattern, None)
1838 elif message_type == "sunsubscribe":
1839 s_channel = response[1]
1840 if s_channel in self.pending_unsubscribe_shard_channels:
1841 self.shard_channels.pop(s_channel, None)
1842 self.pending_unsubscribe_shard_channels.discard(s_channel)
1843 else:
1844 channel = response[1]
1845 if channel in self.pending_unsubscribe_channels:
1846 self.pending_unsubscribe_channels.discard(channel)
1847 self.channels.pop(channel, None)
1848 if not self.channels and not self.patterns and not self.shard_channels:
1849 # There are no subscriptions anymore, set subscribed_event flag
1850 # to false
1851 self.subscribed_event.clear()
1853 if message_type in self.PUBLISH_MESSAGE_TYPES:
1854 # if there's a message handler, invoke it
1855 if message_type == "pmessage":
1856 handler = self.patterns.get(message["pattern"], None)
1857 elif message_type == "smessage":
1858 handler = self.shard_channels.get(message["channel"], None)
1859 else:
1860 handler = self.channels.get(message["channel"], None)
1861 if handler:
1862 handler(message)
1863 return None
1864 elif message_type != "pong":
1865 # this is a subscribe/unsubscribe message. ignore if we don't
1866 # want them
1867 if ignore_subscribe_messages or self.ignore_subscribe_messages:
1868 return None
1870 return message
1872 def run_in_thread(
1873 self,
1874 sleep_time: float = 0.0,
1875 daemon: bool = False,
1876 exception_handler: Optional[Callable] = None,
1877 pubsub=None,
1878 sharded_pubsub: bool = False,
1879 ) -> "PubSubWorkerThread":
1880 for channel, handler in self.channels.items():
1881 if handler is None:
1882 raise PubSubError(f"Channel: '{channel}' has no handler registered")
1883 for pattern, handler in self.patterns.items():
1884 if handler is None:
1885 raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
1886 for s_channel, handler in self.shard_channels.items():
1887 if handler is None:
1888 raise PubSubError(
1889 f"Shard Channel: '{s_channel}' has no handler registered"
1890 )
1892 pubsub = self if pubsub is None else pubsub
1893 thread = PubSubWorkerThread(
1894 pubsub,
1895 sleep_time,
1896 daemon=daemon,
1897 exception_handler=exception_handler,
1898 sharded_pubsub=sharded_pubsub,
1899 )
1900 thread.start()
1901 return thread
1904class PubSubWorkerThread(threading.Thread):
1905 def __init__(
1906 self,
1907 pubsub,
1908 sleep_time: float,
1909 daemon: bool = False,
1910 exception_handler: Union[
1911 Callable[[Exception, "PubSub", "PubSubWorkerThread"], None], None
1912 ] = None,
1913 sharded_pubsub: bool = False,
1914 ):
1915 super().__init__()
1916 self.daemon = daemon
1917 self.pubsub = pubsub
1918 self.sleep_time = sleep_time
1919 self.exception_handler = exception_handler
1920 self.sharded_pubsub = sharded_pubsub
1921 self._running = threading.Event()
1922 # Set before start() so run() cannot undo an early stop() request.
1923 self._running.set()
1925 def run(self) -> None:
1926 pubsub = self.pubsub
1927 sleep_time = self.sleep_time
1928 while self._running.is_set():
1929 try:
1930 if not self.sharded_pubsub:
1931 pubsub.get_message(
1932 ignore_subscribe_messages=True, timeout=sleep_time
1933 )
1934 else:
1935 pubsub.get_sharded_message(
1936 ignore_subscribe_messages=True, timeout=sleep_time
1937 )
1938 except BaseException as e:
1939 if self.exception_handler is None:
1940 raise
1941 self.exception_handler(e, pubsub, self)
1942 pubsub.close()
1944 def stop(self, timeout: Optional[float] = None) -> None:
1945 """Wait for the worker to finish after clearing the running flag.
1947 timeout bounds that wait. None waits until the worker exits.
1948 The wait is skipped when stop() runs on the worker thread.
1949 """
1950 # trip the flag so the run loop exits. the run loop will
1951 # close the pubsub connection, which disconnects the socket
1952 # and returns the connection to the pool.
1953 self._running.clear()
1954 # wait for that close before returning, so a caller that
1955 # follows stop() with pubsub.close() does not disconnect the
1956 # socket while get_message is still reading it. the exception
1957 # handler calls stop() from this thread; joining there deadlocks.
1958 if threading.current_thread() is not self and self.is_alive():
1959 self.join(timeout)
1962class Pipeline(Redis):
1963 """
1964 Pipelines provide a way to transmit multiple commands to the Redis server
1965 in one transmission. This is convenient for batch processing, such as
1966 saving all the values in a list to Redis.
1968 All commands executed within a pipeline(when running in transactional mode,
1969 which is the default behavior) are wrapped with MULTI and EXEC
1970 calls. This guarantees all commands executed in the pipeline will be
1971 executed atomically.
1973 Any command raising an exception does *not* halt the execution of
1974 subsequent commands in the pipeline. Instead, the exception is caught
1975 and its instance is placed into the response list returned by execute().
1976 Code iterating over the response list should be able to deal with an
1977 instance of an exception as a potential value. In general, these will be
1978 ResponseError exceptions, such as those raised when issuing a command
1979 on a key of a different datatype.
1980 """
1982 UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
1984 def __init__(
1985 self,
1986 connection_pool: ConnectionPool,
1987 response_callbacks,
1988 transaction,
1989 shard_hint,
1990 ):
1991 self.connection_pool = connection_pool
1992 self.connection: Optional[Connection] = None
1993 self.response_callbacks = response_callbacks
1994 self.transaction = transaction
1995 self.shard_hint = shard_hint
1996 self.watching = False
1997 self.command_stack = []
1998 self.scripts: Set[Script] = set()
1999 self.explicit_transaction = False
2001 def __enter__(self) -> "Pipeline":
2002 return self
2004 def __exit__(self, exc_type, exc_value, traceback):
2005 self.reset()
2007 def __del__(self):
2008 try:
2009 self.reset()
2010 except Exception:
2011 pass
2013 def __len__(self) -> int:
2014 return len(self.command_stack)
2016 def __bool__(self) -> bool:
2017 """Pipeline instances should always evaluate to True"""
2018 return True
2020 def reset(self) -> None:
2021 self.command_stack = []
2022 self.scripts = set()
2023 # make sure to reset the connection state in the event that we were
2024 # watching something. A dropped connection has already lost its
2025 # WATCHes, so skip the UNWATCH instead of reconnecting to send it.
2026 if self.watching and self.connection and self.connection.is_connected:
2027 try:
2028 # call this manually since our unwatch or
2029 # immediate_execute_command methods can call reset()
2030 self.connection.send_command("UNWATCH")
2031 self.connection.read_response()
2032 except ConnectionError:
2033 # disconnect will also remove any previous WATCHes
2034 self.connection.disconnect()
2035 # clean up the other instance attributes
2036 self.watching = False
2037 self.explicit_transaction = False
2039 # we can safely return the connection to the pool here since we're
2040 # sure we're no longer WATCHing anything
2041 if self.connection:
2042 self.connection_pool.release(self.connection)
2043 self.connection = None
2045 def close(self) -> None:
2046 """Close the pipeline"""
2047 self.reset()
2049 def multi(self) -> None:
2050 """
2051 Start a transactional block of the pipeline after WATCH commands
2052 are issued. End the transactional block with `execute`.
2053 """
2054 if self.explicit_transaction:
2055 raise RedisError("Cannot issue nested calls to MULTI")
2056 if self.command_stack:
2057 raise RedisError(
2058 "Commands without an initial WATCH have already been issued"
2059 )
2060 self.explicit_transaction = True
2062 def execute_command(self, *args, **kwargs):
2063 if (self.watching or args[0] == "WATCH") and not self.explicit_transaction:
2064 return self.immediate_execute_command(*args, **kwargs)
2065 return self.pipeline_execute_command(*args, **kwargs)
2067 def _disconnect_reset_raise_on_watching(
2068 self,
2069 conn: AbstractConnection,
2070 error: Exception,
2071 failure_count: Optional[int] = None,
2072 start_time: Optional[float] = None,
2073 command_name: Optional[str] = None,
2074 ) -> None:
2075 """
2076 Close the connection reset watching state and
2077 raise an exception if we were watching.
2079 The supported exceptions are already checked in the
2080 retry object so we don't need to do it here.
2082 After we disconnect the connection, it will try to reconnect and
2083 do a health check as part of the send_command logic(on connection level).
2084 """
2085 if error and failure_count <= conn.retry.get_retries():
2086 record_operation_duration(
2087 command_name=command_name,
2088 duration_seconds=time.monotonic() - start_time,
2089 server_address=getattr(conn, "host", None),
2090 server_port=getattr(conn, "port", None),
2091 db_namespace=str(conn.db),
2092 error=error,
2093 retry_attempts=failure_count,
2094 )
2095 conn.disconnect()
2097 # if we were already watching a variable, the watch is no longer
2098 # valid since this connection has died. raise a WatchError, which
2099 # indicates the user should retry this transaction.
2100 if self.watching:
2101 self.reset()
2102 raise WatchError(
2103 f"A {type(error).__name__} occurred while watching one or more keys"
2104 )
2106 def immediate_execute_command(self, *args, **options):
2107 """
2108 Execute a command immediately, but don't auto-retry on the supported
2109 errors for retry if we're already WATCHing a variable.
2110 Used when issuing WATCH or subsequent commands retrieving their values but before
2111 MULTI is called.
2112 """
2113 command_name = args[0]
2114 conn = self.connection
2115 # if this is the first call, we need a connection
2116 if not conn:
2117 conn = self.connection_pool.get_connection()
2118 self.connection = conn
2120 # Start timing for observability
2121 start_time = time.monotonic()
2122 # Track actual retry attempts for error reporting
2123 actual_retry_attempts = [0]
2125 def failure_callback(error, failure_count):
2126 if is_debug_log_enabled():
2127 add_debug_log_for_operation_failure(conn, error, args)
2128 actual_retry_attempts[0] = failure_count
2129 self._disconnect_reset_raise_on_watching(
2130 conn, error, failure_count, start_time, command_name
2131 )
2133 try:
2134 response = conn.retry.call_with_retry(
2135 lambda: self._send_command_parse_response(
2136 conn, command_name, *args, **options
2137 ),
2138 failure_callback,
2139 with_failure_count=True,
2140 )
2142 record_operation_duration(
2143 command_name=command_name,
2144 duration_seconds=time.monotonic() - start_time,
2145 server_address=getattr(conn, "host", None),
2146 server_port=getattr(conn, "port", None),
2147 db_namespace=str(conn.db),
2148 )
2150 return response
2151 except Exception as e:
2152 record_error_count(
2153 server_address=getattr(conn, "host", None),
2154 server_port=getattr(conn, "port", None),
2155 network_peer_address=getattr(conn, "host", None),
2156 network_peer_port=getattr(conn, "port", None),
2157 error_type=e,
2158 retry_attempts=actual_retry_attempts[0],
2159 is_internal=False,
2160 )
2161 raise
2163 def pipeline_execute_command(self, *args, **options) -> "Pipeline":
2164 """
2165 Stage a command to be executed when execute() is next called
2167 Returns the current Pipeline object back so commands can be
2168 chained together, such as:
2170 pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
2172 At some other point, you can then run: pipe.execute(),
2173 which will execute all commands queued in the pipe.
2174 """
2175 self.command_stack.append((args, options))
2176 return self
2178 def _himport_prepare_pipeline(self, conn, commands):
2179 """Delegate to the shared sync HIMPORT executor."""
2180 _himport_exec.prepare_pipeline(self, conn, [args for args, _ in commands])
2182 def _execute_transaction(
2183 self, connection: Connection, commands, raise_on_error
2184 ) -> List:
2185 # Ensure fieldsets referenced by buffered HIMPORT SETs are prepared on this
2186 # connection before the MULTI/EXEC block (session state, not transactional).
2187 self._himport_prepare_pipeline(connection, commands)
2188 cmds = chain([(("MULTI",), {})], commands, [(("EXEC",), {})])
2189 all_cmds = connection.pack_commands(
2190 [args for args, options in cmds if EMPTY_RESPONSE not in options]
2191 )
2192 connection.send_packed_command(all_cmds)
2193 errors = []
2195 # parse off the response for MULTI
2196 # NOTE: we need to handle ResponseErrors here and continue
2197 # so that we read all the additional command messages from
2198 # the socket
2199 try:
2200 self.parse_response(connection, "_")
2201 except ResponseError as e:
2202 errors.append((0, e))
2204 # and all the other commands
2205 for i, command in enumerate(commands):
2206 if EMPTY_RESPONSE in command[1]:
2207 errors.append((i, command[1][EMPTY_RESPONSE]))
2208 else:
2209 try:
2210 self.parse_response(connection, "_")
2211 except ResponseError as e:
2212 self.annotate_exception(e, i + 1, command[0])
2213 errors.append((i, e))
2215 # parse the EXEC.
2216 try:
2217 response = self.parse_response(connection, "_")
2218 except ExecAbortError:
2219 if errors:
2220 raise errors[0][1]
2221 raise
2223 # EXEC clears any watched keys
2224 self.watching = False
2226 if response is None:
2227 raise WatchError("Watched variable changed.")
2229 # put any parse errors into the response
2230 for i, e in errors:
2231 response.insert(i, e)
2233 if len(response) != len(commands):
2234 self.connection.disconnect()
2235 raise ResponseError(
2236 "Wrong number of response items from pipeline execution"
2237 )
2239 # find any errors in the response and raise if necessary
2240 if raise_on_error:
2241 self.raise_first_error(commands, response)
2243 # We have to run response callbacks manually
2244 data = []
2245 for r, cmd in zip(response, commands):
2246 if not isinstance(r, Exception):
2247 args, options = cmd
2248 # Remove keys entry, it needs only for cache.
2249 options.pop("keys", None)
2250 command_name = args[0]
2251 if connection._resp2_fallback:
2252 callback = _get_response_callback(
2253 self.response_callbacks, command_name, connection
2254 )
2255 else:
2256 callback = self.response_callbacks.get(command_name)
2257 if callback is not None:
2258 r = callback(r, **options)
2259 data.append(r)
2261 return data
2263 def _execute_pipeline(self, connection, commands, raise_on_error):
2264 # Fold any first-use HIMPORT PREPAREs for referenced fieldsets into the same
2265 # packed write as the queued commands, so a pipeline that lands on a fresh or
2266 # reconnected connection stays a single round trip (the batched write bypasses
2267 # the per-command lazy PREPARE path). Deferred-discard reconciliation happens
2268 # inside pipeline_prepares and only touches the socket when discards are
2269 # actually pending.
2270 fieldsets = _himport_exec.pipeline_prepares(
2271 self, connection, [args for args, _ in commands]
2272 )
2273 preflight = _himport_exec.prepare_wire_commands(fieldsets)
2274 # build up all commands into a single request to increase network perf
2275 all_cmds = connection.pack_commands(preflight + [args for args, _ in commands])
2276 connection.send_packed_command(all_cmds)
2278 # Drain the leading PREPARE replies (bookkeeping + capture the first error)
2279 # before the queued replies. Everything on the wire is read before raising so
2280 # the pooled socket never desyncs.
2281 prep_error = _himport_exec.drain_pipeline_prepares(self, connection, fieldsets)
2283 responses = []
2284 try:
2285 for args, options in commands:
2286 try:
2287 responses.append(
2288 self.parse_response(connection, args[0], **options)
2289 )
2290 except ResponseError as e:
2291 responses.append(e)
2292 except BaseException:
2293 # A response callback raised, so the replies of the rest of the batch
2294 # are still on the socket. Drop the connection rather than hand them to
2295 # the next caller that borrows it from the pool.
2296 connection.disconnect()
2297 raise
2299 # A PREPARE failure (rare: an invalid fieldset definition) is a hard error,
2300 # raised regardless of raise_on_error as it was before folding -- only now
2301 # every reply has already been drained.
2302 if prep_error is not None:
2303 raise prep_error
2304 if raise_on_error:
2305 self.raise_first_error(commands, responses)
2307 return responses
2309 def raise_first_error(self, commands, response):
2310 for i, r in enumerate(response):
2311 if isinstance(r, ResponseError):
2312 self.annotate_exception(r, i + 1, commands[i][0])
2313 raise r
2315 def annotate_exception(self, exception, number, command):
2316 cmd = command_text(command)
2317 msg = (
2318 f"Command # {number} ({truncate_text(cmd)}) of pipeline "
2319 f"caused error: {exception.args[0]}"
2320 )
2321 exception.args = (msg,) + exception.args[1:]
2323 def parse_response(self, connection, command_name, **options):
2324 result = Redis.parse_response(self, connection, command_name, **options)
2325 if command_name in self.UNWATCH_COMMANDS:
2326 self.watching = False
2327 elif command_name == "WATCH":
2328 self.watching = True
2329 return result
2331 def load_scripts(self):
2332 # make sure all scripts that are about to be run on this pipeline exist
2333 scripts = list(self.scripts)
2334 immediate = self.immediate_execute_command
2335 shas = [s.sha for s in scripts]
2336 # we can't use the normal script_* methods because they would just
2337 # get buffered in the pipeline.
2338 exists = immediate("SCRIPT EXISTS", *shas)
2339 if not all(exists):
2340 for s, exist in zip(scripts, exists):
2341 if not exist:
2342 s.sha = immediate("SCRIPT LOAD", s.script)
2344 def _disconnect_raise_on_watching(
2345 self,
2346 conn: AbstractConnection,
2347 error: Exception,
2348 failure_count: Optional[int] = None,
2349 start_time: Optional[float] = None,
2350 command_name: Optional[str] = None,
2351 ) -> None:
2352 """
2353 Close the connection, raise an exception if we were watching.
2355 The supported exceptions are already checked in the
2356 retry object so we don't need to do it here.
2358 After we disconnect the connection, it will try to reconnect and
2359 do a health check as part of the send_command logic(on connection level).
2360 """
2361 if error and failure_count <= conn.retry.get_retries():
2362 record_operation_duration(
2363 command_name=command_name,
2364 duration_seconds=time.monotonic() - start_time,
2365 server_address=getattr(conn, "host", None),
2366 server_port=getattr(conn, "port", None),
2367 db_namespace=str(conn.db),
2368 error=error,
2369 retry_attempts=failure_count,
2370 )
2371 conn.disconnect()
2372 # if we were watching a variable, the watch is no longer valid
2373 # since this connection has died. raise a WatchError, which
2374 # indicates the user should retry this transaction.
2375 if self.watching:
2376 raise WatchError(
2377 f"A {type(error).__name__} occurred while watching one or more keys"
2378 )
2380 def execute(self, raise_on_error: bool = True) -> List[Any]:
2381 """Execute all the commands in the current pipeline"""
2382 stack = self.command_stack
2383 if not stack and not self.watching:
2384 return []
2385 if self.scripts:
2386 self.load_scripts()
2387 if self.transaction or self.explicit_transaction:
2388 execute = self._execute_transaction
2389 operation_name = "MULTI"
2390 else:
2391 execute = self._execute_pipeline
2392 operation_name = "PIPELINE"
2394 conn = self.connection
2395 if not conn:
2396 conn = self.connection_pool.get_connection()
2397 # assign to self.connection so reset() releases the connection
2398 # back to the pool after we're done
2399 self.connection = conn
2401 # Start timing for observability
2402 start_time = time.monotonic()
2403 # Track actual retry attempts for error reporting
2404 actual_retry_attempts = [0]
2406 def failure_callback(error, failure_count):
2407 if is_debug_log_enabled():
2408 add_debug_log_for_operation_failure(conn, error, (operation_name,))
2409 actual_retry_attempts[0] = failure_count
2410 self._disconnect_raise_on_watching(
2411 conn, error, failure_count, start_time, operation_name
2412 )
2414 try:
2415 response = conn.retry.call_with_retry(
2416 lambda: execute(conn, stack, raise_on_error),
2417 failure_callback,
2418 with_failure_count=True,
2419 )
2421 record_operation_duration(
2422 command_name=operation_name,
2423 duration_seconds=time.monotonic() - start_time,
2424 server_address=getattr(conn, "host", None),
2425 server_port=getattr(conn, "port", None),
2426 db_namespace=str(conn.db),
2427 )
2428 return response
2429 except Exception as e:
2430 record_error_count(
2431 server_address=getattr(conn, "host", None),
2432 server_port=getattr(conn, "port", None),
2433 network_peer_address=getattr(conn, "host", None),
2434 network_peer_port=getattr(conn, "port", None),
2435 error_type=e,
2436 retry_attempts=actual_retry_attempts[0],
2437 is_internal=False,
2438 )
2439 raise
2441 finally:
2442 # in reset() the connection is disconnected before returned to the pool if
2443 # it is marked for reconnect.
2444 self.reset()
2446 def discard(self):
2447 """
2448 Flushes all previously queued commands
2449 See: https://redis.io/commands/DISCARD
2450 """
2451 self.execute_command("DISCARD")
2453 def watch(self, *names):
2454 """Watches the values at keys ``names``"""
2455 if self.explicit_transaction:
2456 raise RedisError("Cannot issue a WATCH after a MULTI")
2457 return self.execute_command("WATCH", *names)
2459 def unwatch(self) -> bool:
2460 """Unwatches all previously specified keys"""
2461 return self.watching and self.execute_command("UNWATCH") or True