client.py 56 KB

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