client.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. import asyncio
  2. import copy
  3. import inspect
  4. import re
  5. import warnings
  6. from typing import (
  7. TYPE_CHECKING,
  8. Any,
  9. AsyncIterator,
  10. Awaitable,
  11. Callable,
  12. Dict,
  13. Iterable,
  14. List,
  15. Mapping,
  16. MutableMapping,
  17. Optional,
  18. Set,
  19. Tuple,
  20. Type,
  21. TypeVar,
  22. Union,
  23. cast,
  24. )
  25. from redis._parsers.helpers import (
  26. _RedisCallbacks,
  27. _RedisCallbacksRESP2,
  28. _RedisCallbacksRESP3,
  29. bool_ok,
  30. )
  31. from redis.asyncio.connection import (
  32. Connection,
  33. ConnectionPool,
  34. SSLConnection,
  35. UnixDomainSocketConnection,
  36. )
  37. from redis.asyncio.lock import Lock
  38. from redis.asyncio.retry import Retry
  39. from redis.client import (
  40. EMPTY_RESPONSE,
  41. NEVER_DECODE,
  42. AbstractRedis,
  43. CaseInsensitiveDict,
  44. )
  45. from redis.commands import (
  46. AsyncCoreCommands,
  47. AsyncRedisModuleCommands,
  48. AsyncSentinelCommands,
  49. list_or_args,
  50. )
  51. from redis.compat import Protocol, TypedDict
  52. from redis.credentials import CredentialProvider
  53. from redis.exceptions import (
  54. ConnectionError,
  55. ExecAbortError,
  56. PubSubError,
  57. RedisError,
  58. ResponseError,
  59. TimeoutError,
  60. WatchError,
  61. )
  62. from redis.typing import ChannelT, EncodableT, KeyT
  63. from redis.utils import (
  64. HIREDIS_AVAILABLE,
  65. _set_info_logger,
  66. deprecated_function,
  67. get_lib_version,
  68. safe_str,
  69. str_if_bytes,
  70. )
  71. PubSubHandler = Callable[[Dict[str, str]], Awaitable[None]]
  72. _KeyT = TypeVar("_KeyT", bound=KeyT)
  73. _ArgT = TypeVar("_ArgT", KeyT, EncodableT)
  74. _RedisT = TypeVar("_RedisT", bound="Redis")
  75. _NormalizeKeysT = TypeVar("_NormalizeKeysT", bound=Mapping[ChannelT, object])
  76. if TYPE_CHECKING:
  77. from redis.commands.core import Script
  78. class ResponseCallbackProtocol(Protocol):
  79. def __call__(self, response: Any, **kwargs):
  80. ...
  81. class AsyncResponseCallbackProtocol(Protocol):
  82. async def __call__(self, response: Any, **kwargs):
  83. ...
  84. ResponseCallbackT = Union[ResponseCallbackProtocol, AsyncResponseCallbackProtocol]
  85. class Redis(
  86. AbstractRedis, AsyncRedisModuleCommands, AsyncCoreCommands, AsyncSentinelCommands
  87. ):
  88. """
  89. Implementation of the Redis protocol.
  90. This abstract class provides a Python interface to all Redis commands
  91. and an implementation of the Redis protocol.
  92. Pipelines derive from this, implementing how
  93. the commands are sent and received to the Redis server. Based on
  94. configuration, an instance will either use a ConnectionPool, or
  95. Connection object to talk to redis.
  96. """
  97. response_callbacks: MutableMapping[Union[str, bytes], ResponseCallbackT]
  98. @classmethod
  99. def from_url(
  100. cls,
  101. url: str,
  102. single_connection_client: bool = False,
  103. auto_close_connection_pool: Optional[bool] = None,
  104. **kwargs,
  105. ):
  106. """
  107. Return a Redis client object configured from the given URL
  108. For example::
  109. redis://[[username]:[password]]@localhost:6379/0
  110. rediss://[[username]:[password]]@localhost:6379/0
  111. unix://[username@]/path/to/socket.sock?db=0[&password=password]
  112. Three URL schemes are supported:
  113. - `redis://` creates a TCP socket connection. See more at:
  114. <https://www.iana.org/assignments/uri-schemes/prov/redis>
  115. - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
  116. <https://www.iana.org/assignments/uri-schemes/prov/rediss>
  117. - ``unix://``: creates a Unix Domain Socket connection.
  118. The username, password, hostname, path and all querystring values
  119. are passed through urllib.parse.unquote in order to replace any
  120. percent-encoded values with their corresponding characters.
  121. There are several ways to specify a database number. The first value
  122. found will be used:
  123. 1. A ``db`` querystring option, e.g. redis://localhost?db=0
  124. 2. If using the redis:// or rediss:// schemes, the path argument
  125. of the url, e.g. redis://localhost/0
  126. 3. A ``db`` keyword argument to this function.
  127. If none of these options are specified, the default db=0 is used.
  128. All querystring options are cast to their appropriate Python types.
  129. Boolean arguments can be specified with string values "True"/"False"
  130. or "Yes"/"No". Values that cannot be properly cast cause a
  131. ``ValueError`` to be raised. Once parsed, the querystring arguments
  132. and keyword arguments are passed to the ``ConnectionPool``'s
  133. class initializer. In the case of conflicting arguments, querystring
  134. arguments always win.
  135. """
  136. connection_pool = ConnectionPool.from_url(url, **kwargs)
  137. client = cls(
  138. connection_pool=connection_pool,
  139. single_connection_client=single_connection_client,
  140. )
  141. if auto_close_connection_pool is not None:
  142. warnings.warn(
  143. DeprecationWarning(
  144. '"auto_close_connection_pool" is deprecated '
  145. "since version 5.0.0. "
  146. "Please create a ConnectionPool explicitly and "
  147. "provide to the Redis() constructor instead."
  148. )
  149. )
  150. else:
  151. auto_close_connection_pool = True
  152. client.auto_close_connection_pool = auto_close_connection_pool
  153. return client
  154. @classmethod
  155. def from_pool(
  156. cls: Type["Redis"],
  157. connection_pool: ConnectionPool,
  158. ) -> "Redis":
  159. """
  160. Return a Redis client from the given connection pool.
  161. The Redis client will take ownership of the connection pool and
  162. close it when the Redis client is closed.
  163. """
  164. client = cls(
  165. connection_pool=connection_pool,
  166. )
  167. client.auto_close_connection_pool = True
  168. return client
  169. def __init__(
  170. self,
  171. *,
  172. host: str = "localhost",
  173. port: int = 6379,
  174. db: Union[str, int] = 0,
  175. password: Optional[str] = None,
  176. socket_timeout: Optional[float] = None,
  177. socket_connect_timeout: Optional[float] = None,
  178. socket_keepalive: Optional[bool] = None,
  179. socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
  180. connection_pool: Optional[ConnectionPool] = None,
  181. unix_socket_path: Optional[str] = None,
  182. encoding: str = "utf-8",
  183. encoding_errors: str = "strict",
  184. decode_responses: bool = False,
  185. retry_on_timeout: bool = False,
  186. retry_on_error: Optional[list] = None,
  187. ssl: bool = False,
  188. ssl_keyfile: Optional[str] = None,
  189. ssl_certfile: Optional[str] = None,
  190. ssl_cert_reqs: str = "required",
  191. ssl_ca_certs: Optional[str] = None,
  192. ssl_ca_data: Optional[str] = None,
  193. ssl_check_hostname: bool = False,
  194. max_connections: Optional[int] = None,
  195. single_connection_client: bool = False,
  196. health_check_interval: int = 0,
  197. client_name: Optional[str] = None,
  198. lib_name: Optional[str] = "redis-py",
  199. lib_version: Optional[str] = get_lib_version(),
  200. username: Optional[str] = None,
  201. retry: Optional[Retry] = None,
  202. auto_close_connection_pool: Optional[bool] = None,
  203. redis_connect_func=None,
  204. credential_provider: Optional[CredentialProvider] = None,
  205. protocol: Optional[int] = 2,
  206. ):
  207. """
  208. Initialize a new Redis client.
  209. To specify a retry policy for specific errors, first set
  210. `retry_on_error` to a list of the error/s to retry on, then set
  211. `retry` to a valid `Retry` object.
  212. To retry on TimeoutError, `retry_on_timeout` can also be set to `True`.
  213. """
  214. kwargs: Dict[str, Any]
  215. # auto_close_connection_pool only has an effect if connection_pool is
  216. # None. It is assumed that if connection_pool is not None, the user
  217. # wants to manage the connection pool themselves.
  218. if auto_close_connection_pool is not None:
  219. warnings.warn(
  220. DeprecationWarning(
  221. '"auto_close_connection_pool" is deprecated '
  222. "since version 5.0.0. "
  223. "Please create a ConnectionPool explicitly and "
  224. "provide to the Redis() constructor instead."
  225. )
  226. )
  227. else:
  228. auto_close_connection_pool = True
  229. if not connection_pool:
  230. # Create internal connection pool, expected to be closed by Redis instance
  231. if not retry_on_error:
  232. retry_on_error = []
  233. if retry_on_timeout is True:
  234. retry_on_error.append(TimeoutError)
  235. kwargs = {
  236. "db": db,
  237. "username": username,
  238. "password": password,
  239. "credential_provider": credential_provider,
  240. "socket_timeout": socket_timeout,
  241. "encoding": encoding,
  242. "encoding_errors": encoding_errors,
  243. "decode_responses": decode_responses,
  244. "retry_on_timeout": retry_on_timeout,
  245. "retry_on_error": retry_on_error,
  246. "retry": copy.deepcopy(retry),
  247. "max_connections": max_connections,
  248. "health_check_interval": health_check_interval,
  249. "client_name": client_name,
  250. "lib_name": lib_name,
  251. "lib_version": lib_version,
  252. "redis_connect_func": redis_connect_func,
  253. "protocol": protocol,
  254. }
  255. # based on input, setup appropriate connection args
  256. if unix_socket_path is not None:
  257. kwargs.update(
  258. {
  259. "path": unix_socket_path,
  260. "connection_class": UnixDomainSocketConnection,
  261. }
  262. )
  263. else:
  264. # TCP specific options
  265. kwargs.update(
  266. {
  267. "host": host,
  268. "port": port,
  269. "socket_connect_timeout": socket_connect_timeout,
  270. "socket_keepalive": socket_keepalive,
  271. "socket_keepalive_options": socket_keepalive_options,
  272. }
  273. )
  274. if ssl:
  275. kwargs.update(
  276. {
  277. "connection_class": SSLConnection,
  278. "ssl_keyfile": ssl_keyfile,
  279. "ssl_certfile": ssl_certfile,
  280. "ssl_cert_reqs": ssl_cert_reqs,
  281. "ssl_ca_certs": ssl_ca_certs,
  282. "ssl_ca_data": ssl_ca_data,
  283. "ssl_check_hostname": ssl_check_hostname,
  284. }
  285. )
  286. # This arg only used if no pool is passed in
  287. self.auto_close_connection_pool = auto_close_connection_pool
  288. connection_pool = ConnectionPool(**kwargs)
  289. else:
  290. # If a pool is passed in, do not close it
  291. self.auto_close_connection_pool = False
  292. self.connection_pool = connection_pool
  293. self.single_connection_client = single_connection_client
  294. self.connection: Optional[Connection] = None
  295. self.response_callbacks = CaseInsensitiveDict(_RedisCallbacks)
  296. if self.connection_pool.connection_kwargs.get("protocol") in ["3", 3]:
  297. self.response_callbacks.update(_RedisCallbacksRESP3)
  298. else:
  299. self.response_callbacks.update(_RedisCallbacksRESP2)
  300. # If using a single connection client, we need to lock creation-of and use-of
  301. # the client in order to avoid race conditions such as using asyncio.gather
  302. # on a set of redis commands
  303. self._single_conn_lock = asyncio.Lock()
  304. def __repr__(self):
  305. return f"{self.__class__.__name__}<{self.connection_pool!r}>"
  306. def __await__(self):
  307. return self.initialize().__await__()
  308. async def initialize(self: _RedisT) -> _RedisT:
  309. if self.single_connection_client:
  310. async with self._single_conn_lock:
  311. if self.connection is None:
  312. self.connection = await self.connection_pool.get_connection("_")
  313. return self
  314. def set_response_callback(self, command: str, callback: ResponseCallbackT):
  315. """Set a custom Response Callback"""
  316. self.response_callbacks[command] = callback
  317. def get_encoder(self):
  318. """Get the connection pool's encoder"""
  319. return self.connection_pool.get_encoder()
  320. def get_connection_kwargs(self):
  321. """Get the connection's key-word arguments"""
  322. return self.connection_pool.connection_kwargs
  323. def get_retry(self) -> Optional["Retry"]:
  324. return self.get_connection_kwargs().get("retry")
  325. def set_retry(self, retry: "Retry") -> None:
  326. self.get_connection_kwargs().update({"retry": retry})
  327. self.connection_pool.set_retry(retry)
  328. def load_external_module(self, funcname, func):
  329. """
  330. This function can be used to add externally defined redis modules,
  331. and their namespaces to the redis client.
  332. funcname - A string containing the name of the function to create
  333. func - The function, being added to this class.
  334. ex: Assume that one has a custom redis module named foomod that
  335. creates command named 'foo.dothing' and 'foo.anotherthing' in redis.
  336. To load function functions into this namespace:
  337. from redis import Redis
  338. from foomodule import F
  339. r = Redis()
  340. r.load_external_module("foo", F)
  341. r.foo().dothing('your', 'arguments')
  342. For a concrete example see the reimport of the redisjson module in
  343. tests/test_connection.py::test_loading_external_modules
  344. """
  345. setattr(self, funcname, func)
  346. def pipeline(
  347. self, transaction: bool = True, shard_hint: Optional[str] = None
  348. ) -> "Pipeline":
  349. """
  350. Return a new pipeline object that can queue multiple commands for
  351. later execution. ``transaction`` indicates whether all commands
  352. should be executed atomically. Apart from making a group of operations
  353. atomic, pipelines are useful for reducing the back-and-forth overhead
  354. between the client and server.
  355. """
  356. return Pipeline(
  357. self.connection_pool, self.response_callbacks, transaction, shard_hint
  358. )
  359. async def transaction(
  360. self,
  361. func: Callable[["Pipeline"], Union[Any, Awaitable[Any]]],
  362. *watches: KeyT,
  363. shard_hint: Optional[str] = None,
  364. value_from_callable: bool = False,
  365. watch_delay: Optional[float] = None,
  366. ):
  367. """
  368. Convenience method for executing the callable `func` as a transaction
  369. while watching all keys specified in `watches`. The 'func' callable
  370. should expect a single argument which is a Pipeline object.
  371. """
  372. pipe: Pipeline
  373. async with self.pipeline(True, shard_hint) as pipe:
  374. while True:
  375. try:
  376. if watches:
  377. await pipe.watch(*watches)
  378. func_value = func(pipe)
  379. if inspect.isawaitable(func_value):
  380. func_value = await func_value
  381. exec_value = await pipe.execute()
  382. return func_value if value_from_callable else exec_value
  383. except WatchError:
  384. if watch_delay is not None and watch_delay > 0:
  385. await asyncio.sleep(watch_delay)
  386. continue
  387. def lock(
  388. self,
  389. name: KeyT,
  390. timeout: Optional[float] = None,
  391. sleep: float = 0.1,
  392. blocking: bool = True,
  393. blocking_timeout: Optional[float] = None,
  394. lock_class: Optional[Type[Lock]] = None,
  395. thread_local: bool = True,
  396. ) -> Lock:
  397. """
  398. Return a new Lock object using key ``name`` that mimics
  399. the behavior of threading.Lock.
  400. If specified, ``timeout`` indicates a maximum life for the lock.
  401. By default, it will remain locked until release() is called.
  402. ``sleep`` indicates the amount of time to sleep per loop iteration
  403. when the lock is in blocking mode and another client is currently
  404. holding the lock.
  405. ``blocking`` indicates whether calling ``acquire`` should block until
  406. the lock has been acquired or to fail immediately, causing ``acquire``
  407. to return False and the lock not being acquired. Defaults to True.
  408. Note this value can be overridden by passing a ``blocking``
  409. argument to ``acquire``.
  410. ``blocking_timeout`` indicates the maximum amount of time in seconds to
  411. spend trying to acquire the lock. A value of ``None`` indicates
  412. continue trying forever. ``blocking_timeout`` can be specified as a
  413. float or integer, both representing the number of seconds to wait.
  414. ``lock_class`` forces the specified lock implementation. Note that as
  415. of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
  416. a Lua-based lock). So, it's unlikely you'll need this parameter, unless
  417. you have created your own custom lock class.
  418. ``thread_local`` indicates whether the lock token is placed in
  419. thread-local storage. By default, the token is placed in thread local
  420. storage so that a thread only sees its token, not a token set by
  421. another thread. Consider the following timeline:
  422. time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
  423. thread-1 sets the token to "abc"
  424. time: 1, thread-2 blocks trying to acquire `my-lock` using the
  425. Lock instance.
  426. time: 5, thread-1 has not yet completed. redis expires the lock
  427. key.
  428. time: 5, thread-2 acquired `my-lock` now that it's available.
  429. thread-2 sets the token to "xyz"
  430. time: 6, thread-1 finishes its work and calls release(). if the
  431. token is *not* stored in thread local storage, then
  432. thread-1 would see the token value as "xyz" and would be
  433. able to successfully release the thread-2's lock.
  434. In some use cases it's necessary to disable thread local storage. For
  435. example, if you have code where one thread acquires a lock and passes
  436. that lock instance to a worker thread to release later. If thread
  437. local storage isn't disabled in this case, the worker thread won't see
  438. the token set by the thread that acquired the lock. Our assumption
  439. is that these cases aren't common and as such default to using
  440. thread local storage."""
  441. if lock_class is None:
  442. lock_class = Lock
  443. return lock_class(
  444. self,
  445. name,
  446. timeout=timeout,
  447. sleep=sleep,
  448. blocking=blocking,
  449. blocking_timeout=blocking_timeout,
  450. thread_local=thread_local,
  451. )
  452. def pubsub(self, **kwargs) -> "PubSub":
  453. """
  454. Return a Publish/Subscribe object. With this object, you can
  455. subscribe to channels and listen for messages that get published to
  456. them.
  457. """
  458. return PubSub(self.connection_pool, **kwargs)
  459. def monitor(self) -> "Monitor":
  460. return Monitor(self.connection_pool)
  461. def client(self) -> "Redis":
  462. return self.__class__(
  463. connection_pool=self.connection_pool, single_connection_client=True
  464. )
  465. async def __aenter__(self: _RedisT) -> _RedisT:
  466. return await self.initialize()
  467. async def __aexit__(self, exc_type, exc_value, traceback):
  468. await self.aclose()
  469. _DEL_MESSAGE = "Unclosed Redis client"
  470. # passing _warnings and _grl as argument default since they may be gone
  471. # by the time __del__ is called at shutdown
  472. def __del__(
  473. self,
  474. _warn: Any = warnings.warn,
  475. _grl: Any = asyncio.get_running_loop,
  476. ) -> None:
  477. if hasattr(self, "connection") and (self.connection is not None):
  478. _warn(f"Unclosed client session {self!r}", ResourceWarning, source=self)
  479. try:
  480. context = {"client": self, "message": self._DEL_MESSAGE}
  481. _grl().call_exception_handler(context)
  482. except RuntimeError:
  483. pass
  484. async def aclose(self, close_connection_pool: Optional[bool] = None) -> None:
  485. """
  486. Closes Redis client connection
  487. :param close_connection_pool: decides whether to close the connection pool used
  488. by this Redis client, overriding Redis.auto_close_connection_pool. By default,
  489. let Redis.auto_close_connection_pool decide whether to close the connection
  490. pool.
  491. """
  492. conn = self.connection
  493. if conn:
  494. self.connection = None
  495. await self.connection_pool.release(conn)
  496. if close_connection_pool or (
  497. close_connection_pool is None and self.auto_close_connection_pool
  498. ):
  499. await self.connection_pool.disconnect()
  500. @deprecated_function(version="5.0.0", reason="Use aclose() instead", name="close")
  501. async def close(self, close_connection_pool: Optional[bool] = None) -> None:
  502. """
  503. Alias for aclose(), for backwards compatibility
  504. """
  505. await self.aclose(close_connection_pool)
  506. async def _send_command_parse_response(self, conn, command_name, *args, **options):
  507. """
  508. Send a command and parse the response
  509. """
  510. await conn.send_command(*args)
  511. return await self.parse_response(conn, command_name, **options)
  512. async def _disconnect_raise(self, conn: Connection, error: Exception):
  513. """
  514. Close the connection and raise an exception
  515. if retry_on_error is not set or the error
  516. is not one of the specified error types
  517. """
  518. await conn.disconnect()
  519. if (
  520. conn.retry_on_error is None
  521. or isinstance(error, tuple(conn.retry_on_error)) is False
  522. ):
  523. raise error
  524. # COMMAND EXECUTION AND PROTOCOL PARSING
  525. async def execute_command(self, *args, **options):
  526. """Execute a command and return a parsed response"""
  527. await self.initialize()
  528. pool = self.connection_pool
  529. command_name = args[0]
  530. conn = self.connection or await pool.get_connection(command_name, **options)
  531. if self.single_connection_client:
  532. await self._single_conn_lock.acquire()
  533. try:
  534. return await conn.retry.call_with_retry(
  535. lambda: self._send_command_parse_response(
  536. conn, command_name, *args, **options
  537. ),
  538. lambda error: self._disconnect_raise(conn, error),
  539. )
  540. finally:
  541. if self.single_connection_client:
  542. self._single_conn_lock.release()
  543. if not self.connection:
  544. await pool.release(conn)
  545. async def parse_response(
  546. self, connection: Connection, command_name: Union[str, bytes], **options
  547. ):
  548. """Parses a response from the Redis server"""
  549. try:
  550. if NEVER_DECODE in options:
  551. response = await connection.read_response(disable_decoding=True)
  552. options.pop(NEVER_DECODE)
  553. else:
  554. response = await connection.read_response()
  555. except ResponseError:
  556. if EMPTY_RESPONSE in options:
  557. return options[EMPTY_RESPONSE]
  558. raise
  559. if EMPTY_RESPONSE in options:
  560. options.pop(EMPTY_RESPONSE)
  561. if command_name in self.response_callbacks:
  562. # Mypy bug: https://github.com/python/mypy/issues/10977
  563. command_name = cast(str, command_name)
  564. retval = self.response_callbacks[command_name](response, **options)
  565. return await retval if inspect.isawaitable(retval) else retval
  566. return response
  567. StrictRedis = Redis
  568. class MonitorCommandInfo(TypedDict):
  569. time: float
  570. db: int
  571. client_address: str
  572. client_port: str
  573. client_type: str
  574. command: str
  575. class Monitor:
  576. """
  577. Monitor is useful for handling the MONITOR command to the redis server.
  578. next_command() method returns one command from monitor
  579. listen() method yields commands from monitor.
  580. """
  581. monitor_re = re.compile(r"\[(\d+) (.*?)\] (.*)")
  582. command_re = re.compile(r'"(.*?)(?<!\\)"')
  583. def __init__(self, connection_pool: ConnectionPool):
  584. self.connection_pool = connection_pool
  585. self.connection: Optional[Connection] = None
  586. async def connect(self):
  587. if self.connection is None:
  588. self.connection = await self.connection_pool.get_connection("MONITOR")
  589. async def __aenter__(self):
  590. await self.connect()
  591. await self.connection.send_command("MONITOR")
  592. # check that monitor returns 'OK', but don't return it to user
  593. response = await self.connection.read_response()
  594. if not bool_ok(response):
  595. raise RedisError(f"MONITOR failed: {response}")
  596. return self
  597. async def __aexit__(self, *args):
  598. await self.connection.disconnect()
  599. await self.connection_pool.release(self.connection)
  600. async def next_command(self) -> MonitorCommandInfo:
  601. """Parse the response from a monitor command"""
  602. await self.connect()
  603. response = await self.connection.read_response()
  604. if isinstance(response, bytes):
  605. response = self.connection.encoder.decode(response, force=True)
  606. command_time, command_data = response.split(" ", 1)
  607. m = self.monitor_re.match(command_data)
  608. db_id, client_info, command = m.groups()
  609. command = " ".join(self.command_re.findall(command))
  610. # Redis escapes double quotes because each piece of the command
  611. # string is surrounded by double quotes. We don't have that
  612. # requirement so remove the escaping and leave the quote.
  613. command = command.replace('\\"', '"')
  614. if client_info == "lua":
  615. client_address = "lua"
  616. client_port = ""
  617. client_type = "lua"
  618. elif client_info.startswith("unix"):
  619. client_address = "unix"
  620. client_port = client_info[5:]
  621. client_type = "unix"
  622. else:
  623. # use rsplit as ipv6 addresses contain colons
  624. client_address, client_port = client_info.rsplit(":", 1)
  625. client_type = "tcp"
  626. return {
  627. "time": float(command_time),
  628. "db": int(db_id),
  629. "client_address": client_address,
  630. "client_port": client_port,
  631. "client_type": client_type,
  632. "command": command,
  633. }
  634. async def listen(self) -> AsyncIterator[MonitorCommandInfo]:
  635. """Listen for commands coming to the server."""
  636. while True:
  637. yield await self.next_command()
  638. class PubSub:
  639. """
  640. PubSub provides publish, subscribe and listen support to Redis channels.
  641. After subscribing to one or more channels, the listen() method will block
  642. until a message arrives on one of the subscribed channels. That message
  643. will be returned and it's safe to start listening again.
  644. """
  645. PUBLISH_MESSAGE_TYPES = ("message", "pmessage")
  646. UNSUBSCRIBE_MESSAGE_TYPES = ("unsubscribe", "punsubscribe")
  647. HEALTH_CHECK_MESSAGE = "redis-py-health-check"
  648. def __init__(
  649. self,
  650. connection_pool: ConnectionPool,
  651. shard_hint: Optional[str] = None,
  652. ignore_subscribe_messages: bool = False,
  653. encoder=None,
  654. push_handler_func: Optional[Callable] = None,
  655. ):
  656. self.connection_pool = connection_pool
  657. self.shard_hint = shard_hint
  658. self.ignore_subscribe_messages = ignore_subscribe_messages
  659. self.connection = None
  660. # we need to know the encoding options for this connection in order
  661. # to lookup channel and pattern names for callback handlers.
  662. self.encoder = encoder
  663. self.push_handler_func = push_handler_func
  664. if self.encoder is None:
  665. self.encoder = self.connection_pool.get_encoder()
  666. if self.encoder.decode_responses:
  667. self.health_check_response = [
  668. ["pong", self.HEALTH_CHECK_MESSAGE],
  669. self.HEALTH_CHECK_MESSAGE,
  670. ]
  671. else:
  672. self.health_check_response = [
  673. [b"pong", self.encoder.encode(self.HEALTH_CHECK_MESSAGE)],
  674. self.encoder.encode(self.HEALTH_CHECK_MESSAGE),
  675. ]
  676. if self.push_handler_func is None:
  677. _set_info_logger()
  678. self.channels = {}
  679. self.pending_unsubscribe_channels = set()
  680. self.patterns = {}
  681. self.pending_unsubscribe_patterns = set()
  682. self._lock = asyncio.Lock()
  683. async def __aenter__(self):
  684. return self
  685. async def __aexit__(self, exc_type, exc_value, traceback):
  686. await self.aclose()
  687. def __del__(self):
  688. if self.connection:
  689. self.connection._deregister_connect_callback(self.on_connect)
  690. async def aclose(self):
  691. # In case a connection property does not yet exist
  692. # (due to a crash earlier in the Redis() constructor), return
  693. # immediately as there is nothing to clean-up.
  694. if not hasattr(self, "connection"):
  695. return
  696. async with self._lock:
  697. if self.connection:
  698. await self.connection.disconnect()
  699. self.connection._deregister_connect_callback(self.on_connect)
  700. await self.connection_pool.release(self.connection)
  701. self.connection = None
  702. self.channels = {}
  703. self.pending_unsubscribe_channels = set()
  704. self.patterns = {}
  705. self.pending_unsubscribe_patterns = set()
  706. @deprecated_function(version="5.0.0", reason="Use aclose() instead", name="close")
  707. async def close(self) -> None:
  708. """Alias for aclose(), for backwards compatibility"""
  709. await self.aclose()
  710. @deprecated_function(version="5.0.0", reason="Use aclose() instead", name="reset")
  711. async def reset(self) -> None:
  712. """Alias for aclose(), for backwards compatibility"""
  713. await self.aclose()
  714. async def on_connect(self, connection: Connection):
  715. """Re-subscribe to any channels and patterns previously subscribed to"""
  716. # NOTE: for python3, we can't pass bytestrings as keyword arguments
  717. # so we need to decode channel/pattern names back to unicode strings
  718. # before passing them to [p]subscribe.
  719. self.pending_unsubscribe_channels.clear()
  720. self.pending_unsubscribe_patterns.clear()
  721. if self.channels:
  722. channels = {}
  723. for k, v in self.channels.items():
  724. channels[self.encoder.decode(k, force=True)] = v
  725. await self.subscribe(**channels)
  726. if self.patterns:
  727. patterns = {}
  728. for k, v in self.patterns.items():
  729. patterns[self.encoder.decode(k, force=True)] = v
  730. await self.psubscribe(**patterns)
  731. @property
  732. def subscribed(self):
  733. """Indicates if there are subscriptions to any channels or patterns"""
  734. return bool(self.channels or self.patterns)
  735. async def execute_command(self, *args: EncodableT):
  736. """Execute a publish/subscribe command"""
  737. # NOTE: don't parse the response in this function -- it could pull a
  738. # legitimate message off the stack if the connection is already
  739. # subscribed to one or more channels
  740. await self.connect()
  741. connection = self.connection
  742. kwargs = {"check_health": not self.subscribed}
  743. await self._execute(connection, connection.send_command, *args, **kwargs)
  744. async def connect(self):
  745. """
  746. Ensure that the PubSub is connected
  747. """
  748. if self.connection is None:
  749. self.connection = await self.connection_pool.get_connection(
  750. "pubsub", self.shard_hint
  751. )
  752. # register a callback that re-subscribes to any channels we
  753. # were listening to when we were disconnected
  754. self.connection._register_connect_callback(self.on_connect)
  755. else:
  756. await self.connection.connect()
  757. if self.push_handler_func is not None and not HIREDIS_AVAILABLE:
  758. self.connection._parser.set_push_handler(self.push_handler_func)
  759. async def _disconnect_raise_connect(self, conn, error):
  760. """
  761. Close the connection and raise an exception
  762. if retry_on_timeout is not set or the error
  763. is not a TimeoutError. Otherwise, try to reconnect
  764. """
  765. await conn.disconnect()
  766. if not (conn.retry_on_timeout and isinstance(error, TimeoutError)):
  767. raise error
  768. await conn.connect()
  769. async def _execute(self, conn, command, *args, **kwargs):
  770. """
  771. Connect manually upon disconnection. If the Redis server is down,
  772. this will fail and raise a ConnectionError as desired.
  773. After reconnection, the ``on_connect`` callback should have been
  774. called by the # connection to resubscribe us to any channels and
  775. patterns we were previously listening to
  776. """
  777. return await conn.retry.call_with_retry(
  778. lambda: command(*args, **kwargs),
  779. lambda error: self._disconnect_raise_connect(conn, error),
  780. )
  781. async def parse_response(self, block: bool = True, timeout: float = 0):
  782. """Parse the response from a publish/subscribe command"""
  783. conn = self.connection
  784. if conn is None:
  785. raise RuntimeError(
  786. "pubsub connection not set: "
  787. "did you forget to call subscribe() or psubscribe()?"
  788. )
  789. await self.check_health()
  790. if not conn.is_connected:
  791. await conn.connect()
  792. read_timeout = None if block else timeout
  793. response = await self._execute(
  794. conn,
  795. conn.read_response,
  796. timeout=read_timeout,
  797. disconnect_on_error=False,
  798. push_request=True,
  799. )
  800. if conn.health_check_interval and response in self.health_check_response:
  801. # ignore the health check message as user might not expect it
  802. return None
  803. return response
  804. async def check_health(self):
  805. conn = self.connection
  806. if conn is None:
  807. raise RuntimeError(
  808. "pubsub connection not set: "
  809. "did you forget to call subscribe() or psubscribe()?"
  810. )
  811. if (
  812. conn.health_check_interval
  813. and asyncio.get_running_loop().time() > conn.next_health_check
  814. ):
  815. await conn.send_command(
  816. "PING", self.HEALTH_CHECK_MESSAGE, check_health=False
  817. )
  818. def _normalize_keys(self, data: _NormalizeKeysT) -> _NormalizeKeysT:
  819. """
  820. normalize channel/pattern names to be either bytes or strings
  821. based on whether responses are automatically decoded. this saves us
  822. from coercing the value for each message coming in.
  823. """
  824. encode = self.encoder.encode
  825. decode = self.encoder.decode
  826. return {decode(encode(k)): v for k, v in data.items()} # type: ignore[return-value] # noqa: E501
  827. async def psubscribe(self, *args: ChannelT, **kwargs: PubSubHandler):
  828. """
  829. Subscribe to channel patterns. Patterns supplied as keyword arguments
  830. expect a pattern name as the key and a callable as the value. A
  831. pattern's callable will be invoked automatically when a message is
  832. received on that pattern rather than producing a message via
  833. ``listen()``.
  834. """
  835. parsed_args = list_or_args((args[0],), args[1:]) if args else args
  836. new_patterns: Dict[ChannelT, PubSubHandler] = dict.fromkeys(parsed_args)
  837. # Mypy bug: https://github.com/python/mypy/issues/10970
  838. new_patterns.update(kwargs) # type: ignore[arg-type]
  839. ret_val = await self.execute_command("PSUBSCRIBE", *new_patterns.keys())
  840. # update the patterns dict AFTER we send the command. we don't want to
  841. # subscribe twice to these patterns, once for the command and again
  842. # for the reconnection.
  843. new_patterns = self._normalize_keys(new_patterns)
  844. self.patterns.update(new_patterns)
  845. self.pending_unsubscribe_patterns.difference_update(new_patterns)
  846. return ret_val
  847. def punsubscribe(self, *args: ChannelT) -> Awaitable:
  848. """
  849. Unsubscribe from the supplied patterns. If empty, unsubscribe from
  850. all patterns.
  851. """
  852. patterns: Iterable[ChannelT]
  853. if args:
  854. parsed_args = list_or_args((args[0],), args[1:])
  855. patterns = self._normalize_keys(dict.fromkeys(parsed_args)).keys()
  856. else:
  857. parsed_args = []
  858. patterns = self.patterns
  859. self.pending_unsubscribe_patterns.update(patterns)
  860. return self.execute_command("PUNSUBSCRIBE", *parsed_args)
  861. async def subscribe(self, *args: ChannelT, **kwargs: Callable):
  862. """
  863. Subscribe to channels. Channels supplied as keyword arguments expect
  864. a channel name as the key and a callable as the value. A channel's
  865. callable will be invoked automatically when a message is received on
  866. that channel rather than producing a message via ``listen()`` or
  867. ``get_message()``.
  868. """
  869. parsed_args = list_or_args((args[0],), args[1:]) if args else ()
  870. new_channels = dict.fromkeys(parsed_args)
  871. # Mypy bug: https://github.com/python/mypy/issues/10970
  872. new_channels.update(kwargs) # type: ignore[arg-type]
  873. ret_val = await self.execute_command("SUBSCRIBE", *new_channels.keys())
  874. # update the channels dict AFTER we send the command. we don't want to
  875. # subscribe twice to these channels, once for the command and again
  876. # for the reconnection.
  877. new_channels = self._normalize_keys(new_channels)
  878. self.channels.update(new_channels)
  879. self.pending_unsubscribe_channels.difference_update(new_channels)
  880. return ret_val
  881. def unsubscribe(self, *args) -> Awaitable:
  882. """
  883. Unsubscribe from the supplied channels. If empty, unsubscribe from
  884. all channels
  885. """
  886. if args:
  887. parsed_args = list_or_args(args[0], args[1:])
  888. channels = self._normalize_keys(dict.fromkeys(parsed_args))
  889. else:
  890. parsed_args = []
  891. channels = self.channels
  892. self.pending_unsubscribe_channels.update(channels)
  893. return self.execute_command("UNSUBSCRIBE", *parsed_args)
  894. async def listen(self) -> AsyncIterator:
  895. """Listen for messages on channels this client has been subscribed to"""
  896. while self.subscribed:
  897. response = await self.handle_message(await self.parse_response(block=True))
  898. if response is not None:
  899. yield response
  900. async def get_message(
  901. self, ignore_subscribe_messages: bool = False, timeout: Optional[float] = 0.0
  902. ):
  903. """
  904. Get the next message if one is available, otherwise None.
  905. If timeout is specified, the system will wait for `timeout` seconds
  906. before returning. Timeout should be specified as a floating point
  907. number or None to wait indefinitely.
  908. """
  909. response = await self.parse_response(block=(timeout is None), timeout=timeout)
  910. if response:
  911. return await self.handle_message(response, ignore_subscribe_messages)
  912. return None
  913. def ping(self, message=None) -> Awaitable:
  914. """
  915. Ping the Redis server
  916. """
  917. args = ["PING", message] if message is not None else ["PING"]
  918. return self.execute_command(*args)
  919. async def handle_message(self, response, ignore_subscribe_messages=False):
  920. """
  921. Parses a pub/sub message. If the channel or pattern was subscribed to
  922. with a message handler, the handler is invoked instead of a parsed
  923. message being returned.
  924. """
  925. if response is None:
  926. return None
  927. if isinstance(response, bytes):
  928. response = [b"pong", response] if response != b"PONG" else [b"pong", b""]
  929. message_type = str_if_bytes(response[0])
  930. if message_type == "pmessage":
  931. message = {
  932. "type": message_type,
  933. "pattern": response[1],
  934. "channel": response[2],
  935. "data": response[3],
  936. }
  937. elif message_type == "pong":
  938. message = {
  939. "type": message_type,
  940. "pattern": None,
  941. "channel": None,
  942. "data": response[1],
  943. }
  944. else:
  945. message = {
  946. "type": message_type,
  947. "pattern": None,
  948. "channel": response[1],
  949. "data": response[2],
  950. }
  951. # if this is an unsubscribe message, remove it from memory
  952. if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
  953. if message_type == "punsubscribe":
  954. pattern = response[1]
  955. if pattern in self.pending_unsubscribe_patterns:
  956. self.pending_unsubscribe_patterns.remove(pattern)
  957. self.patterns.pop(pattern, None)
  958. else:
  959. channel = response[1]
  960. if channel in self.pending_unsubscribe_channels:
  961. self.pending_unsubscribe_channels.remove(channel)
  962. self.channels.pop(channel, None)
  963. if message_type in self.PUBLISH_MESSAGE_TYPES:
  964. # if there's a message handler, invoke it
  965. if message_type == "pmessage":
  966. handler = self.patterns.get(message["pattern"], None)
  967. else:
  968. handler = self.channels.get(message["channel"], None)
  969. if handler:
  970. if inspect.iscoroutinefunction(handler):
  971. await handler(message)
  972. else:
  973. handler(message)
  974. return None
  975. elif message_type != "pong":
  976. # this is a subscribe/unsubscribe message. ignore if we don't
  977. # want them
  978. if ignore_subscribe_messages or self.ignore_subscribe_messages:
  979. return None
  980. return message
  981. async def run(
  982. self,
  983. *,
  984. exception_handler: Optional["PSWorkerThreadExcHandlerT"] = None,
  985. poll_timeout: float = 1.0,
  986. ) -> None:
  987. """Process pub/sub messages using registered callbacks.
  988. This is the equivalent of :py:meth:`redis.PubSub.run_in_thread` in
  989. redis-py, but it is a coroutine. To launch it as a separate task, use
  990. ``asyncio.create_task``:
  991. >>> task = asyncio.create_task(pubsub.run())
  992. To shut it down, use asyncio cancellation:
  993. >>> task.cancel()
  994. >>> await task
  995. """
  996. for channel, handler in self.channels.items():
  997. if handler is None:
  998. raise PubSubError(f"Channel: '{channel}' has no handler registered")
  999. for pattern, handler in self.patterns.items():
  1000. if handler is None:
  1001. raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
  1002. await self.connect()
  1003. while True:
  1004. try:
  1005. await self.get_message(
  1006. ignore_subscribe_messages=True, timeout=poll_timeout
  1007. )
  1008. except asyncio.CancelledError:
  1009. raise
  1010. except BaseException as e:
  1011. if exception_handler is None:
  1012. raise
  1013. res = exception_handler(e, self)
  1014. if inspect.isawaitable(res):
  1015. await res
  1016. # Ensure that other tasks on the event loop get a chance to run
  1017. # if we didn't have to block for I/O anywhere.
  1018. await asyncio.sleep(0)
  1019. class PubsubWorkerExceptionHandler(Protocol):
  1020. def __call__(self, e: BaseException, pubsub: PubSub):
  1021. ...
  1022. class AsyncPubsubWorkerExceptionHandler(Protocol):
  1023. async def __call__(self, e: BaseException, pubsub: PubSub):
  1024. ...
  1025. PSWorkerThreadExcHandlerT = Union[
  1026. PubsubWorkerExceptionHandler, AsyncPubsubWorkerExceptionHandler
  1027. ]
  1028. CommandT = Tuple[Tuple[Union[str, bytes], ...], Mapping[str, Any]]
  1029. CommandStackT = List[CommandT]
  1030. class Pipeline(Redis): # lgtm [py/init-calls-subclass]
  1031. """
  1032. Pipelines provide a way to transmit multiple commands to the Redis server
  1033. in one transmission. This is convenient for batch processing, such as
  1034. saving all the values in a list to Redis.
  1035. All commands executed within a pipeline are wrapped with MULTI and EXEC
  1036. calls. This guarantees all commands executed in the pipeline will be
  1037. executed atomically.
  1038. Any command raising an exception does *not* halt the execution of
  1039. subsequent commands in the pipeline. Instead, the exception is caught
  1040. and its instance is placed into the response list returned by execute().
  1041. Code iterating over the response list should be able to deal with an
  1042. instance of an exception as a potential value. In general, these will be
  1043. ResponseError exceptions, such as those raised when issuing a command
  1044. on a key of a different datatype.
  1045. """
  1046. UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
  1047. def __init__(
  1048. self,
  1049. connection_pool: ConnectionPool,
  1050. response_callbacks: MutableMapping[Union[str, bytes], ResponseCallbackT],
  1051. transaction: bool,
  1052. shard_hint: Optional[str],
  1053. ):
  1054. self.connection_pool = connection_pool
  1055. self.connection = None
  1056. self.response_callbacks = response_callbacks
  1057. self.is_transaction = transaction
  1058. self.shard_hint = shard_hint
  1059. self.watching = False
  1060. self.command_stack: CommandStackT = []
  1061. self.scripts: Set["Script"] = set()
  1062. self.explicit_transaction = False
  1063. async def __aenter__(self: _RedisT) -> _RedisT:
  1064. return self
  1065. async def __aexit__(self, exc_type, exc_value, traceback):
  1066. await self.reset()
  1067. def __await__(self):
  1068. return self._async_self().__await__()
  1069. _DEL_MESSAGE = "Unclosed Pipeline client"
  1070. def __len__(self):
  1071. return len(self.command_stack)
  1072. def __bool__(self):
  1073. """Pipeline instances should always evaluate to True"""
  1074. return True
  1075. async def _async_self(self):
  1076. return self
  1077. async def reset(self):
  1078. self.command_stack = []
  1079. self.scripts = set()
  1080. # make sure to reset the connection state in the event that we were
  1081. # watching something
  1082. if self.watching and self.connection:
  1083. try:
  1084. # call this manually since our unwatch or
  1085. # immediate_execute_command methods can call reset()
  1086. await self.connection.send_command("UNWATCH")
  1087. await self.connection.read_response()
  1088. except ConnectionError:
  1089. # disconnect will also remove any previous WATCHes
  1090. if self.connection:
  1091. await self.connection.disconnect()
  1092. # clean up the other instance attributes
  1093. self.watching = False
  1094. self.explicit_transaction = False
  1095. # we can safely return the connection to the pool here since we're
  1096. # sure we're no longer WATCHing anything
  1097. if self.connection:
  1098. await self.connection_pool.release(self.connection)
  1099. self.connection = None
  1100. async def aclose(self) -> None:
  1101. """Alias for reset(), a standard method name for cleanup"""
  1102. await self.reset()
  1103. def multi(self):
  1104. """
  1105. Start a transactional block of the pipeline after WATCH commands
  1106. are issued. End the transactional block with `execute`.
  1107. """
  1108. if self.explicit_transaction:
  1109. raise RedisError("Cannot issue nested calls to MULTI")
  1110. if self.command_stack:
  1111. raise RedisError(
  1112. "Commands without an initial WATCH have already been issued"
  1113. )
  1114. self.explicit_transaction = True
  1115. def execute_command(
  1116. self, *args, **kwargs
  1117. ) -> Union["Pipeline", Awaitable["Pipeline"]]:
  1118. if (self.watching or args[0] == "WATCH") and not self.explicit_transaction:
  1119. return self.immediate_execute_command(*args, **kwargs)
  1120. return self.pipeline_execute_command(*args, **kwargs)
  1121. async def _disconnect_reset_raise(self, conn, error):
  1122. """
  1123. Close the connection, reset watching state and
  1124. raise an exception if we were watching,
  1125. retry_on_timeout is not set,
  1126. or the error is not a TimeoutError
  1127. """
  1128. await conn.disconnect()
  1129. # if we were already watching a variable, the watch is no longer
  1130. # valid since this connection has died. raise a WatchError, which
  1131. # indicates the user should retry this transaction.
  1132. if self.watching:
  1133. await self.aclose()
  1134. raise WatchError(
  1135. "A ConnectionError occurred on while watching one or more keys"
  1136. )
  1137. # if retry_on_timeout is not set, or the error is not
  1138. # a TimeoutError, raise it
  1139. if not (conn.retry_on_timeout and isinstance(error, TimeoutError)):
  1140. await self.aclose()
  1141. raise
  1142. async def immediate_execute_command(self, *args, **options):
  1143. """
  1144. Execute a command immediately, but don't auto-retry on a
  1145. ConnectionError if we're already WATCHing a variable. Used when
  1146. issuing WATCH or subsequent commands retrieving their values but before
  1147. MULTI is called.
  1148. """
  1149. command_name = args[0]
  1150. conn = self.connection
  1151. # if this is the first call, we need a connection
  1152. if not conn:
  1153. conn = await self.connection_pool.get_connection(
  1154. command_name, self.shard_hint
  1155. )
  1156. self.connection = conn
  1157. return await conn.retry.call_with_retry(
  1158. lambda: self._send_command_parse_response(
  1159. conn, command_name, *args, **options
  1160. ),
  1161. lambda error: self._disconnect_reset_raise(conn, error),
  1162. )
  1163. def pipeline_execute_command(self, *args, **options):
  1164. """
  1165. Stage a command to be executed when execute() is next called
  1166. Returns the current Pipeline object back so commands can be
  1167. chained together, such as:
  1168. pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
  1169. At some other point, you can then run: pipe.execute(),
  1170. which will execute all commands queued in the pipe.
  1171. """
  1172. self.command_stack.append((args, options))
  1173. return self
  1174. async def _execute_transaction( # noqa: C901
  1175. self, connection: Connection, commands: CommandStackT, raise_on_error
  1176. ):
  1177. pre: CommandT = (("MULTI",), {})
  1178. post: CommandT = (("EXEC",), {})
  1179. cmds = (pre, *commands, post)
  1180. all_cmds = connection.pack_commands(
  1181. args for args, options in cmds if EMPTY_RESPONSE not in options
  1182. )
  1183. await connection.send_packed_command(all_cmds)
  1184. errors = []
  1185. # parse off the response for MULTI
  1186. # NOTE: we need to handle ResponseErrors here and continue
  1187. # so that we read all the additional command messages from
  1188. # the socket
  1189. try:
  1190. await self.parse_response(connection, "_")
  1191. except ResponseError as err:
  1192. errors.append((0, err))
  1193. # and all the other commands
  1194. for i, command in enumerate(commands):
  1195. if EMPTY_RESPONSE in command[1]:
  1196. errors.append((i, command[1][EMPTY_RESPONSE]))
  1197. else:
  1198. try:
  1199. await self.parse_response(connection, "_")
  1200. except ResponseError as err:
  1201. self.annotate_exception(err, i + 1, command[0])
  1202. errors.append((i, err))
  1203. # parse the EXEC.
  1204. try:
  1205. response = await self.parse_response(connection, "_")
  1206. except ExecAbortError as err:
  1207. if errors:
  1208. raise errors[0][1] from err
  1209. raise
  1210. # EXEC clears any watched keys
  1211. self.watching = False
  1212. if response is None:
  1213. raise WatchError("Watched variable changed.") from None
  1214. # put any parse errors into the response
  1215. for i, e in errors:
  1216. response.insert(i, e)
  1217. if len(response) != len(commands):
  1218. if self.connection:
  1219. await self.connection.disconnect()
  1220. raise ResponseError(
  1221. "Wrong number of response items from pipeline execution"
  1222. ) from None
  1223. # find any errors in the response and raise if necessary
  1224. if raise_on_error:
  1225. self.raise_first_error(commands, response)
  1226. # We have to run response callbacks manually
  1227. data = []
  1228. for r, cmd in zip(response, commands):
  1229. if not isinstance(r, Exception):
  1230. args, options = cmd
  1231. command_name = args[0]
  1232. if command_name in self.response_callbacks:
  1233. r = self.response_callbacks[command_name](r, **options)
  1234. if inspect.isawaitable(r):
  1235. r = await r
  1236. data.append(r)
  1237. return data
  1238. async def _execute_pipeline(
  1239. self, connection: Connection, commands: CommandStackT, raise_on_error: bool
  1240. ):
  1241. # build up all commands into a single request to increase network perf
  1242. all_cmds = connection.pack_commands([args for args, _ in commands])
  1243. await connection.send_packed_command(all_cmds)
  1244. response = []
  1245. for args, options in commands:
  1246. try:
  1247. response.append(
  1248. await self.parse_response(connection, args[0], **options)
  1249. )
  1250. except ResponseError as e:
  1251. response.append(e)
  1252. if raise_on_error:
  1253. self.raise_first_error(commands, response)
  1254. return response
  1255. def raise_first_error(self, commands: CommandStackT, response: Iterable[Any]):
  1256. for i, r in enumerate(response):
  1257. if isinstance(r, ResponseError):
  1258. self.annotate_exception(r, i + 1, commands[i][0])
  1259. raise r
  1260. def annotate_exception(
  1261. self, exception: Exception, number: int, command: Iterable[object]
  1262. ) -> None:
  1263. cmd = " ".join(map(safe_str, command))
  1264. msg = f"Command # {number} ({cmd}) of pipeline caused error: {exception.args}"
  1265. exception.args = (msg,) + exception.args[1:]
  1266. async def parse_response(
  1267. self, connection: Connection, command_name: Union[str, bytes], **options
  1268. ):
  1269. result = await super().parse_response(connection, command_name, **options)
  1270. if command_name in self.UNWATCH_COMMANDS:
  1271. self.watching = False
  1272. elif command_name == "WATCH":
  1273. self.watching = True
  1274. return result
  1275. async def load_scripts(self):
  1276. # make sure all scripts that are about to be run on this pipeline exist
  1277. scripts = list(self.scripts)
  1278. immediate = self.immediate_execute_command
  1279. shas = [s.sha for s in scripts]
  1280. # we can't use the normal script_* methods because they would just
  1281. # get buffered in the pipeline.
  1282. exists = await immediate("SCRIPT EXISTS", *shas)
  1283. if not all(exists):
  1284. for s, exist in zip(scripts, exists):
  1285. if not exist:
  1286. s.sha = await immediate("SCRIPT LOAD", s.script)
  1287. async def _disconnect_raise_reset(self, conn: Connection, error: Exception):
  1288. """
  1289. Close the connection, raise an exception if we were watching,
  1290. and raise an exception if retry_on_timeout is not set,
  1291. or the error is not a TimeoutError
  1292. """
  1293. await conn.disconnect()
  1294. # if we were watching a variable, the watch is no longer valid
  1295. # since this connection has died. raise a WatchError, which
  1296. # indicates the user should retry this transaction.
  1297. if self.watching:
  1298. raise WatchError(
  1299. "A ConnectionError occurred on while watching one or more keys"
  1300. )
  1301. # if retry_on_timeout is not set, or the error is not
  1302. # a TimeoutError, raise it
  1303. if not (conn.retry_on_timeout and isinstance(error, TimeoutError)):
  1304. await self.reset()
  1305. raise
  1306. async def execute(self, raise_on_error: bool = True):
  1307. """Execute all the commands in the current pipeline"""
  1308. stack = self.command_stack
  1309. if not stack and not self.watching:
  1310. return []
  1311. if self.scripts:
  1312. await self.load_scripts()
  1313. if self.is_transaction or self.explicit_transaction:
  1314. execute = self._execute_transaction
  1315. else:
  1316. execute = self._execute_pipeline
  1317. conn = self.connection
  1318. if not conn:
  1319. conn = await self.connection_pool.get_connection("MULTI", self.shard_hint)
  1320. # assign to self.connection so reset() releases the connection
  1321. # back to the pool after we're done
  1322. self.connection = conn
  1323. conn = cast(Connection, conn)
  1324. try:
  1325. return await conn.retry.call_with_retry(
  1326. lambda: execute(conn, stack, raise_on_error),
  1327. lambda error: self._disconnect_raise_reset(conn, error),
  1328. )
  1329. finally:
  1330. await self.reset()
  1331. async def discard(self):
  1332. """Flushes all previously queued commands
  1333. See: https://redis.io/commands/DISCARD
  1334. """
  1335. await self.execute_command("DISCARD")
  1336. async def watch(self, *names: KeyT):
  1337. """Watches the values at keys ``names``"""
  1338. if self.explicit_transaction:
  1339. raise RedisError("Cannot issue a WATCH after a MULTI")
  1340. return await self.execute_command("WATCH", *names)
  1341. async def unwatch(self):
  1342. """Unwatches all previously specified keys"""
  1343. return self.watching and await self.execute_command("UNWATCH") or True