Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/asyncio/client.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 asyncio
2import copy
3import inspect
4import logging
5import math
6import re
7import time
8import warnings
9from functools import cached_property
10from typing import (
11 TYPE_CHECKING,
12 Any,
13 AsyncIterator,
14 Awaitable,
15 Callable,
16 Dict,
17 Iterable,
18 List,
19 Literal,
20 Mapping,
21 MutableMapping,
22 Optional,
23 Protocol,
24 Self,
25 Sequence,
26 Set,
27 Tuple,
28 Type,
29 TypedDict,
30 TypeVar,
31 Union,
32 cast,
33)
35from redis._defaults import (
36 DEFAULT_RETRY_BASE,
37 DEFAULT_RETRY_CAP,
38 DEFAULT_RETRY_COUNT,
39 DEFAULT_SOCKET_CONNECT_TIMEOUT,
40 DEFAULT_SOCKET_READ_SIZE,
41 DEFAULT_SOCKET_TIMEOUT,
42)
43from redis._parsers.helpers import bool_ok, decode_info
44from redis._parsers.response_callbacks import _get_response_callback
45from redis.asyncio import _himport_exec
46from redis.asyncio.connection import (
47 AbstractConnection,
48 Connection,
49 ConnectionPool,
50 SSLConnection,
51 UnixDomainSocketConnection,
52)
53from redis.asyncio.lock import Lock
54from redis.asyncio.observability.recorder import (
55 record_error_count,
56 record_operation_duration,
57 record_pubsub_message,
58)
59from redis.asyncio.retry import Retry, _to_async_retry
60from redis.backoff import ExponentialWithJitterBackoff
61from redis.client import (
62 EMPTY_RESPONSE,
63 NEVER_DECODE,
64 AbstractRedis,
65 default_response_callbacks,
66)
67from redis.commands import (
68 AsyncCoreCommands,
69 AsyncRedisModuleCommands,
70 AsyncSentinelCommands,
71 list_or_args,
72)
73from redis.commands.helpers import parse_pubsub_subscriptions, pubsub_subscription_args
74from redis.credentials import CredentialProvider, StreamingCredentialProvider
75from redis.driver_info import DriverInfo, resolve_driver_info
76from redis.event import (
77 AfterPooledConnectionsInstantiationEvent,
78 AfterPubSubConnectionInstantiationEvent,
79 AfterSingleConnectionInstantiationEvent,
80 ClientType,
81 EventDispatcher,
82)
83from redis.exceptions import (
84 ConnectionError,
85 ExecAbortError,
86 PubSubError,
87 RedisError,
88 ResponseError,
89 WatchError,
90)
91from redis.himport import HImportRegistry, parse_himport_set_args
92from redis.maint_notifications import MaintNotificationsConfig
93from redis.observability.attributes import PubSubDirection
94from redis.typing import (
95 ChannelT,
96 EncodableT,
97 FieldT,
98 KeyT,
99 PubSubHandler,
100 Subscription,
101)
102from redis.utils import (
103 SENTINEL,
104 SSL_AVAILABLE,
105 _set_info_logger,
106 check_protocol_version,
107 command_text,
108 deprecated_args,
109 deprecated_function,
110 experimental_method,
111 safe_str,
112 str_if_bytes,
113 truncate_text,
114)
116if TYPE_CHECKING and SSL_AVAILABLE:
117 from ssl import TLSVersion, VerifyFlags, VerifyMode
118else:
119 TLSVersion = None
120 VerifyMode = None
121 VerifyFlags = None
123_KeyT = TypeVar("_KeyT", bound=KeyT)
124_ArgT = TypeVar("_ArgT", KeyT, EncodableT)
125_RedisT = TypeVar("_RedisT", bound="Redis")
126_NormalizeKeysT = TypeVar("_NormalizeKeysT", bound=Mapping[ChannelT, object])
127if TYPE_CHECKING:
128 from redis.asyncio.keyspace_notifications import AsyncKeyspaceNotifications
129 from redis.commands.core import Script
132logger = logging.getLogger(__name__)
135def is_debug_log_enabled():
136 return logger.isEnabledFor(logging.DEBUG)
139def add_debug_log_for_operation_failure(
140 connection: AbstractConnection,
141 error: BaseException | None = None,
142 args: Sequence[Any] | None = None,
143):
144 details = connection.extract_connection_details() if connection else "no connection"
145 prefix = (
146 f"{type(error).__name__} received" if error is not None else "Operation failed"
147 )
148 # Log only the command name - argument values can carry secrets
149 # (AUTH, CONFIG SET requirepass, ACL SETUSER) or user data.
150 command = f" for command {safe_str(args[0])}" if args else ""
151 suffix = f", error: {error}" if error is not None else ""
152 logger.debug(
153 f"{prefix}{command}, with connection: {connection}, details: {details}{suffix}",
154 )
157class ResponseCallbackProtocol(Protocol):
158 def __call__(self, response: Any, **kwargs): ...
161class AsyncResponseCallbackProtocol(Protocol):
162 async def __call__(self, response: Any, **kwargs): ...
165ResponseCallbackT = Union[ResponseCallbackProtocol, AsyncResponseCallbackProtocol]
168class Redis(
169 AbstractRedis, AsyncRedisModuleCommands, AsyncCoreCommands, AsyncSentinelCommands
170):
171 """
172 Implementation of the Redis protocol.
174 This abstract class provides a Python interface to all Redis commands
175 and an implementation of the Redis protocol.
177 Pipelines derive from this, implementing how
178 the commands are sent and received to the Redis server. Based on
179 configuration, an instance will either use a ConnectionPool, or
180 Connection object to talk to redis.
181 """
183 # Type discrimination marker for @overload self-type pattern
184 _is_async_client: Literal[True] = True
186 response_callbacks: MutableMapping[Union[str, bytes], ResponseCallbackT]
188 @classmethod
189 def from_url(
190 cls: Type["Redis"],
191 url: str,
192 single_connection_client: bool = False,
193 auto_close_connection_pool: Optional[bool] = None,
194 **kwargs,
195 ) -> "Redis":
196 """
197 Return a Redis client object configured from the given URL
199 For example::
201 redis://[[username]:[password]]@localhost:6379/0
202 rediss://[[username]:[password]]@localhost:6379/0
203 unix://[username@]/path/to/socket.sock?db=0[&password=password]
205 Three URL schemes are supported:
207 - `redis://` creates a TCP socket connection. See more at:
208 <https://www.iana.org/assignments/uri-schemes/prov/redis>
209 - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
210 <https://www.iana.org/assignments/uri-schemes/prov/rediss>
211 - ``unix://``: creates a Unix Domain Socket connection.
213 The username, password, hostname and path are passed through
214 urllib.parse.unquote in order to replace any percent-encoded values
215 with their corresponding characters. Querystring values are decoded
216 by urllib.parse.parse_qs and are not unquoted again.
218 There are several ways to specify a database number. The first value
219 found will be used:
221 1. A ``db`` querystring option, e.g. redis://localhost?db=0
223 2. If using the redis:// or rediss:// schemes, the path argument
224 of the url, e.g. redis://localhost/0
226 3. A ``db`` keyword argument to this function.
228 If none of these options are specified, the default db=0 is used.
230 All querystring options are cast to their appropriate Python types.
231 Boolean arguments can be specified with string values "True"/"False"
232 or "Yes"/"No". Values that cannot be properly cast cause a
233 ``ValueError`` to be raised. Once parsed, the querystring arguments
234 and keyword arguments are passed to the ``ConnectionPool``'s
235 class initializer. In the case of conflicting arguments, querystring
236 arguments always win.
238 """
239 connection_pool = ConnectionPool.from_url(url, **kwargs)
240 client = cls(
241 connection_pool=connection_pool,
242 single_connection_client=single_connection_client,
243 )
244 if auto_close_connection_pool is not None:
245 warnings.warn(
246 DeprecationWarning(
247 '"auto_close_connection_pool" is deprecated '
248 "since version 5.0.1. "
249 "Please create a ConnectionPool explicitly and "
250 "provide to the Redis() constructor instead."
251 )
252 )
253 else:
254 auto_close_connection_pool = True
255 client.auto_close_connection_pool = auto_close_connection_pool
256 return client
258 @classmethod
259 def from_pool(
260 cls: Type["Redis"],
261 connection_pool: ConnectionPool,
262 ) -> "Redis":
263 """
264 Return a Redis client from the given connection pool.
265 The Redis client will take ownership of the connection pool and
266 close it when the Redis client is closed.
268 Because the client closes (disconnects all connections in) the pool
269 when it is closed or garbage-collected, the pool must not be shared
270 with other clients. Constructing multiple clients from the same pool
271 via ``from_pool`` -- for example one per request across tasks -- is
272 not safe: when one client is closed it will disconnect connections
273 still in use by the others.
275 To share a single pool across clients, construct the pool explicitly
276 and manage its lifecycle instead. Unlike ``from_pool``, the plain
277 ``Redis(connection_pool=pool)`` constructor does not take ownership of
278 the pool and will not close it, so a pool created this way can be
279 safely shared across clients. ``ConnectionPool`` supports the async
280 context manager protocol for this::
282 async with ConnectionPool.from_url(url) as pool:
283 r = Redis(connection_pool=pool)
284 """
285 client = cls(
286 connection_pool=connection_pool,
287 )
288 client.auto_close_connection_pool = True
289 return client
291 @deprecated_args(
292 args_to_warn=["retry_on_timeout"],
293 reason="TimeoutError is included by default.",
294 version="6.0.0",
295 )
296 @deprecated_args(
297 args_to_warn=["lib_name", "lib_version"],
298 reason="Use 'driver_info' parameter instead. "
299 "lib_name and lib_version will be removed in a future version.",
300 )
301 def __init__(
302 self,
303 *,
304 host: str = "localhost",
305 port: int = 6379,
306 db: str | int = 0,
307 password: str | None = None,
308 socket_timeout: float | None = DEFAULT_SOCKET_TIMEOUT,
309 socket_connect_timeout: float | None = DEFAULT_SOCKET_CONNECT_TIMEOUT,
310 socket_read_size: int = DEFAULT_SOCKET_READ_SIZE,
311 socket_keepalive: bool | None = True,
312 socket_keepalive_options: Mapping[int, int | bytes] | object | None = SENTINEL,
313 connection_pool: ConnectionPool | None = None,
314 unix_socket_path: str | None = None,
315 encoding: str = "utf-8",
316 encoding_errors: str = "strict",
317 decode_responses: bool = False,
318 retry_on_timeout: bool = False,
319 retry: Retry = Retry(
320 backoff=ExponentialWithJitterBackoff(
321 base=DEFAULT_RETRY_BASE, cap=DEFAULT_RETRY_CAP
322 ),
323 retries=DEFAULT_RETRY_COUNT,
324 ),
325 retry_on_error: list | None = None,
326 ssl: bool = False,
327 ssl_keyfile: str | None = None,
328 ssl_certfile: str | None = None,
329 ssl_cert_reqs: "str | VerifyMode" = "required",
330 ssl_include_verify_flags: List["VerifyFlags"] | None = None,
331 ssl_exclude_verify_flags: List["VerifyFlags"] | None = None,
332 ssl_ca_certs: str | None = None,
333 ssl_ca_data: str | None = None,
334 ssl_ca_path: str | None = None,
335 ssl_check_hostname: bool = True,
336 ssl_min_version: "TLSVersion | None" = None,
337 ssl_ciphers: str | None = None,
338 ssl_password: str | None = None,
339 max_connections: int | None = None,
340 single_connection_client: bool = False,
341 health_check_interval: int = 0,
342 client_name: str | None = None,
343 lib_name: str | object | None = SENTINEL,
344 lib_version: str | object | None = SENTINEL,
345 driver_info: DriverInfo | object | None = SENTINEL,
346 username: str | None = None,
347 auto_close_connection_pool: bool | None = None,
348 redis_connect_func=None,
349 credential_provider: CredentialProvider | None = None,
350 protocol: int | None = None,
351 legacy_responses: bool = True,
352 event_dispatcher: EventDispatcher | None = None,
353 maint_notifications_config: MaintNotificationsConfig | None = None,
354 ):
355 """
356 Initialize a new Redis client.
358 To specify a retry policy for specific errors, you have two options:
360 1. Set the `retry_on_error` to a list of the error/s to retry on, and
361 you can also set `retry` to a valid `Retry` object(in case the default
362 one is not appropriate) - with this approach the retries will be triggered
363 on the default errors specified in the Retry object enriched with the
364 errors specified in `retry_on_error`.
366 2. Define a `Retry` object with configured 'supported_errors' and set
367 it to the `retry` parameter - with this approach you completely redefine
368 the errors on which retries will happen.
370 `retry_on_timeout` is deprecated - please include the TimeoutError
371 either in the Retry object or in the `retry_on_error` list.
373 When 'connection_pool' is provided - the retry configuration of the
374 provided pool will be used.
376 Args:
378 socket_keepalive:
379 if `True`, TCP keepalive is enabled for TCP socket connections.
380 Argument is ignored when connection_pool is provided.
381 socket_keepalive_options:
382 mapping of TCP keepalive socket option constants to values, for
383 example `{socket.TCP_KEEPIDLE: 30}`. If left unspecified, redis-py
384 uses TCP keepalive defaults when `socket_keepalive` is enabled:
385 idle 30 seconds, interval 5 seconds, and 3 probes. Platform-specific
386 options that are not available are skipped. Pass `None` or `{}` to
387 avoid setting additional TCP keepalive options. Argument is ignored
388 when connection_pool is provided.
389 maint_notifications_config:
390 configures the pool to support maintenance notifications - see
391 `redis.maint_notifications.MaintNotificationsConfig` for details.
392 Only supported with RESP3
393 If not provided and protocol is RESP3, the maintenance notifications
394 will be enabled by default (logic is included in the connection pool
395 initialization).
396 Argument is ignored when connection_pool is provided.
397 """
398 kwargs: Dict[str, Any]
399 if event_dispatcher is not None:
400 self._event_dispatcher = event_dispatcher
401 # auto_close_connection_pool only has an effect if connection_pool is
402 # None. It is assumed that if connection_pool is not None, the user
403 # wants to manage the connection pool themselves.
404 if auto_close_connection_pool is not None:
405 warnings.warn(
406 DeprecationWarning(
407 '"auto_close_connection_pool" is deprecated '
408 "since version 5.0.1. "
409 "Please create a ConnectionPool explicitly and "
410 "provide to the Redis() constructor instead."
411 )
412 )
413 else:
414 auto_close_connection_pool = True
416 if not connection_pool:
417 # Create internal connection pool, expected to be closed by Redis instance
418 if not retry_on_error:
419 retry_on_error = []
421 # Handle driver_info: if provided, use it; otherwise create from lib_name/lib_version.
422 computed_driver_info = resolve_driver_info(
423 driver_info, lib_name, lib_version
424 )
426 kwargs = {
427 "db": db,
428 "username": username,
429 "password": password,
430 "credential_provider": credential_provider,
431 "socket_timeout": socket_timeout,
432 "socket_read_size": socket_read_size,
433 "encoding": encoding,
434 "encoding_errors": encoding_errors,
435 "decode_responses": decode_responses,
436 "retry_on_error": retry_on_error,
437 "retry": copy.deepcopy(retry),
438 "max_connections": max_connections,
439 "health_check_interval": health_check_interval,
440 "client_name": client_name,
441 "driver_info": computed_driver_info,
442 "redis_connect_func": redis_connect_func,
443 "protocol": protocol,
444 "legacy_responses": legacy_responses,
445 }
446 # based on input, setup appropriate connection args
447 if unix_socket_path is not None:
448 if (
449 maint_notifications_config
450 and maint_notifications_config.enabled is True
451 ):
452 raise RedisError(
453 "Maintenance notifications are not supported with Unix "
454 "domain socket connections"
455 )
456 kwargs.update(
457 {
458 "path": unix_socket_path,
459 "connection_class": UnixDomainSocketConnection,
460 "maint_notifications_config": MaintNotificationsConfig(
461 enabled=False
462 ),
463 }
464 )
465 else:
466 # TCP specific options
467 kwargs.update(
468 {
469 "host": host,
470 "port": port,
471 "socket_connect_timeout": socket_connect_timeout,
472 "socket_keepalive": socket_keepalive,
473 "socket_keepalive_options": socket_keepalive_options,
474 }
475 )
477 if ssl:
478 kwargs.update(
479 {
480 "connection_class": SSLConnection,
481 "ssl_keyfile": ssl_keyfile,
482 "ssl_certfile": ssl_certfile,
483 "ssl_cert_reqs": ssl_cert_reqs,
484 "ssl_include_verify_flags": ssl_include_verify_flags,
485 "ssl_exclude_verify_flags": ssl_exclude_verify_flags,
486 "ssl_ca_certs": ssl_ca_certs,
487 "ssl_ca_data": ssl_ca_data,
488 "ssl_ca_path": ssl_ca_path,
489 "ssl_check_hostname": ssl_check_hostname,
490 "ssl_min_version": ssl_min_version,
491 "ssl_ciphers": ssl_ciphers,
492 "ssl_password": ssl_password,
493 }
494 )
495 maint_notifications_enabled = (
496 maint_notifications_config and maint_notifications_config.enabled
497 )
498 if maint_notifications_enabled and not check_protocol_version(protocol, 3):
499 raise RedisError(
500 "Maintenance notifications handlers on connection are only supported with RESP version 3"
501 )
502 if maint_notifications_config:
503 kwargs.update(
504 {
505 "maint_notifications_config": maint_notifications_config,
506 }
507 )
508 # This arg only used if no pool is passed in
509 self.auto_close_connection_pool = auto_close_connection_pool
510 connection_pool = ConnectionPool(**kwargs)
511 else:
512 # If a pool is passed in, do not close it
513 self.auto_close_connection_pool = False
515 # A user-supplied dispatcher always gets the event, for its own
516 # listeners. The default one is private to this client, so its only
517 # listener is the built-in re-auth one, which acts on a
518 # StreamingCredentialProvider alone: skip the no-op dispatch (and
519 # building the dispatcher) for any other provider.
520 if event_dispatcher is not None or (
521 credential_provider is not None
522 and isinstance(credential_provider, StreamingCredentialProvider)
523 ):
524 self._event_dispatcher.dispatch(
525 AfterPooledConnectionsInstantiationEvent(
526 [connection_pool], ClientType.ASYNC, credential_provider
527 )
528 )
530 self.connection_pool = connection_pool
531 self.single_connection_client = single_connection_client
532 self.connection: Optional[Connection] = None
534 connection_kwargs = self.connection_pool.connection_kwargs
535 self.response_callbacks = default_response_callbacks(
536 connection_kwargs.get("protocol"),
537 connection_kwargs.get("legacy_responses", True),
538 )
540 # If using a single connection client, we need to lock creation-of and use-of
541 # the client in order to avoid race conditions such as using asyncio.gather
542 # on a set of redis commands
543 self._single_conn_lock = asyncio.Lock()
545 # When used as an async context manager, we need to increment and decrement
546 # a usage counter so that we can close the connection pool when no one is
547 # using the client.
548 self._usage_counter = 0
549 self._usage_lock = asyncio.Lock()
551 @cached_property
552 def _event_dispatcher(self) -> EventDispatcher:
553 # Built on first use when the client was given no dispatcher; a
554 # dispatcher passed to __init__ is stored on the instance instead.
555 return EventDispatcher()
557 def __repr__(self):
558 return (
559 f"<{self.__class__.__module__}.{self.__class__.__name__}"
560 f"({self.connection_pool!r})>"
561 )
563 def __await__(self):
564 return self.initialize().__await__()
566 async def initialize(self: _RedisT) -> _RedisT:
567 if self.single_connection_client:
568 async with self._single_conn_lock:
569 if self.connection is None:
570 self.connection = await self.connection_pool.get_connection()
572 self._event_dispatcher.dispatch(
573 AfterSingleConnectionInstantiationEvent(
574 self.connection, ClientType.ASYNC, self._single_conn_lock
575 )
576 )
577 return self
579 def set_response_callback(self, command: str, callback: ResponseCallbackT):
580 """Set a custom Response Callback"""
581 self.response_callbacks[command] = callback
583 def get_encoder(self):
584 """Get the connection pool's encoder"""
585 return self.connection_pool.get_encoder()
587 def get_connection_kwargs(self):
588 """Get the connection's key-word arguments"""
589 return self.connection_pool.connection_kwargs
591 @property
592 def himport_registry(self) -> HImportRegistry:
593 """The client's HIMPORT fieldset registry (empty if none was declared).
595 Read-only: the registry is mutated only through the HIMPORT command methods.
596 """
597 return self.connection_pool.himport_registry
599 def get_retry(self) -> Optional[Retry]:
600 return self.get_connection_kwargs().get("retry")
602 def set_retry(self, retry: Retry) -> None:
603 retry = _to_async_retry(retry)
604 self.get_connection_kwargs().update({"retry": retry})
605 self.connection_pool.set_retry(retry)
607 def load_external_module(self, funcname, func):
608 """
609 This function can be used to add externally defined redis modules,
610 and their namespaces to the redis client.
612 funcname - A string containing the name of the function to create
613 func - The function, being added to this class.
615 ex: Assume that one has a custom redis module named foomod that
616 creates command named 'foo.dothing' and 'foo.anotherthing' in redis.
617 To load function functions into this namespace:
619 from redis import Redis
620 from foomodule import F
621 r = Redis()
622 r.load_external_module("foo", F)
623 r.foo().dothing('your', 'arguments')
625 For a concrete example see the reimport of the redisjson module in
626 tests/test_connection.py::test_loading_external_modules
627 """
628 setattr(self, funcname, func)
630 def pipeline(
631 self, transaction: bool = True, shard_hint: Optional[str] = None
632 ) -> "Pipeline":
633 """
634 Return a new pipeline object that can queue multiple commands for
635 later execution. ``transaction`` indicates whether all commands
636 should be executed atomically. Apart from making a group of operations
637 atomic, pipelines are useful for reducing the back-and-forth overhead
638 between the client and server.
639 """
640 return Pipeline(
641 self.connection_pool, self.response_callbacks, transaction, shard_hint
642 )
644 async def transaction(
645 self,
646 func: Callable[["Pipeline"], Union[Any, Awaitable[Any]]],
647 *watches: KeyT,
648 shard_hint: Optional[str] = None,
649 value_from_callable: bool = False,
650 watch_delay: Optional[float] = None,
651 ):
652 """
653 Convenience method for executing the callable `func` as a transaction
654 while watching all keys specified in `watches`. The 'func' callable
655 should expect a single argument which is a Pipeline object.
656 """
657 pipe: Pipeline
658 async with self.pipeline(True, shard_hint) as pipe:
659 while True:
660 try:
661 if watches:
662 await pipe.watch(*watches)
663 func_value = func(pipe)
664 if inspect.isawaitable(func_value):
665 func_value = await func_value
666 exec_value = await pipe.execute()
667 return func_value if value_from_callable else exec_value
668 except WatchError:
669 if watch_delay is not None and watch_delay > 0:
670 await asyncio.sleep(watch_delay)
671 continue
673 def lock(
674 self,
675 name: KeyT,
676 timeout: Optional[float] = None,
677 sleep: float = 0.1,
678 blocking: bool = True,
679 blocking_timeout: Optional[float] = None,
680 lock_class: Optional[Type[Lock]] = None,
681 thread_local: bool = True,
682 raise_on_release_error: bool = True,
683 ) -> Lock:
684 """
685 Return a new Lock object using key ``name`` that mimics
686 the behavior of threading.Lock.
688 If specified, ``timeout`` indicates a maximum life for the lock.
689 By default, it will remain locked until release() is called.
691 ``sleep`` indicates the amount of time to sleep per loop iteration
692 when the lock is in blocking mode and another client is currently
693 holding the lock.
695 ``blocking`` indicates whether calling ``acquire`` should block until
696 the lock has been acquired or to fail immediately, causing ``acquire``
697 to return False and the lock not being acquired. Defaults to True.
698 Note this value can be overridden by passing a ``blocking``
699 argument to ``acquire``.
701 ``blocking_timeout`` indicates the maximum amount of time in seconds to
702 spend trying to acquire the lock. A value of ``None`` indicates
703 continue trying forever. ``blocking_timeout`` can be specified as a
704 float or integer, both representing the number of seconds to wait.
706 ``lock_class`` forces the specified lock implementation. Note that as
707 of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
708 a Lua-based lock). So, it's unlikely you'll need this parameter, unless
709 you have created your own custom lock class.
711 ``thread_local`` indicates whether the lock token is placed in
712 thread-local storage. By default, the token is placed in thread local
713 storage so that a thread only sees its token, not a token set by
714 another thread. Consider the following timeline:
716 time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
717 thread-1 sets the token to "abc"
718 time: 1, thread-2 blocks trying to acquire `my-lock` using the
719 Lock instance.
720 time: 5, thread-1 has not yet completed. redis expires the lock
721 key.
722 time: 5, thread-2 acquired `my-lock` now that it's available.
723 thread-2 sets the token to "xyz"
724 time: 6, thread-1 finishes its work and calls release(). if the
725 token is *not* stored in thread local storage, then
726 thread-1 would see the token value as "xyz" and would be
727 able to successfully release the thread-2's lock.
729 ``raise_on_release_error`` indicates whether to raise an exception when
730 the lock is no longer owned when exiting the context manager. By default,
731 this is True, meaning an exception will be raised. If False, the warning
732 will be logged and the exception will be suppressed.
734 In some use cases it's necessary to disable thread local storage. For
735 example, if you have code where one thread acquires a lock and passes
736 that lock instance to a worker thread to release later. If thread
737 local storage isn't disabled in this case, the worker thread won't see
738 the token set by the thread that acquired the lock. Our assumption
739 is that these cases aren't common and as such default to using
740 thread local storage."""
741 if lock_class is None:
742 lock_class = Lock
743 return lock_class(
744 self,
745 name,
746 timeout=timeout,
747 sleep=sleep,
748 blocking=blocking,
749 blocking_timeout=blocking_timeout,
750 thread_local=thread_local,
751 raise_on_release_error=raise_on_release_error,
752 )
754 def pubsub(self, **kwargs) -> "PubSub":
755 """
756 Return a Publish/Subscribe object. With this object, you can
757 subscribe to channels and listen for messages that get published to
758 them.
759 """
760 return PubSub(
761 self.connection_pool, event_dispatcher=self._event_dispatcher, **kwargs
762 )
764 def keyspace_notifications(
765 self,
766 key_prefix: Union[str, bytes, None] = None,
767 ignore_subscribe_messages: bool = True,
768 ) -> "AsyncKeyspaceNotifications":
769 """
770 Return an :class:`~redis.asyncio.keyspace_notifications.AsyncKeyspaceNotifications`
771 object for subscribing to keyspace and keyevent notifications.
773 Note: Keyspace notifications must be enabled on the Redis server via
774 the ``notify-keyspace-events`` configuration option.
776 Args:
777 key_prefix: Optional prefix to filter and strip from keys in
778 notifications.
779 ignore_subscribe_messages: If True, subscribe/unsubscribe
780 confirmations are not returned by
781 get_message/listen.
782 """
783 from redis.asyncio.keyspace_notifications import AsyncKeyspaceNotifications
785 return AsyncKeyspaceNotifications(
786 self,
787 key_prefix=key_prefix,
788 ignore_subscribe_messages=ignore_subscribe_messages,
789 )
791 def monitor(self) -> "Monitor":
792 return Monitor(self.connection_pool)
794 def client(self) -> "Redis":
795 return self.__class__(
796 connection_pool=self.connection_pool, single_connection_client=True
797 )
799 async def __aenter__(self: _RedisT) -> _RedisT:
800 """
801 Async context manager entry. Increments a usage counter so that the
802 connection pool is only closed (via aclose()) when no context is using
803 the client.
804 """
805 await self._increment_usage()
806 try:
807 # Initialize the client (i.e. establish connection, etc.)
808 return await self.initialize()
809 except (Exception, asyncio.CancelledError):
810 # If initialization fails, decrement the counter to keep it in sync
811 await asyncio.shield(self._decrement_usage())
812 raise
814 async def _increment_usage(self) -> int:
815 """
816 Helper coroutine to increment the usage counter while holding the lock.
817 Returns the new value of the usage counter.
818 """
819 async with self._usage_lock:
820 self._usage_counter += 1
821 return self._usage_counter
823 async def _decrement_usage(self) -> int:
824 """
825 Helper coroutine to decrement the usage counter while holding the lock.
826 Returns the new value of the usage counter.
827 """
828 async with self._usage_lock:
829 self._usage_counter -= 1
830 return self._usage_counter
832 async def _release_usage(self) -> None:
833 """
834 Decrement the usage counter and close the client on the last exit.
836 Hold the lock through closing so a new context cannot use connections
837 that are still being disconnected by the previous context.
838 """
839 async with self._usage_lock:
840 self._usage_counter -= 1
841 if self._usage_counter == 0:
842 await self.aclose()
844 async def __aexit__(self, exc_type, exc_value, traceback):
845 """
846 Async context manager exit. Decrements a usage counter. If this is the
847 last exit (counter becomes zero), the client closes its connection pool.
848 """
849 await asyncio.shield(self._release_usage())
851 _DEL_MESSAGE = "Unclosed Redis client"
853 # passing _warnings and _grl as argument default since they may be gone
854 # by the time __del__ is called at shutdown
855 def __del__(
856 self,
857 _warn: Any = warnings.warn,
858 _grl: Any = asyncio.get_running_loop,
859 ) -> None:
860 if hasattr(self, "connection") and (self.connection is not None):
861 _warn(f"Unclosed client session {self!r}", ResourceWarning, source=self)
862 try:
863 context = {"client": self, "message": self._DEL_MESSAGE}
864 _grl().call_exception_handler(context)
865 except RuntimeError:
866 pass
867 self.connection._close()
869 async def aclose(self, close_connection_pool: Optional[bool] = None) -> None:
870 """
871 Closes Redis client connection
873 Args:
874 close_connection_pool:
875 decides whether to close the connection pool used by this Redis client,
876 overriding Redis.auto_close_connection_pool.
877 By default, let Redis.auto_close_connection_pool decide
878 whether to close the connection pool.
879 """
880 conn = self.connection
881 if conn:
882 self.connection = None
883 await self.connection_pool.release(conn)
884 if close_connection_pool or (
885 close_connection_pool is None and self.auto_close_connection_pool
886 ):
887 await self.connection_pool.aclose()
889 @deprecated_function(version="5.0.1", reason="Use aclose() instead", name="close")
890 async def close(self, close_connection_pool: Optional[bool] = None) -> None:
891 """
892 Alias for aclose(), for backwards compatibility
893 """
894 await self.aclose(close_connection_pool)
896 async def _send_command_parse_response(self, conn, command_name, *args, **options):
897 """
898 Send a command and parse the response
899 """
900 # HIMPORT SET is the one command whose wire form depends on per-connection
901 # state: the fieldset must be PREPAREd on this connection first, and any
902 # fieldset discarded since this connection last reconciled must be dropped.
903 # Handling it here (rather than in himport_set) lets himport_set reuse the
904 # full execute_command machinery — retry, disconnect-on-error, pooling — so
905 # a failed HIMPORT SET disconnects the connection like any other command.
906 # This per-command branch in the hot dispatch path is deliberate and has no
907 # cleaner alternative: this is the only seam where the concrete borrowed
908 # connection is known, and connection-scoped session setup can only happen
909 # once that connection is chosen. The overhead is one string compare per
910 # command.
911 himport_set = parse_himport_set_args(args)
912 if himport_set is not None:
913 # ``args`` is an HIMPORT SET in either the joined ("HIMPORT SET", key,
914 # ...) or split ("HIMPORT", "SET", key, ...) raw form; the operands come
915 # back at the right offsets for the form. A command with too few operands
916 # returns None and falls through to the normal send path so the server
917 # returns its arity error instead of a client-side IndexError here.
918 key, fieldset_name, values = himport_set
919 return await self._himport_execute_set(conn, key, fieldset_name, values)
920 await conn.send_command(*args)
921 return await self.parse_response(conn, command_name, **options)
923 async def _himport_reconcile_discards(self, conn):
924 """Delegate to the shared async HIMPORT executor."""
925 return await _himport_exec.reconcile_discards(self, conn)
927 async def _himport_prepare_and_set(
928 self, conn, key, fieldset_name, values, fieldset
929 ):
930 """Delegate to the shared async HIMPORT executor."""
931 return await _himport_exec.prepare_and_set(
932 self, conn, key, fieldset_name, values, fieldset
933 )
935 async def _himport_execute_set(self, conn, key, fieldset_name, values):
936 """Delegate to the shared async HIMPORT executor."""
937 return await _himport_exec.execute_set(self, conn, key, fieldset_name, values)
939 async def _close_connection(
940 self,
941 conn: Connection,
942 error: Optional[BaseException] = None,
943 failure_count: Optional[int] = None,
944 start_time: Optional[float] = None,
945 command_name: Optional[str] = None,
946 ):
947 """
948 Close the connection before retrying.
950 The supported exceptions are already checked in the
951 retry object so we don't need to do it here.
953 After we disconnect the connection, it will try to reconnect and
954 do a health check as part of the send_command logic(on connection level).
955 """
956 if (
957 error
958 and failure_count is not None
959 and failure_count <= conn.retry.get_retries()
960 ):
961 await record_operation_duration(
962 command_name=command_name,
963 duration_seconds=time.monotonic() - start_time,
964 server_address=getattr(conn, "host", None),
965 server_port=getattr(conn, "port", None),
966 db_namespace=str(conn.db),
967 error=error,
968 retry_attempts=failure_count,
969 )
971 await conn.disconnect(error=error, failure_count=failure_count)
973 # COMMAND EXECUTION AND PROTOCOL PARSING
974 async def execute_command(self, *args, **options):
975 """Execute a command and return a parsed response"""
976 await self.initialize()
977 pool = self.connection_pool
978 command_name = args[0]
979 conn = self.connection or await pool.get_connection()
981 # Start timing for observability
982 start_time = time.monotonic()
983 # Track actual retry attempts for error reporting
984 actual_retry_attempts = 0
986 def failure_callback(error, failure_count):
987 if is_debug_log_enabled():
988 add_debug_log_for_operation_failure(conn, error, args)
989 nonlocal actual_retry_attempts
990 actual_retry_attempts = failure_count
991 return self._close_connection(
992 conn, error, failure_count, start_time, command_name
993 )
995 if self.single_connection_client:
996 await self._single_conn_lock.acquire()
997 try:
998 result = await conn.retry.call_with_retry(
999 lambda: self._send_command_parse_response(
1000 conn, command_name, *args, **options
1001 ),
1002 failure_callback,
1003 with_failure_count=True,
1004 )
1006 await record_operation_duration(
1007 command_name=command_name,
1008 duration_seconds=time.monotonic() - start_time,
1009 server_address=getattr(conn, "host", None),
1010 server_port=getattr(conn, "port", None),
1011 db_namespace=str(conn.db),
1012 )
1013 return result
1014 except Exception as e:
1015 await record_error_count(
1016 server_address=getattr(conn, "host", None),
1017 server_port=getattr(conn, "port", None),
1018 network_peer_address=getattr(conn, "host", None),
1019 network_peer_port=getattr(conn, "port", None),
1020 error_type=e,
1021 retry_attempts=actual_retry_attempts,
1022 is_internal=False,
1023 )
1024 raise
1025 finally:
1026 try:
1027 if self.single_connection_client and conn and conn.should_reconnect():
1028 await self._close_connection(conn)
1029 await conn.connect()
1030 finally:
1031 if self.single_connection_client:
1032 self._single_conn_lock.release()
1033 if not self.connection:
1034 await pool.release(conn)
1036 async def parse_response(
1037 self, connection: Connection, command_name: Union[str, bytes], **options
1038 ):
1039 """Parses a response from the Redis server"""
1040 try:
1041 if NEVER_DECODE in options:
1042 response = await connection.read_response(disable_decoding=True)
1043 options.pop(NEVER_DECODE)
1044 if command_name == "INFO":
1045 response = decode_info(response, self.get_encoder())
1046 else:
1047 response = await connection.read_response()
1048 except ResponseError:
1049 if EMPTY_RESPONSE in options:
1050 return options[EMPTY_RESPONSE]
1051 raise
1053 if EMPTY_RESPONSE in options:
1054 options.pop(EMPTY_RESPONSE)
1056 # Remove keys entry, it needs only for cache.
1057 options.pop("keys", None)
1059 if connection._resp2_fallback:
1060 callback = _get_response_callback(
1061 self.response_callbacks, command_name, connection
1062 )
1063 else:
1064 callback = self.response_callbacks.get(command_name)
1065 if callback is not None:
1066 retval = callback(response, **options)
1067 return await retval if inspect.isawaitable(retval) else retval
1068 return response
1070 # HIMPORT orchestration (async mirror of redis.client.Redis). See
1071 # ``.agents/himport_client_support_spec.md``.
1073 @experimental_method()
1074 async def himport_prepare(
1075 self, fieldset_name: str, fields: Iterable[FieldT]
1076 ) -> bool:
1077 """Declare an HIMPORT fieldset for use by :meth:`himport_set`."""
1078 await self.initialize()
1079 fieldset = self.himport_registry.prepare(fieldset_name, fields)
1080 conn = self.connection
1081 if self.single_connection_client and conn is not None and conn.is_connected:
1082 await self.himport_prepare_internal(fieldset_name, fieldset.fields)
1083 conn._himport_prepared[fieldset_name] = fieldset.version
1084 return True
1086 @experimental_method()
1087 async def himport_discard(self, fieldset_name: str) -> int:
1088 """Remove a fieldset from the registry."""
1089 await self.initialize()
1090 removed = self.himport_registry.discard(fieldset_name)
1091 conn = self.connection
1092 if self.single_connection_client and conn is not None and conn.is_connected:
1093 if removed:
1094 await self.himport_discard_internal(fieldset_name)
1095 conn._himport_prepared.pop(fieldset_name, None)
1096 conn._himport_reconciled_revision = self.himport_registry.revision
1097 return 1 if removed else 0
1099 @experimental_method()
1100 async def himport_discard_all(self) -> int:
1101 """Remove all fieldsets from the registry."""
1102 await self.initialize()
1103 count = self.himport_registry.discard_all()
1104 conn = self.connection
1105 if self.single_connection_client and conn is not None and conn.is_connected:
1106 if count:
1107 await self.himport_discard_all_internal()
1108 conn._himport_prepared.clear()
1109 conn._himport_reconciled_revision = self.himport_registry.revision
1110 return count
1113StrictRedis = Redis
1116class MonitorCommandInfo(TypedDict):
1117 time: float
1118 db: int
1119 client_address: str
1120 client_port: str
1121 client_type: str
1122 command: str
1125class Monitor:
1126 """
1127 Monitor is useful for handling the MONITOR command to the redis server.
1128 next_command() method returns one command from monitor
1129 listen() method yields commands from monitor.
1130 """
1132 monitor_re = re.compile(r"\[(\d+) (.*?)\] (.*)")
1133 # Each argument is quoted with its backslashes and quotes escaped, so an
1134 # argument ending in a backslash ends in an escaped backslash, not an
1135 # escaped quote.
1136 command_re = re.compile(r'"([^"\\]*+(?:\\.[^"\\]*+)*+)"')
1138 def __init__(self, connection_pool: ConnectionPool):
1139 self.connection_pool = connection_pool
1140 self.connection: Optional[Connection] = None
1142 async def connect(self):
1143 if self.connection is None:
1144 self.connection = await self.connection_pool.get_connection()
1146 async def __aenter__(self):
1147 await self.connect()
1148 try:
1149 await self.connection.send_command("MONITOR")
1150 # check that monitor returns 'OK', but don't return it to user
1151 response = await self.connection.read_response()
1152 if not bool_ok(response):
1153 raise RedisError(f"MONITOR failed: {response}")
1154 except BaseException:
1155 try:
1156 await self.__aexit__()
1157 except Exception:
1158 pass
1159 raise
1160 return self
1162 async def __aexit__(self, *args):
1163 connection, self.connection = self.connection, None
1164 if connection is None:
1165 return
1166 try:
1167 await connection.disconnect()
1168 finally:
1169 await asyncio.shield(self.connection_pool.release(connection))
1171 async def next_command(self) -> MonitorCommandInfo:
1172 """Parse the response from a monitor command"""
1173 await self.connect()
1174 response = await self.connection.read_response()
1175 if isinstance(response, bytes):
1176 response = self.connection.encoder.decode(response, force=True)
1177 command_time, command_data = response.split(" ", 1)
1178 m = self.monitor_re.match(command_data)
1179 db_id, client_info, command = m.groups()
1180 command = " ".join(self.command_re.findall(command))
1181 # Redis escapes double quotes because each piece of the command
1182 # string is surrounded by double quotes. We don't have that
1183 # requirement so remove the escaping and leave the quote.
1184 command = command.replace('\\"', '"')
1186 if client_info == "lua":
1187 client_address = "lua"
1188 client_port = ""
1189 client_type = "lua"
1190 elif client_info.startswith("unix"):
1191 client_address = "unix"
1192 client_port = client_info[5:]
1193 client_type = "unix"
1194 else:
1195 if client_info == "":
1196 client_address = ""
1197 client_port = ""
1198 client_type = "unknown"
1199 else:
1200 # use rsplit as ipv6 addresses contain colons
1201 client_address, client_port = client_info.rsplit(":", 1)
1202 client_type = "tcp"
1203 return {
1204 "time": float(command_time),
1205 "db": int(db_id),
1206 "client_address": client_address,
1207 "client_port": client_port,
1208 "client_type": client_type,
1209 "command": command,
1210 }
1212 async def listen(self) -> AsyncIterator[MonitorCommandInfo]:
1213 """Listen for commands coming to the server."""
1214 while True:
1215 yield await self.next_command()
1218class _UncancellableFuture(asyncio.Future):
1219 """A future that ignores cancel(): awaiting it is not woken by Task.cancel()."""
1221 def cancel(self, msg: Any = None) -> bool:
1222 return False
1225class PubSub:
1226 """
1227 PubSub provides publish, subscribe and listen support to Redis channels.
1229 After subscribing to one or more channels, the listen() method will block
1230 until a message arrives on one of the subscribed channels. That message
1231 will be returned and it's safe to start listening again.
1232 """
1234 PUBLISH_MESSAGE_TYPES = ("message", "pmessage", "smessage")
1235 UNSUBSCRIBE_MESSAGE_TYPES = ("unsubscribe", "punsubscribe", "sunsubscribe")
1236 HEALTH_CHECK_MESSAGE = "redis-py-health-check"
1238 def __init__(
1239 self,
1240 connection_pool: ConnectionPool,
1241 shard_hint: Optional[str] = None,
1242 ignore_subscribe_messages: bool = False,
1243 encoder=None,
1244 push_handler_func: Optional[Callable] = None,
1245 event_dispatcher: Optional["EventDispatcher"] = None,
1246 ):
1247 if event_dispatcher is None:
1248 self._event_dispatcher = EventDispatcher()
1249 else:
1250 self._event_dispatcher = event_dispatcher
1251 self.connection_pool = connection_pool
1252 self.shard_hint = shard_hint
1253 self.ignore_subscribe_messages = ignore_subscribe_messages
1254 self.connection = None
1255 # we need to know the encoding options for this connection in order
1256 # to lookup channel and pattern names for callback handlers.
1257 self.encoder = encoder
1258 self.push_handler_func = push_handler_func
1259 if self.encoder is None:
1260 self.encoder = self.connection_pool.get_encoder()
1261 if self.encoder.decode_responses:
1262 self.health_check_response = [
1263 ["pong", self.HEALTH_CHECK_MESSAGE],
1264 self.HEALTH_CHECK_MESSAGE,
1265 ]
1266 else:
1267 self.health_check_response = [
1268 [b"pong", self.encoder.encode(self.HEALTH_CHECK_MESSAGE)],
1269 self.encoder.encode(self.HEALTH_CHECK_MESSAGE),
1270 ]
1271 if self.push_handler_func is None:
1272 _set_info_logger()
1273 self.channels = {}
1274 self.pending_unsubscribe_channels = set()
1275 self.patterns = {}
1276 self.pending_unsubscribe_patterns = set()
1277 self.shard_channels = {}
1278 self.pending_unsubscribe_shard_channels = set()
1279 self._lock = asyncio.Lock()
1281 async def __aenter__(self) -> Self:
1282 return self
1284 async def __aexit__(self, exc_type, exc_value, traceback) -> None:
1285 await self.aclose()
1287 def __del__(self) -> None:
1288 if self.connection:
1289 self.connection.deregister_connect_callback(self.on_connect)
1291 async def aclose(self) -> None:
1292 # In case a connection property does not yet exist
1293 # (due to a crash earlier in the Redis() constructor), return
1294 # immediately as there is nothing to clean-up.
1295 if not hasattr(self, "connection"):
1296 return
1297 # Shield the teardown so that cancelling the caller (e.g. a cancelled
1298 # task or anyio cancel scope exiting ``async with r.pubsub()``) cannot
1299 # stop it while it waits for the lock, disconnects, or releases: the
1300 # connection would otherwise never be returned to the pool. The caller
1301 # still sees the CancelledError.
1302 teardown = asyncio.ensure_future(self._aclose())
1303 try:
1304 await asyncio.shield(teardown)
1305 except asyncio.CancelledError:
1306 # Finish first so callers' locks (e.g. ClusterPubSub) outlive it.
1307 # Repeated cancels (anyio re-cancels on every loop turn) only mark
1308 # this task while it waits here, so it wakes once, when done.
1309 waiter = _UncancellableFuture(loop=asyncio.get_running_loop())
1310 teardown.add_done_callback(lambda _: waiter.set_result(None))
1311 try:
1312 await waiter
1313 except asyncio.CancelledError:
1314 pass # the cancels marked while waiting
1315 if not teardown.cancelled() and teardown.exception() is not None:
1316 logger.warning(
1317 "PubSub teardown failed after a cancellation",
1318 exc_info=teardown.exception(),
1319 )
1320 raise
1322 async def _aclose(self) -> None:
1323 async with self._lock:
1324 if self.connection:
1325 # Use nowait=True to avoid awaiting StreamWriter.wait_closed(),
1326 # which can deadlock when a concurrent reader task (e.g. one
1327 # running pubsub.run() or get_message(block=True)) still holds
1328 # the transport. See https://github.com/redis/redis-py/issues/3941
1329 await self.connection.disconnect(nowait=True)
1330 self.connection.deregister_connect_callback(self.on_connect)
1331 if self.push_handler_func is not None:
1332 # The handler is set on the parser of a pooled connection:
1333 # put the parser's own back, or the next PubSub that gets
1334 # this connection has its messages handed to ours
1335 parser = self.connection._get_parser()
1336 if (
1337 getattr(parser, "pubsub_push_handler_func", None)
1338 is self.push_handler_func
1339 ):
1340 parser.set_pubsub_push_handler(
1341 parser.handle_pubsub_push_response
1342 )
1343 # Detach before awaiting release, as Pipeline.reset() does, so
1344 # the pubsub never holds a connection that is back in the pool.
1345 connection, self.connection = self.connection, None
1346 await self.connection_pool.release(connection)
1347 self.channels = {}
1348 self.pending_unsubscribe_channels = set()
1349 self.patterns = {}
1350 self.pending_unsubscribe_patterns = set()
1351 self.shard_channels = {}
1352 self.pending_unsubscribe_shard_channels = set()
1354 @deprecated_function(version="5.0.1", reason="Use aclose() instead", name="close")
1355 async def close(self) -> None:
1356 """Alias for aclose(), for backwards compatibility"""
1357 await self.aclose()
1359 @deprecated_function(version="5.0.1", reason="Use aclose() instead", name="reset")
1360 async def reset(self) -> None:
1361 """Alias for aclose(), for backwards compatibility"""
1362 await self.aclose()
1364 async def _resubscribe(self, subscribed, subscribe_fn) -> None:
1365 # Replay handler-backed subscriptions as positional Subscription objects
1366 # so binary names never need to be decoded into keyword argument keys.
1367 subscriptions = pubsub_subscription_args(subscribed)
1368 if subscriptions:
1369 await subscribe_fn(*subscriptions)
1371 async def _resubscribe_shard_channels(self) -> None:
1372 await self._resubscribe(self.shard_channels, self.ssubscribe)
1374 async def on_connect(self, connection: Connection):
1375 """Re-subscribe to any channels and patterns previously subscribed to"""
1376 self.pending_unsubscribe_channels.clear()
1377 self.pending_unsubscribe_patterns.clear()
1378 self.pending_unsubscribe_shard_channels.clear()
1379 if self.channels:
1380 await self._resubscribe(self.channels, self.subscribe)
1381 if self.patterns:
1382 await self._resubscribe(self.patterns, self.psubscribe)
1383 if self.shard_channels:
1384 await self._resubscribe_shard_channels()
1386 @property
1387 def subscribed(self):
1388 """Indicates if there are subscriptions to any channels or patterns"""
1389 return bool(self.channels or self.patterns or self.shard_channels)
1391 async def execute_command(self, *args: EncodableT):
1392 """Execute a publish/subscribe command"""
1394 # NOTE: don't parse the response in this function -- it could pull a
1395 # legitimate message off the stack if the connection is already
1396 # subscribed to one or more channels
1398 await self.connect()
1399 connection = self.connection
1400 kwargs = {"check_health": not self.subscribed}
1401 await self._execute(connection, connection.send_command, *args, **kwargs)
1403 async def connect(self):
1404 """
1405 Ensure that the PubSub is connected
1406 """
1407 if self.connection is None:
1408 self.connection = await self.connection_pool.get_connection()
1409 # register a callback that re-subscribes to any channels we
1410 # were listening to when we were disconnected
1411 self.connection.register_connect_callback(self.on_connect)
1412 else:
1413 await self.connection.connect()
1414 if self.push_handler_func is not None:
1415 self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
1417 self._event_dispatcher.dispatch(
1418 AfterPubSubConnectionInstantiationEvent(
1419 self.connection, self.connection_pool, ClientType.ASYNC, self._lock
1420 )
1421 )
1423 async def _reconnect(
1424 self,
1425 conn,
1426 error: Optional[BaseException] = None,
1427 failure_count: Optional[int] = None,
1428 start_time: Optional[float] = None,
1429 command_name: Optional[str] = None,
1430 ):
1431 """
1432 The supported exceptions are already checked in the
1433 retry object so we don't need to do it here.
1435 In this error handler we are trying to reconnect to the server.
1436 """
1437 if (
1438 error
1439 and failure_count is not None
1440 and failure_count <= conn.retry.get_retries()
1441 ):
1442 if command_name:
1443 await record_operation_duration(
1444 command_name=command_name,
1445 duration_seconds=time.monotonic() - start_time,
1446 server_address=getattr(conn, "host", None),
1447 server_port=getattr(conn, "port", None),
1448 db_namespace=str(conn.db),
1449 error=error,
1450 retry_attempts=failure_count,
1451 )
1452 await conn.disconnect(error=error, failure_count=failure_count)
1453 await conn.connect()
1455 async def _execute(self, conn, command, *args, **kwargs):
1456 """
1457 Connect manually upon disconnection. If the Redis server is down,
1458 this will fail and raise a ConnectionError as desired.
1459 After reconnection, the ``on_connect`` callback should have been
1460 called by the # connection to resubscribe us to any channels and
1461 patterns we were previously listening to
1462 """
1463 if not len(args) == 0:
1464 command_name = args[0]
1465 else:
1466 command_name = None
1468 # Start timing for observability
1469 start_time = time.monotonic()
1470 # Track actual retry attempts for error reporting
1471 actual_retry_attempts = 0
1473 def failure_callback(error, failure_count):
1474 if is_debug_log_enabled():
1475 add_debug_log_for_operation_failure(conn, error, args)
1476 nonlocal actual_retry_attempts
1477 actual_retry_attempts = failure_count
1478 return self._reconnect(conn, error, failure_count, start_time, command_name)
1480 try:
1481 response = await conn.retry.call_with_retry(
1482 lambda: command(*args, **kwargs),
1483 failure_callback,
1484 with_failure_count=True,
1485 )
1487 if command_name:
1488 await record_operation_duration(
1489 command_name=command_name,
1490 duration_seconds=time.monotonic() - start_time,
1491 server_address=getattr(conn, "host", None),
1492 server_port=getattr(conn, "port", None),
1493 db_namespace=str(conn.db),
1494 )
1496 return response
1497 except Exception as e:
1498 await record_error_count(
1499 server_address=getattr(conn, "host", None),
1500 server_port=getattr(conn, "port", None),
1501 network_peer_address=getattr(conn, "host", None),
1502 network_peer_port=getattr(conn, "port", None),
1503 error_type=e,
1504 retry_attempts=actual_retry_attempts,
1505 is_internal=False,
1506 )
1507 raise
1509 async def parse_response(self, block: bool = True, timeout: float = 0):
1510 """
1511 Parse the response from a publish/subscribe command.
1513 Args:
1514 block: If True, block indefinitely until a message is available.
1515 If False, return immediately if no message is available.
1516 Default: True
1517 timeout: The timeout in seconds for reading a response when block=False.
1518 This parameter is ignored when block=True.
1519 Default: 0 (return immediately if no data available)
1521 Returns:
1522 The parsed response from the server, or None if no message is available
1523 within the timeout period (when block=False).
1525 Important:
1526 The block and timeout parameters work together:
1527 - When block=True: timeout is IGNORED, method blocks indefinitely
1528 - When block=False: timeout is USED, method returns after timeout expires
1530 Typically, you should use get_message(timeout=X) instead of calling
1531 parse_response() directly. The get_message() method automatically sets
1532 block=False when a timeout is provided, and block=True when timeout=None.
1534 Example:
1535 # Block indefinitely (timeout is ignored)
1536 response = await pubsub.parse_response(block=True, timeout=0.1)
1538 # Non-blocking with 0.1 second timeout
1539 response = await pubsub.parse_response(block=False, timeout=0.1)
1541 # Non-blocking, return immediately
1542 response = await pubsub.parse_response(block=False, timeout=0)
1544 # Recommended: use get_message() instead
1545 msg = await pubsub.get_message(timeout=0.1) # automatically sets block=False
1546 msg = await pubsub.get_message(timeout=None) # automatically sets block=True
1547 """
1548 conn = self.connection
1549 if conn is None:
1550 raise RuntimeError(
1551 "pubsub connection not set: "
1552 "did you forget to call subscribe() or psubscribe()?"
1553 )
1555 await self.check_health()
1557 if not conn.is_connected:
1558 await conn.connect()
1560 # Block=True: signal "no timeout" to conn.read_response via
1561 # math.inf. The connection treats math.inf as the per-read
1562 # opt-in for blocking indefinitely without falling back to
1563 # self.socket_timeout. Reconnect/AUTH/HELLO/resubscribe
1564 # operations performed by the retry layer continue to honor
1565 # self.socket_timeout because they do not pass math.inf.
1566 #
1567 # TODO(next-major): when the async Connection.read_response
1568 # default for ``timeout`` is changed to SENTINEL, passing
1569 # ``timeout=None`` from this method will become the natural
1570 # "no timeout" signal and the math.inf hand-off can be
1571 # removed. That swap is a breaking change to the
1572 # Connection.read_response signature so it must wait for a
1573 # major release.
1574 read_timeout = math.inf if block else timeout
1575 response = await self._execute(
1576 conn,
1577 conn.read_response,
1578 timeout=read_timeout,
1579 disconnect_on_error=False,
1580 push_request=True,
1581 )
1583 if conn.health_check_interval and response in self.health_check_response:
1584 # ignore the health check message as user might not expect it
1585 return None
1586 return response
1588 async def check_health(self):
1589 conn = self.connection
1590 if conn is None:
1591 raise RuntimeError(
1592 "pubsub connection not set: "
1593 "did you forget to call subscribe() or psubscribe()?"
1594 )
1596 if (
1597 conn.health_check_interval
1598 and asyncio.get_running_loop().time() > conn.next_health_check
1599 ):
1600 await conn.send_command(
1601 "PING", self.HEALTH_CHECK_MESSAGE, check_health=False
1602 )
1604 def _normalize_keys(self, data: _NormalizeKeysT) -> _NormalizeKeysT:
1605 """
1606 normalize channel/pattern names to be either bytes or strings
1607 based on whether responses are automatically decoded. this saves us
1608 from coercing the value for each message coming in.
1609 """
1610 encode = self.encoder.encode
1611 decode = self.encoder.decode
1612 return {decode(encode(k)): v for k, v in data.items()} # type: ignore[return-value] # noqa: E501
1614 async def psubscribe(
1615 self, *args: ChannelT | Subscription, **kwargs: PubSubHandler
1616 ) -> None:
1617 """
1618 Subscribe to channel patterns.
1619 Patterns supplied as keyword arguments expect a pattern name as the
1620 key and a callable as the value.
1621 ``Subscription`` objects can also be supplied positionally with an
1622 optional handler.
1623 A pattern's callable will be invoked automatically
1624 when a message is received on that pattern rather than producing a
1625 message via ``listen()``.
1626 """
1627 new_patterns = parse_pubsub_subscriptions(args, kwargs)
1628 ret_val = await self.execute_command("PSUBSCRIBE", *new_patterns.keys())
1629 # update the patterns dict AFTER we send the command. we don't want to
1630 # subscribe twice to these patterns, once for the command and again
1631 # for the reconnection.
1632 new_patterns = self._normalize_keys(new_patterns)
1633 self.patterns.update(new_patterns)
1634 self.pending_unsubscribe_patterns.difference_update(new_patterns)
1635 return ret_val
1637 def punsubscribe(self, *args: ChannelT) -> Awaitable:
1638 """
1639 Unsubscribe from the supplied patterns. If empty, unsubscribe from
1640 all patterns.
1641 """
1642 patterns: Iterable[ChannelT]
1643 if args:
1644 parsed_args = list_or_args(args[0], args[1:])
1645 patterns = self._normalize_keys(dict.fromkeys(parsed_args)).keys()
1646 else:
1647 parsed_args = []
1648 patterns = self.patterns
1649 self.pending_unsubscribe_patterns.update(patterns)
1650 return self.execute_command("PUNSUBSCRIBE", *parsed_args)
1652 async def subscribe(
1653 self, *args: ChannelT | Subscription, **kwargs: PubSubHandler
1654 ) -> None:
1655 """
1656 Subscribe to channels.
1657 Channels supplied as keyword arguments expect
1658 a channel name as the key and a callable as the value.
1659 ``Subscription`` objects can also be supplied positionally with an
1660 optional handler.
1661 A channel's callable will be invoked automatically
1662 when a message is received on that channel rather than producing a
1663 message via ``listen()`` or ``get_message()``.
1664 """
1665 new_channels = parse_pubsub_subscriptions(args, kwargs)
1666 ret_val = await self.execute_command("SUBSCRIBE", *new_channels.keys())
1667 # update the channels dict AFTER we send the command. we don't want to
1668 # subscribe twice to these channels, once for the command and again
1669 # for the reconnection.
1670 new_channels = self._normalize_keys(new_channels)
1671 self.channels.update(new_channels)
1672 self.pending_unsubscribe_channels.difference_update(new_channels)
1673 return ret_val
1675 def unsubscribe(self, *args) -> Awaitable:
1676 """
1677 Unsubscribe from the supplied channels. If empty, unsubscribe from
1678 all channels
1679 """
1680 if args:
1681 parsed_args = list_or_args(args[0], args[1:])
1682 channels = self._normalize_keys(dict.fromkeys(parsed_args))
1683 else:
1684 parsed_args = []
1685 channels = self.channels
1686 self.pending_unsubscribe_channels.update(channels)
1687 return self.execute_command("UNSUBSCRIBE", *parsed_args)
1689 async def ssubscribe(
1690 self,
1691 *args: ChannelT | Subscription,
1692 target_node: Any = None,
1693 **kwargs: PubSubHandler,
1694 ) -> None:
1695 """
1696 Subscribes the client to the specified shard channels.
1697 Channels supplied as keyword arguments expect a channel name as the key
1698 and a callable as the value.
1699 ``Subscription`` objects can also be supplied positionally
1700 with an optional handler.
1701 A channel's callable will be invoked automatically when a message
1702 is received on that channel rather than producing a message
1703 via ``listen()`` or ``get_sharded_message()``.
1704 """
1705 new_s_channels = parse_pubsub_subscriptions(args, kwargs)
1706 ret_val = await self.execute_command("SSUBSCRIBE", *new_s_channels.keys())
1707 # update the s_channels dict AFTER we send the command. we don't want to
1708 # subscribe twice to these channels, once for the command and again
1709 # for the reconnection.
1710 new_s_channels = self._normalize_keys(new_s_channels)
1711 self.shard_channels.update(new_s_channels)
1712 self.pending_unsubscribe_shard_channels.difference_update(new_s_channels)
1713 return ret_val
1715 def sunsubscribe(self, *args, target_node=None) -> Awaitable:
1716 """
1717 Unsubscribe from the supplied shard_channels. If empty, unsubscribe from
1718 all shard_channels
1719 """
1720 if args:
1721 args = list_or_args(args[0], args[1:])
1722 s_channels = self._normalize_keys(dict.fromkeys(args))
1723 else:
1724 s_channels = self.shard_channels
1725 self.pending_unsubscribe_shard_channels.update(s_channels)
1726 return self.execute_command("SUNSUBSCRIBE", *args)
1728 async def listen(self) -> AsyncIterator:
1729 """Listen for messages on channels this client has been subscribed to.
1731 Iteration ends once every channel and pattern has been unsubscribed
1732 from. If nothing is subscribed when iteration begins it ends
1733 immediately rather than waiting, so subscribe first: a listener
1734 started before any subscription finishes without yielding anything.
1735 """
1736 while self.subscribed:
1737 response = await self.handle_message(await self.parse_response(block=True))
1738 if response is not None:
1739 yield response
1741 async def get_message(
1742 self, ignore_subscribe_messages: bool = False, timeout: Optional[float] = 0.0
1743 ):
1744 """
1745 Get the next message if one is available, otherwise None.
1747 If timeout is specified, the system will wait for `timeout` seconds
1748 before returning. Timeout should be specified as a floating point
1749 number or None to wait indefinitely.
1750 """
1751 response = await self.parse_response(block=(timeout is None), timeout=timeout)
1752 if response:
1753 return await self.handle_message(response, ignore_subscribe_messages)
1754 return None
1756 get_sharded_message = get_message
1758 def ping(self, message=None) -> Awaitable[bool]:
1759 """
1760 Ping the Redis server to test connectivity.
1762 Sends a PING command to the Redis server and returns True if the server
1763 responds with "PONG".
1764 """
1765 args = ["PING", message] if message is not None else ["PING"]
1766 return self.execute_command(*args)
1768 async def handle_message(self, response, ignore_subscribe_messages=False):
1769 """
1770 Parses a pub/sub message. If the channel or pattern was subscribed to
1771 with a message handler, the handler is invoked instead of a parsed
1772 message being returned.
1773 """
1774 if response is None:
1775 return None
1776 if isinstance(response, bytes):
1777 response = [b"pong", response] if response != b"PONG" else [b"pong", b""]
1778 elif isinstance(response, str):
1779 response = ["pong", response] if response != "PONG" else ["pong", ""]
1780 message_type = str_if_bytes(response[0])
1781 if message_type == "pmessage":
1782 message = {
1783 "type": message_type,
1784 "pattern": response[1],
1785 "channel": response[2],
1786 "data": response[3],
1787 }
1788 elif message_type == "pong":
1789 message = {
1790 "type": message_type,
1791 "pattern": None,
1792 "channel": None,
1793 "data": response[1],
1794 }
1795 else:
1796 message = {
1797 "type": message_type,
1798 "pattern": None,
1799 "channel": response[1],
1800 "data": response[2],
1801 }
1803 if message_type in ["message", "pmessage"]:
1804 channel = str_if_bytes(message["channel"])
1805 await record_pubsub_message(
1806 direction=PubSubDirection.RECEIVE,
1807 channel=channel,
1808 )
1809 elif message_type == "smessage":
1810 channel = str_if_bytes(message["channel"])
1811 await record_pubsub_message(
1812 direction=PubSubDirection.RECEIVE,
1813 channel=channel,
1814 sharded=True,
1815 )
1817 # if this is an unsubscribe message, remove it from memory.
1818 # ``discard`` rather than ``remove``: the guard above already makes the
1819 # removal conditional, so the two are equivalent for a single caller -
1820 # but another writer can drop the same entry between the check and the
1821 # removal, and ``remove`` would then raise ``KeyError`` out of a pubsub
1822 # read that no caller catches. ``ClusterPubSub._detach_shard_channel``
1823 # is such a writer: it forgets a migrating shard channel locally,
1824 # deliberately without the per-node I/O lock this bookkeeping runs
1825 # under, because waiting for that lock stalls reconciliation behind a
1826 # poll's whole retry budget on the node being migrated away from.
1827 if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
1828 if message_type == "punsubscribe":
1829 pattern = response[1]
1830 if pattern in self.pending_unsubscribe_patterns:
1831 self.pending_unsubscribe_patterns.discard(pattern)
1832 self.patterns.pop(pattern, None)
1833 elif message_type == "sunsubscribe":
1834 s_channel = response[1]
1835 if s_channel in self.pending_unsubscribe_shard_channels:
1836 self.shard_channels.pop(s_channel, None)
1837 self.pending_unsubscribe_shard_channels.discard(s_channel)
1838 else:
1839 channel = response[1]
1840 if channel in self.pending_unsubscribe_channels:
1841 self.pending_unsubscribe_channels.discard(channel)
1842 self.channels.pop(channel, None)
1844 if message_type in self.PUBLISH_MESSAGE_TYPES:
1845 # if there's a message handler, invoke it
1846 if message_type == "pmessage":
1847 handler = self.patterns.get(message["pattern"], None)
1848 elif message_type == "smessage":
1849 handler = self.shard_channels.get(message["channel"], None)
1850 else:
1851 handler = self.channels.get(message["channel"], None)
1852 if handler:
1853 if inspect.iscoroutinefunction(handler):
1854 await handler(message)
1855 else:
1856 handler(message)
1857 return None
1858 elif message_type != "pong":
1859 # this is a subscribe/unsubscribe message. ignore if we don't
1860 # want them
1861 if ignore_subscribe_messages or self.ignore_subscribe_messages:
1862 return None
1864 return message
1866 async def run(
1867 self,
1868 *,
1869 exception_handler: Optional["PSWorkerThreadExcHandlerT"] = None,
1870 poll_timeout: float = 1.0,
1871 pubsub=None,
1872 ) -> None:
1873 """Process pub/sub messages using registered callbacks.
1875 This is the equivalent of :py:meth:`redis.PubSub.run_in_thread` in
1876 redis-py, but it is a coroutine. To launch it as a separate task, use
1877 ``asyncio.create_task``:
1879 >>> task = asyncio.create_task(pubsub.run())
1881 To shut it down, use asyncio cancellation:
1883 >>> task.cancel()
1884 >>> await task
1885 """
1886 for channel, handler in self.channels.items():
1887 if handler is None:
1888 raise PubSubError(f"Channel: '{channel}' has no handler registered")
1889 for pattern, handler in self.patterns.items():
1890 if handler is None:
1891 raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
1892 for s_channel, handler in self.shard_channels.items():
1893 if handler is None:
1894 raise PubSubError(
1895 f"Shard Channel: '{s_channel}' has no handler registered"
1896 )
1898 await self.connect()
1899 while True:
1900 try:
1901 if pubsub is None:
1902 await self.get_message(
1903 ignore_subscribe_messages=True, timeout=poll_timeout
1904 )
1905 else:
1906 await pubsub.get_message(
1907 ignore_subscribe_messages=True, timeout=poll_timeout
1908 )
1909 except asyncio.CancelledError:
1910 raise
1911 except BaseException as e:
1912 if exception_handler is None:
1913 raise
1914 res = exception_handler(e, self)
1915 if inspect.isawaitable(res):
1916 await res
1917 # Ensure that other tasks on the event loop get a chance to run
1918 # if we didn't have to block for I/O anywhere.
1919 await asyncio.sleep(0)
1922class PubsubWorkerExceptionHandler(Protocol):
1923 def __call__(self, e: BaseException, pubsub: PubSub): ...
1926class AsyncPubsubWorkerExceptionHandler(Protocol):
1927 async def __call__(self, e: BaseException, pubsub: PubSub): ...
1930PSWorkerThreadExcHandlerT = Union[
1931 PubsubWorkerExceptionHandler, AsyncPubsubWorkerExceptionHandler
1932]
1935CommandT = Tuple[Tuple[Union[str, bytes], ...], Mapping[str, Any]]
1936CommandStackT = List[CommandT]
1938# Packing at least this many commands is enough CPU work to be worth moving
1939# off the event loop; ~1000 tiny commands pack in about 1ms, which already
1940# outgrows the asyncio.to_thread dispatch. Smaller pipelines keep the
1941# existing synchronous path and never touch the loop's default executor.
1942_PIPELINE_PACK_OFFLOAD_MIN_COMMANDS = 1000
1944# Reading a reply only suspends when the socket buffer is empty, so a large
1945# pipeline whose replies are already buffered never yields while it reads them
1946# or runs their callbacks (#3416). A pipeline of at least this many commands
1947# yields to the event loop once per this many commands in those loops, but not
1948# after the last one: ~1000 replies take a few ms to process, and a yield costs
1949# a few microseconds. Smaller pipelines never yield.
1950_PIPELINE_YIELD_MIN_COMMANDS = 1000
1953async def _pack_pipeline_commands(
1954 connection: Connection, commands: Sequence[Iterable[EncodableT]]
1955) -> List[bytes]:
1956 """Pack commands, off the event loop for large batches.
1958 Packing is pure CPU work and can block the event loop for seconds on
1959 very large pipelines (#3416), but handing a batch to a worker thread
1960 also costs a dispatch. Small batches are packed inline; only batches
1961 at or above ``_PIPELINE_PACK_OFFLOAD_MIN_COMMANDS`` are offloaded.
1962 """
1963 if len(commands) < _PIPELINE_PACK_OFFLOAD_MIN_COMMANDS:
1964 return connection.pack_commands(commands)
1965 return await asyncio.to_thread(connection.pack_commands, commands)
1968async def _yield_in_read_loop(connection: Connection) -> None:
1969 """Yield to the event loop from a loop that reads a batch of replies.
1971 The task can be cancelled at the yield: a task.cancel(), an expired
1972 asyncio.timeout() or wait_for() around execute(), or Ctrl+C under
1973 asyncio.run(). The rest of the batch's replies (for a transaction, the rest
1974 of the QUEUED replies and the EXEC reply) are still on the socket, so the
1975 connection is dropped rather than let them be read as the reply to a later
1976 command, such as the UNWATCH that reset() sends while WATCHing, or by the
1977 next caller that borrows it from the pool.
1978 """
1979 try:
1980 await asyncio.sleep(0)
1981 except asyncio.CancelledError:
1982 await connection.disconnect(nowait=True)
1983 raise
1986class Pipeline(Redis): # lgtm [py/init-calls-subclass]
1987 """
1988 Pipelines provide a way to transmit multiple commands to the Redis server
1989 in one transmission. This is convenient for batch processing, such as
1990 saving all the values in a list to Redis.
1992 All commands executed within a pipeline(when running in transactional mode,
1993 which is the default behavior) are wrapped with MULTI and EXEC
1994 calls. This guarantees all commands executed in the pipeline will be
1995 executed atomically.
1997 Any command raising an exception does *not* halt the execution of
1998 subsequent commands in the pipeline. Instead, the exception is caught
1999 and its instance is placed into the response list returned by execute().
2000 Code iterating over the response list should be able to deal with an
2001 instance of an exception as a potential value. In general, these will be
2002 ResponseError exceptions, such as those raised when issuing a command
2003 on a key of a different datatype.
2004 """
2006 UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
2008 def __init__(
2009 self,
2010 connection_pool: ConnectionPool,
2011 response_callbacks: MutableMapping[Union[str, bytes], ResponseCallbackT],
2012 transaction: bool,
2013 shard_hint: Optional[str],
2014 ):
2015 self.connection_pool = connection_pool
2016 self.connection = None
2017 self.response_callbacks = response_callbacks
2018 self.is_transaction = transaction
2019 self.shard_hint = shard_hint
2020 self.watching = False
2021 self.command_stack: CommandStackT = []
2022 self.scripts: Set[Script] = set()
2023 self.explicit_transaction = False
2025 async def __aenter__(self: _RedisT) -> _RedisT:
2026 return self
2028 async def __aexit__(self, exc_type, exc_value, traceback):
2029 await self.reset()
2031 def __await__(self):
2032 return self._async_self().__await__()
2034 _DEL_MESSAGE = "Unclosed Pipeline client"
2036 def __len__(self):
2037 return len(self.command_stack)
2039 def __bool__(self):
2040 """Pipeline instances should always evaluate to True"""
2041 return True
2043 async def _async_self(self):
2044 return self
2046 async def reset(self):
2047 self.command_stack = []
2048 self.scripts = set()
2049 try:
2050 # make sure to reset the connection state in the event that we were
2051 # watching something. A dropped connection has already lost its
2052 # WATCHes, so skip the UNWATCH instead of reconnecting to send it.
2053 if self.watching and self.connection and self.connection.is_connected:
2054 try:
2055 # call this manually since our unwatch or
2056 # immediate_execute_command methods can call reset()
2057 await self.connection.send_command("UNWATCH")
2058 await self.connection.read_response()
2059 except ConnectionError:
2060 # disconnect will also remove any previous WATCHes
2061 if self.connection:
2062 await self.connection.disconnect()
2063 except asyncio.CancelledError:
2064 # Disconnect so any unread UNWATCH reply does not get
2065 # served to the next caller that takes the connection.
2066 if self.connection:
2067 await self.connection.disconnect()
2068 raise
2069 finally:
2070 self.watching = False
2071 self.explicit_transaction = False
2072 # We can safely return the connection to the pool here since we're
2073 # sure we're no longer WATCHing anything. Detach self.connection
2074 # before awaiting release: if a second cancel aborts the await,
2075 # the pipeline must not be left holding a reference to a
2076 # connection that is being returned to the pool. release() itself
2077 # is cancel-safe, so it needs no shield.
2078 if self.connection:
2079 connection, self.connection = self.connection, None
2080 await self.connection_pool.release(connection)
2082 async def aclose(self) -> None:
2083 """Alias for reset(), a standard method name for cleanup"""
2084 await self.reset()
2086 def multi(self):
2087 """
2088 Start a transactional block of the pipeline after WATCH commands
2089 are issued. End the transactional block with `execute`.
2090 """
2091 if self.explicit_transaction:
2092 raise RedisError("Cannot issue nested calls to MULTI")
2093 if self.command_stack:
2094 raise RedisError(
2095 "Commands without an initial WATCH have already been issued"
2096 )
2097 self.explicit_transaction = True
2099 def execute_command(
2100 self, *args, **kwargs
2101 ) -> Union["Pipeline", Awaitable["Pipeline"]]:
2102 if (self.watching or args[0] == "WATCH") and not self.explicit_transaction:
2103 return self.immediate_execute_command(*args, **kwargs)
2104 return self.pipeline_execute_command(*args, **kwargs)
2106 async def _disconnect_reset_raise_on_watching(
2107 self,
2108 conn: Connection,
2109 error: Exception,
2110 failure_count: Optional[int] = None,
2111 start_time: Optional[float] = None,
2112 command_name: Optional[str] = None,
2113 ) -> None:
2114 """
2115 Close the connection reset watching state and
2116 raise an exception if we were watching.
2118 The supported exceptions are already checked in the
2119 retry object so we don't need to do it here.
2121 After we disconnect the connection, it will try to reconnect and
2122 do a health check as part of the send_command logic(on connection level).
2123 """
2124 if (
2125 error
2126 and failure_count is not None
2127 and failure_count <= conn.retry.get_retries()
2128 ):
2129 await record_operation_duration(
2130 command_name=command_name,
2131 duration_seconds=time.monotonic() - start_time,
2132 server_address=getattr(conn, "host", None),
2133 server_port=getattr(conn, "port", None),
2134 db_namespace=str(conn.db),
2135 error=error,
2136 retry_attempts=failure_count,
2137 )
2138 await conn.disconnect(error=error, failure_count=failure_count)
2139 # if we were already watching a variable, the watch is no longer
2140 # valid since this connection has died. raise a WatchError, which
2141 # indicates the user should retry this transaction.
2142 if self.watching:
2143 await self.reset()
2144 raise WatchError(
2145 f"A {type(error).__name__} occurred while watching one or more keys"
2146 )
2148 async def immediate_execute_command(self, *args, **options):
2149 """
2150 Execute a command immediately, but don't auto-retry on the supported
2151 errors for retry if we're already WATCHing a variable.
2152 Used when issuing WATCH or subsequent commands retrieving their values but before
2153 MULTI is called.
2154 """
2155 command_name = args[0]
2156 conn = self.connection
2157 # if this is the first call, we need a connection
2158 if not conn:
2159 conn = await self.connection_pool.get_connection()
2160 self.connection = conn
2162 # Start timing for observability
2163 start_time = time.monotonic()
2164 # Track actual retry attempts for error reporting
2165 actual_retry_attempts = 0
2167 def failure_callback(error, failure_count):
2168 if is_debug_log_enabled():
2169 add_debug_log_for_operation_failure(conn, error, args)
2170 nonlocal actual_retry_attempts
2171 actual_retry_attempts = failure_count
2172 return self._disconnect_reset_raise_on_watching(
2173 conn, error, failure_count, start_time, command_name
2174 )
2176 try:
2177 response = await conn.retry.call_with_retry(
2178 lambda: self._send_command_parse_response(
2179 conn, command_name, *args, **options
2180 ),
2181 failure_callback,
2182 with_failure_count=True,
2183 )
2185 await record_operation_duration(
2186 command_name=command_name,
2187 duration_seconds=time.monotonic() - start_time,
2188 server_address=getattr(conn, "host", None),
2189 server_port=getattr(conn, "port", None),
2190 db_namespace=str(conn.db),
2191 )
2193 return response
2194 except Exception as e:
2195 await record_error_count(
2196 server_address=getattr(conn, "host", None),
2197 server_port=getattr(conn, "port", None),
2198 network_peer_address=getattr(conn, "host", None),
2199 network_peer_port=getattr(conn, "port", None),
2200 error_type=e,
2201 retry_attempts=actual_retry_attempts,
2202 is_internal=False,
2203 )
2204 raise
2206 def pipeline_execute_command(self, *args, **options):
2207 """
2208 Stage a command to be executed when execute() is next called
2210 Returns the current Pipeline object back so commands can be
2211 chained together, such as:
2213 pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
2215 At some other point, you can then run: pipe.execute(),
2216 which will execute all commands queued in the pipe.
2217 """
2218 self.command_stack.append((args, options))
2219 return self
2221 async def _himport_prepare_pipeline(self, conn, commands):
2222 """Delegate to the shared async HIMPORT executor."""
2223 await _himport_exec.prepare_pipeline(self, conn, [args for args, _ in commands])
2225 async def _execute_transaction( # noqa: C901
2226 self, connection: Connection, commands: CommandStackT, raise_on_error
2227 ):
2228 # Ensure fieldsets referenced by buffered HIMPORT SETs are prepared on this
2229 # connection before the MULTI/EXEC block (session state, not transactional).
2230 await self._himport_prepare_pipeline(connection, commands)
2231 pre: CommandT = (("MULTI",), {})
2232 post: CommandT = (("EXEC",), {})
2233 cmds = (pre, *commands, post)
2234 all_cmds = await _pack_pipeline_commands(
2235 connection,
2236 [args for args, options in cmds if EMPTY_RESPONSE not in options],
2237 )
2238 await connection.send_packed_command(all_cmds)
2239 errors = []
2240 may_yield = len(commands) >= _PIPELINE_YIELD_MIN_COMMANDS
2242 # parse off the response for MULTI
2243 # NOTE: we need to handle ResponseErrors here and continue
2244 # so that we read all the additional command messages from
2245 # the socket
2246 try:
2247 await self.parse_response(connection, "_")
2248 except ResponseError as err:
2249 errors.append((0, err))
2251 # and all the other commands
2252 for i, command in enumerate(commands):
2253 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS:
2254 await _yield_in_read_loop(connection)
2255 if EMPTY_RESPONSE in command[1]:
2256 errors.append((i, command[1][EMPTY_RESPONSE]))
2257 else:
2258 try:
2259 await self.parse_response(connection, "_")
2260 except ResponseError as err:
2261 self.annotate_exception(err, i + 1, command[0])
2262 errors.append((i, err))
2264 # parse the EXEC.
2265 try:
2266 response = await self.parse_response(connection, "_")
2267 except ExecAbortError as err:
2268 if errors:
2269 raise errors[0][1] from err
2270 raise
2272 # EXEC clears any watched keys
2273 self.watching = False
2275 if response is None:
2276 raise WatchError("Watched variable changed.") from None
2278 # put any parse errors into the response
2279 for i, e in errors:
2280 response.insert(i, e)
2282 if len(response) != len(commands):
2283 if self.connection:
2284 await self.connection.disconnect()
2285 raise ResponseError(
2286 "Wrong number of response items from pipeline execution"
2287 ) from None
2289 # find any errors in the response and raise if necessary
2290 if raise_on_error:
2291 self.raise_first_error(commands, response)
2293 # We have to run response callbacks manually
2294 data = []
2295 for i, (r, cmd) in enumerate(zip(response, commands)):
2296 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS:
2297 await asyncio.sleep(0)
2298 if not isinstance(r, Exception):
2299 args, options = cmd
2300 command_name = args[0]
2302 # Remove keys entry, it needs only for cache.
2303 options.pop("keys", None)
2305 if connection._resp2_fallback:
2306 callback = _get_response_callback(
2307 self.response_callbacks, command_name, connection
2308 )
2309 else:
2310 callback = self.response_callbacks.get(command_name)
2311 if callback is not None:
2312 r = callback(r, **options)
2313 if inspect.isawaitable(r):
2314 r = await r
2315 data.append(r)
2316 return data
2318 async def _execute_pipeline(
2319 self, connection: Connection, commands: CommandStackT, raise_on_error: bool
2320 ):
2321 # Fold any first-use HIMPORT PREPAREs for referenced fieldsets into the same
2322 # packed write as the queued commands, so a pipeline that lands on a fresh or
2323 # reconnected connection stays a single round trip (the batched write bypasses
2324 # the per-command lazy PREPARE path). Deferred-discard reconciliation happens
2325 # inside pipeline_prepares and only touches the socket when discards are
2326 # actually pending.
2327 fieldsets = await _himport_exec.pipeline_prepares(
2328 self, connection, [args for args, _ in commands]
2329 )
2330 preflight = _himport_exec.prepare_wire_commands(fieldsets)
2331 # build up all commands into a single request to increase network perf
2332 all_cmds = await _pack_pipeline_commands(
2333 connection, preflight + [args for args, _ in commands]
2334 )
2335 await connection.send_packed_command(all_cmds)
2337 # Drain the leading PREPARE replies (bookkeeping + capture the first error)
2338 # before the queued replies. Everything on the wire is read before raising so
2339 # the pooled socket never desyncs.
2340 prep_error = await _himport_exec.drain_pipeline_prepares(
2341 self, connection, fieldsets
2342 )
2344 response = []
2345 may_yield = len(commands) >= _PIPELINE_YIELD_MIN_COMMANDS
2346 try:
2347 for i, (args, options) in enumerate(commands):
2348 if may_yield and i and not i % _PIPELINE_YIELD_MIN_COMMANDS:
2349 await asyncio.sleep(0)
2350 try:
2351 response.append(
2352 await self.parse_response(connection, args[0], **options)
2353 )
2354 except ResponseError as e:
2355 response.append(e)
2356 except BaseException:
2357 # A response callback raised, or the task was cancelled at the yield,
2358 # so the replies of the rest of the batch are still on the socket.
2359 # Drop the connection rather than hand them to the next caller that
2360 # borrows it from the pool.
2361 await connection.disconnect(nowait=True)
2362 raise
2364 # A PREPARE failure (rare: an invalid fieldset definition) is a hard error,
2365 # raised regardless of raise_on_error as it was before folding -- only now
2366 # every reply has already been drained.
2367 if prep_error is not None:
2368 raise prep_error
2369 if raise_on_error:
2370 self.raise_first_error(commands, response)
2371 return response
2373 def raise_first_error(self, commands: CommandStackT, response: Iterable[Any]):
2374 for i, r in enumerate(response):
2375 if isinstance(r, ResponseError):
2376 self.annotate_exception(r, i + 1, commands[i][0])
2377 raise r
2379 def annotate_exception(
2380 self, exception: Exception, number: int, command: Iterable[object]
2381 ) -> None:
2382 cmd = command_text(command)
2383 msg = (
2384 f"Command # {number} ({truncate_text(cmd)}) "
2385 f"of pipeline caused error: {exception.args[0]}"
2386 )
2387 exception.args = (msg,) + exception.args[1:]
2389 async def parse_response(
2390 self, connection: Connection, command_name: Union[str, bytes], **options
2391 ):
2392 result = await super().parse_response(connection, command_name, **options)
2393 if command_name in self.UNWATCH_COMMANDS:
2394 self.watching = False
2395 elif command_name == "WATCH":
2396 self.watching = True
2397 return result
2399 async def load_scripts(self):
2400 # make sure all scripts that are about to be run on this pipeline exist
2401 scripts = list(self.scripts)
2402 immediate = self.immediate_execute_command
2403 shas = [s.sha for s in scripts]
2404 # we can't use the normal script_* methods because they would just
2405 # get buffered in the pipeline.
2406 exists = await immediate("SCRIPT EXISTS", *shas)
2407 if not all(exists):
2408 for s, exist in zip(scripts, exists):
2409 if not exist:
2410 s.sha = await immediate("SCRIPT LOAD", s.script)
2412 async def _disconnect_raise_on_watching(
2413 self,
2414 conn: Connection,
2415 error: Exception,
2416 failure_count: Optional[int] = None,
2417 start_time: Optional[float] = None,
2418 command_name: Optional[str] = None,
2419 ):
2420 """
2421 Close the connection, raise an exception if we were watching.
2423 The supported exceptions are already checked in the
2424 retry object so we don't need to do it here.
2426 After we disconnect the connection, it will try to reconnect and
2427 do a health check as part of the send_command logic(on connection level).
2428 """
2429 if (
2430 error
2431 and failure_count is not None
2432 and failure_count <= conn.retry.get_retries()
2433 ):
2434 await record_operation_duration(
2435 command_name=command_name,
2436 duration_seconds=time.monotonic() - start_time,
2437 server_address=getattr(conn, "host", None),
2438 server_port=getattr(conn, "port", None),
2439 db_namespace=str(conn.db),
2440 error=error,
2441 retry_attempts=failure_count,
2442 )
2443 await conn.disconnect(error=error, failure_count=failure_count)
2444 # if we were watching a variable, the watch is no longer valid
2445 # since this connection has died. raise a WatchError, which
2446 # indicates the user should retry this transaction.
2447 if self.watching:
2448 raise WatchError(
2449 f"A {type(error).__name__} occurred while watching one or more keys"
2450 )
2452 async def execute(self, raise_on_error: bool = True) -> List[Any]:
2453 """Execute all the commands in the current pipeline"""
2454 stack = self.command_stack
2455 if not stack and not self.watching:
2456 return []
2457 if self.scripts:
2458 await self.load_scripts()
2459 if self.is_transaction or self.explicit_transaction:
2460 execute = self._execute_transaction
2461 operation_name = "MULTI"
2462 else:
2463 execute = self._execute_pipeline
2464 operation_name = "PIPELINE"
2466 conn = self.connection
2467 if not conn:
2468 conn = await self.connection_pool.get_connection()
2469 # assign to self.connection so reset() releases the connection
2470 # back to the pool after we're done
2471 self.connection = conn
2472 conn = cast(Connection, conn)
2474 # Start timing for observability
2475 start_time = time.monotonic()
2476 # Track actual retry attempts for error reporting
2477 actual_retry_attempts = 0
2479 def failure_callback(error, failure_count):
2480 if is_debug_log_enabled():
2481 add_debug_log_for_operation_failure(conn, error, (operation_name,))
2482 nonlocal actual_retry_attempts
2483 actual_retry_attempts = failure_count
2484 return self._disconnect_raise_on_watching(
2485 conn, error, failure_count, start_time, operation_name
2486 )
2488 try:
2489 response = await conn.retry.call_with_retry(
2490 lambda: execute(conn, stack, raise_on_error),
2491 failure_callback,
2492 with_failure_count=True,
2493 )
2495 await record_operation_duration(
2496 command_name=operation_name,
2497 duration_seconds=time.monotonic() - start_time,
2498 server_address=getattr(conn, "host", None),
2499 server_port=getattr(conn, "port", None),
2500 db_namespace=str(conn.db),
2501 )
2502 return response
2503 except Exception as e:
2504 await record_error_count(
2505 server_address=getattr(conn, "host", None),
2506 server_port=getattr(conn, "port", None),
2507 network_peer_address=getattr(conn, "host", None),
2508 network_peer_port=getattr(conn, "port", None),
2509 error_type=e,
2510 retry_attempts=actual_retry_attempts,
2511 is_internal=False,
2512 )
2513 raise
2514 finally:
2515 await self.reset()
2517 async def discard(self):
2518 """Flushes all previously queued commands
2519 See: https://redis.io/commands/DISCARD
2520 """
2521 await self.execute_command("DISCARD")
2523 async def watch(self, *names: KeyT):
2524 """Watches the values at keys ``names``"""
2525 if self.explicit_transaction:
2526 raise RedisError("Cannot issue a WATCH after a MULTI")
2527 return await self.execute_command("WATCH", *names)
2529 async def unwatch(self):
2530 """Unwatches all previously specified keys"""
2531 return self.watching and await self.execute_command("UNWATCH") or True