connection.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. import asyncio
  2. import copy
  3. import enum
  4. import inspect
  5. import socket
  6. import ssl
  7. import sys
  8. import weakref
  9. from abc import abstractmethod
  10. from itertools import chain
  11. from types import MappingProxyType
  12. from typing import (
  13. Any,
  14. Callable,
  15. Iterable,
  16. List,
  17. Mapping,
  18. Optional,
  19. Set,
  20. Tuple,
  21. Type,
  22. TypeVar,
  23. Union,
  24. )
  25. from urllib.parse import ParseResult, parse_qs, unquote, urlparse
  26. # the functionality is available in 3.11.x but has a major issue before
  27. # 3.11.3. See https://github.com/redis/redis-py/issues/2633
  28. if sys.version_info >= (3, 11, 3):
  29. from asyncio import timeout as async_timeout
  30. else:
  31. from async_timeout import timeout as async_timeout
  32. from redis.asyncio.retry import Retry
  33. from redis.backoff import NoBackoff
  34. from redis.compat import Protocol, TypedDict
  35. from redis.connection import DEFAULT_RESP_VERSION
  36. from redis.credentials import CredentialProvider, UsernamePasswordCredentialProvider
  37. from redis.exceptions import (
  38. AuthenticationError,
  39. AuthenticationWrongNumberOfArgsError,
  40. ConnectionError,
  41. DataError,
  42. RedisError,
  43. ResponseError,
  44. TimeoutError,
  45. )
  46. from redis.typing import EncodableT
  47. from redis.utils import HIREDIS_AVAILABLE, get_lib_version, str_if_bytes
  48. from .._parsers import (
  49. BaseParser,
  50. Encoder,
  51. _AsyncHiredisParser,
  52. _AsyncRESP2Parser,
  53. _AsyncRESP3Parser,
  54. )
  55. SYM_STAR = b"*"
  56. SYM_DOLLAR = b"$"
  57. SYM_CRLF = b"\r\n"
  58. SYM_LF = b"\n"
  59. SYM_EMPTY = b""
  60. class _Sentinel(enum.Enum):
  61. sentinel = object()
  62. SENTINEL = _Sentinel.sentinel
  63. DefaultParser: Type[Union[_AsyncRESP2Parser, _AsyncRESP3Parser, _AsyncHiredisParser]]
  64. if HIREDIS_AVAILABLE:
  65. DefaultParser = _AsyncHiredisParser
  66. else:
  67. DefaultParser = _AsyncRESP2Parser
  68. class ConnectCallbackProtocol(Protocol):
  69. def __call__(self, connection: "AbstractConnection"):
  70. ...
  71. class AsyncConnectCallbackProtocol(Protocol):
  72. async def __call__(self, connection: "AbstractConnection"):
  73. ...
  74. ConnectCallbackT = Union[ConnectCallbackProtocol, AsyncConnectCallbackProtocol]
  75. class AbstractConnection:
  76. """Manages communication to and from a Redis server"""
  77. __slots__ = (
  78. "db",
  79. "username",
  80. "client_name",
  81. "lib_name",
  82. "lib_version",
  83. "credential_provider",
  84. "password",
  85. "socket_timeout",
  86. "socket_connect_timeout",
  87. "redis_connect_func",
  88. "retry_on_timeout",
  89. "retry_on_error",
  90. "health_check_interval",
  91. "next_health_check",
  92. "last_active_at",
  93. "encoder",
  94. "ssl_context",
  95. "protocol",
  96. "_reader",
  97. "_writer",
  98. "_parser",
  99. "_connect_callbacks",
  100. "_buffer_cutoff",
  101. "_lock",
  102. "_socket_read_size",
  103. "__dict__",
  104. )
  105. def __init__(
  106. self,
  107. *,
  108. db: Union[str, int] = 0,
  109. password: Optional[str] = None,
  110. socket_timeout: Optional[float] = None,
  111. socket_connect_timeout: Optional[float] = None,
  112. retry_on_timeout: bool = False,
  113. retry_on_error: Union[list, _Sentinel] = SENTINEL,
  114. encoding: str = "utf-8",
  115. encoding_errors: str = "strict",
  116. decode_responses: bool = False,
  117. parser_class: Type[BaseParser] = DefaultParser,
  118. socket_read_size: int = 65536,
  119. health_check_interval: float = 0,
  120. client_name: Optional[str] = None,
  121. lib_name: Optional[str] = "redis-py",
  122. lib_version: Optional[str] = get_lib_version(),
  123. username: Optional[str] = None,
  124. retry: Optional[Retry] = None,
  125. redis_connect_func: Optional[ConnectCallbackT] = None,
  126. encoder_class: Type[Encoder] = Encoder,
  127. credential_provider: Optional[CredentialProvider] = None,
  128. protocol: Optional[int] = 2,
  129. ):
  130. if (username or password) and credential_provider is not None:
  131. raise DataError(
  132. "'username' and 'password' cannot be passed along with 'credential_"
  133. "provider'. Please provide only one of the following arguments: \n"
  134. "1. 'password' and (optional) 'username'\n"
  135. "2. 'credential_provider'"
  136. )
  137. self.db = db
  138. self.client_name = client_name
  139. self.lib_name = lib_name
  140. self.lib_version = lib_version
  141. self.credential_provider = credential_provider
  142. self.password = password
  143. self.username = username
  144. self.socket_timeout = socket_timeout
  145. if socket_connect_timeout is None:
  146. socket_connect_timeout = socket_timeout
  147. self.socket_connect_timeout = socket_connect_timeout
  148. self.retry_on_timeout = retry_on_timeout
  149. if retry_on_error is SENTINEL:
  150. retry_on_error = []
  151. if retry_on_timeout:
  152. retry_on_error.append(TimeoutError)
  153. retry_on_error.append(socket.timeout)
  154. retry_on_error.append(asyncio.TimeoutError)
  155. self.retry_on_error = retry_on_error
  156. if retry or retry_on_error:
  157. if not retry:
  158. self.retry = Retry(NoBackoff(), 1)
  159. else:
  160. # deep-copy the Retry object as it is mutable
  161. self.retry = copy.deepcopy(retry)
  162. # Update the retry's supported errors with the specified errors
  163. self.retry.update_supported_errors(retry_on_error)
  164. else:
  165. self.retry = Retry(NoBackoff(), 0)
  166. self.health_check_interval = health_check_interval
  167. self.next_health_check: float = -1
  168. self.encoder = encoder_class(encoding, encoding_errors, decode_responses)
  169. self.redis_connect_func = redis_connect_func
  170. self._reader: Optional[asyncio.StreamReader] = None
  171. self._writer: Optional[asyncio.StreamWriter] = None
  172. self._socket_read_size = socket_read_size
  173. self.set_parser(parser_class)
  174. self._connect_callbacks: List[weakref.WeakMethod[ConnectCallbackT]] = []
  175. self._buffer_cutoff = 6000
  176. try:
  177. p = int(protocol)
  178. except TypeError:
  179. p = DEFAULT_RESP_VERSION
  180. except ValueError:
  181. raise ConnectionError("protocol must be an integer")
  182. finally:
  183. if p < 2 or p > 3:
  184. raise ConnectionError("protocol must be either 2 or 3")
  185. self.protocol = protocol
  186. def __repr__(self):
  187. repr_args = ",".join((f"{k}={v}" for k, v in self.repr_pieces()))
  188. return f"{self.__class__.__name__}<{repr_args}>"
  189. @abstractmethod
  190. def repr_pieces(self):
  191. pass
  192. @property
  193. def is_connected(self):
  194. return self._reader is not None and self._writer is not None
  195. def _register_connect_callback(self, callback):
  196. wm = weakref.WeakMethod(callback)
  197. if wm not in self._connect_callbacks:
  198. self._connect_callbacks.append(wm)
  199. def _deregister_connect_callback(self, callback):
  200. try:
  201. self._connect_callbacks.remove(weakref.WeakMethod(callback))
  202. except ValueError:
  203. pass
  204. def set_parser(self, parser_class: Type[BaseParser]) -> None:
  205. """
  206. Creates a new instance of parser_class with socket size:
  207. _socket_read_size and assigns it to the parser for the connection
  208. :param parser_class: The required parser class
  209. """
  210. self._parser = parser_class(socket_read_size=self._socket_read_size)
  211. async def connect(self):
  212. """Connects to the Redis server if not already connected"""
  213. if self.is_connected:
  214. return
  215. try:
  216. await self.retry.call_with_retry(
  217. lambda: self._connect(), lambda error: self.disconnect()
  218. )
  219. except asyncio.CancelledError:
  220. raise # in 3.7 and earlier, this is an Exception, not BaseException
  221. except (socket.timeout, asyncio.TimeoutError):
  222. raise TimeoutError("Timeout connecting to server")
  223. except OSError as e:
  224. raise ConnectionError(self._error_message(e))
  225. except Exception as exc:
  226. raise ConnectionError(exc) from exc
  227. try:
  228. if not self.redis_connect_func:
  229. # Use the default on_connect function
  230. await self.on_connect()
  231. else:
  232. # Use the passed function redis_connect_func
  233. await self.redis_connect_func(self) if asyncio.iscoroutinefunction(
  234. self.redis_connect_func
  235. ) else self.redis_connect_func(self)
  236. except RedisError:
  237. # clean up after any error in on_connect
  238. await self.disconnect()
  239. raise
  240. # run any user callbacks. right now the only internal callback
  241. # is for pubsub channel/pattern resubscription
  242. # first, remove any dead weakrefs
  243. self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()]
  244. for ref in self._connect_callbacks:
  245. callback = ref()
  246. task = callback(self)
  247. if task and inspect.isawaitable(task):
  248. await task
  249. @abstractmethod
  250. async def _connect(self):
  251. pass
  252. @abstractmethod
  253. def _host_error(self) -> str:
  254. pass
  255. @abstractmethod
  256. def _error_message(self, exception: BaseException) -> str:
  257. pass
  258. async def on_connect(self) -> None:
  259. """Initialize the connection, authenticate and select a database"""
  260. self._parser.on_connect(self)
  261. parser = self._parser
  262. auth_args = None
  263. # if credential provider or username and/or password are set, authenticate
  264. if self.credential_provider or (self.username or self.password):
  265. cred_provider = (
  266. self.credential_provider
  267. or UsernamePasswordCredentialProvider(self.username, self.password)
  268. )
  269. auth_args = cred_provider.get_credentials()
  270. # if resp version is specified and we have auth args,
  271. # we need to send them via HELLO
  272. if auth_args and self.protocol not in [2, "2"]:
  273. if isinstance(self._parser, _AsyncRESP2Parser):
  274. self.set_parser(_AsyncRESP3Parser)
  275. # update cluster exception classes
  276. self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
  277. self._parser.on_connect(self)
  278. if len(auth_args) == 1:
  279. auth_args = ["default", auth_args[0]]
  280. await self.send_command("HELLO", self.protocol, "AUTH", *auth_args)
  281. response = await self.read_response()
  282. if response.get(b"proto") != int(self.protocol) and response.get(
  283. "proto"
  284. ) != int(self.protocol):
  285. raise ConnectionError("Invalid RESP version")
  286. # avoid checking health here -- PING will fail if we try
  287. # to check the health prior to the AUTH
  288. elif auth_args:
  289. await self.send_command("AUTH", *auth_args, check_health=False)
  290. try:
  291. auth_response = await self.read_response()
  292. except AuthenticationWrongNumberOfArgsError:
  293. # a username and password were specified but the Redis
  294. # server seems to be < 6.0.0 which expects a single password
  295. # arg. retry auth with just the password.
  296. # https://github.com/andymccurdy/redis-py/issues/1274
  297. await self.send_command("AUTH", auth_args[-1], check_health=False)
  298. auth_response = await self.read_response()
  299. if str_if_bytes(auth_response) != "OK":
  300. raise AuthenticationError("Invalid Username or Password")
  301. # if resp version is specified, switch to it
  302. elif self.protocol not in [2, "2"]:
  303. if isinstance(self._parser, _AsyncRESP2Parser):
  304. self.set_parser(_AsyncRESP3Parser)
  305. # update cluster exception classes
  306. self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
  307. self._parser.on_connect(self)
  308. await self.send_command("HELLO", self.protocol)
  309. response = await self.read_response()
  310. # if response.get(b"proto") != self.protocol and response.get(
  311. # "proto"
  312. # ) != self.protocol:
  313. # raise ConnectionError("Invalid RESP version")
  314. # if a client_name is given, set it
  315. if self.client_name:
  316. await self.send_command("CLIENT", "SETNAME", self.client_name)
  317. if str_if_bytes(await self.read_response()) != "OK":
  318. raise ConnectionError("Error setting client name")
  319. # set the library name and version, pipeline for lower startup latency
  320. if self.lib_name:
  321. await self.send_command("CLIENT", "SETINFO", "LIB-NAME", self.lib_name)
  322. if self.lib_version:
  323. await self.send_command("CLIENT", "SETINFO", "LIB-VER", self.lib_version)
  324. # if a database is specified, switch to it. Also pipeline this
  325. if self.db:
  326. await self.send_command("SELECT", self.db)
  327. # read responses from pipeline
  328. for _ in (sent for sent in (self.lib_name, self.lib_version) if sent):
  329. try:
  330. await self.read_response()
  331. except ResponseError:
  332. pass
  333. if self.db:
  334. if str_if_bytes(await self.read_response()) != "OK":
  335. raise ConnectionError("Invalid Database")
  336. async def disconnect(self, nowait: bool = False) -> None:
  337. """Disconnects from the Redis server"""
  338. try:
  339. async with async_timeout(self.socket_connect_timeout):
  340. self._parser.on_disconnect()
  341. if not self.is_connected:
  342. return
  343. try:
  344. self._writer.close() # type: ignore[union-attr]
  345. # wait for close to finish, except when handling errors and
  346. # forcefully disconnecting.
  347. if not nowait:
  348. await self._writer.wait_closed() # type: ignore[union-attr]
  349. except OSError:
  350. pass
  351. finally:
  352. self._reader = None
  353. self._writer = None
  354. except asyncio.TimeoutError:
  355. raise TimeoutError(
  356. f"Timed out closing connection after {self.socket_connect_timeout}"
  357. ) from None
  358. async def _send_ping(self):
  359. """Send PING, expect PONG in return"""
  360. await self.send_command("PING", check_health=False)
  361. if str_if_bytes(await self.read_response()) != "PONG":
  362. raise ConnectionError("Bad response from PING health check")
  363. async def _ping_failed(self, error):
  364. """Function to call when PING fails"""
  365. await self.disconnect()
  366. async def check_health(self):
  367. """Check the health of the connection with a PING/PONG"""
  368. if (
  369. self.health_check_interval
  370. and asyncio.get_running_loop().time() > self.next_health_check
  371. ):
  372. await self.retry.call_with_retry(self._send_ping, self._ping_failed)
  373. async def _send_packed_command(self, command: Iterable[bytes]) -> None:
  374. self._writer.writelines(command)
  375. await self._writer.drain()
  376. async def send_packed_command(
  377. self, command: Union[bytes, str, Iterable[bytes]], check_health: bool = True
  378. ) -> None:
  379. if not self.is_connected:
  380. await self.connect()
  381. elif check_health:
  382. await self.check_health()
  383. try:
  384. if isinstance(command, str):
  385. command = command.encode()
  386. if isinstance(command, bytes):
  387. command = [command]
  388. if self.socket_timeout:
  389. await asyncio.wait_for(
  390. self._send_packed_command(command), self.socket_timeout
  391. )
  392. else:
  393. self._writer.writelines(command)
  394. await self._writer.drain()
  395. except asyncio.TimeoutError:
  396. await self.disconnect(nowait=True)
  397. raise TimeoutError("Timeout writing to socket") from None
  398. except OSError as e:
  399. await self.disconnect(nowait=True)
  400. if len(e.args) == 1:
  401. err_no, errmsg = "UNKNOWN", e.args[0]
  402. else:
  403. err_no = e.args[0]
  404. errmsg = e.args[1]
  405. raise ConnectionError(
  406. f"Error {err_no} while writing to socket. {errmsg}."
  407. ) from e
  408. except BaseException:
  409. # BaseExceptions can be raised when a socket send operation is not
  410. # finished, e.g. due to a timeout. Ideally, a caller could then re-try
  411. # to send un-sent data. However, the send_packed_command() API
  412. # does not support it so there is no point in keeping the connection open.
  413. await self.disconnect(nowait=True)
  414. raise
  415. async def send_command(self, *args: Any, **kwargs: Any) -> None:
  416. """Pack and send a command to the Redis server"""
  417. await self.send_packed_command(
  418. self.pack_command(*args), check_health=kwargs.get("check_health", True)
  419. )
  420. async def can_read_destructive(self):
  421. """Poll the socket to see if there's data that can be read."""
  422. try:
  423. return await self._parser.can_read_destructive()
  424. except OSError as e:
  425. await self.disconnect(nowait=True)
  426. host_error = self._host_error()
  427. raise ConnectionError(f"Error while reading from {host_error}: {e.args}")
  428. async def read_response(
  429. self,
  430. disable_decoding: bool = False,
  431. timeout: Optional[float] = None,
  432. *,
  433. disconnect_on_error: bool = True,
  434. push_request: Optional[bool] = False,
  435. ):
  436. """Read the response from a previously sent command"""
  437. read_timeout = timeout if timeout is not None else self.socket_timeout
  438. host_error = self._host_error()
  439. try:
  440. if (
  441. read_timeout is not None
  442. and self.protocol in ["3", 3]
  443. and not HIREDIS_AVAILABLE
  444. ):
  445. async with async_timeout(read_timeout):
  446. response = await self._parser.read_response(
  447. disable_decoding=disable_decoding, push_request=push_request
  448. )
  449. elif read_timeout is not None:
  450. async with async_timeout(read_timeout):
  451. response = await self._parser.read_response(
  452. disable_decoding=disable_decoding
  453. )
  454. elif self.protocol in ["3", 3] and not HIREDIS_AVAILABLE:
  455. response = await self._parser.read_response(
  456. disable_decoding=disable_decoding, push_request=push_request
  457. )
  458. else:
  459. response = await self._parser.read_response(
  460. disable_decoding=disable_decoding
  461. )
  462. except asyncio.TimeoutError:
  463. if timeout is not None:
  464. # user requested timeout, return None. Operation can be retried
  465. return None
  466. # it was a self.socket_timeout error.
  467. if disconnect_on_error:
  468. await self.disconnect(nowait=True)
  469. raise TimeoutError(f"Timeout reading from {host_error}")
  470. except OSError as e:
  471. if disconnect_on_error:
  472. await self.disconnect(nowait=True)
  473. raise ConnectionError(f"Error while reading from {host_error} : {e.args}")
  474. except BaseException:
  475. # Also by default close in case of BaseException. A lot of code
  476. # relies on this behaviour when doing Command/Response pairs.
  477. # See #1128.
  478. if disconnect_on_error:
  479. await self.disconnect(nowait=True)
  480. raise
  481. if self.health_check_interval:
  482. next_time = asyncio.get_running_loop().time() + self.health_check_interval
  483. self.next_health_check = next_time
  484. if isinstance(response, ResponseError):
  485. raise response from None
  486. return response
  487. def pack_command(self, *args: EncodableT) -> List[bytes]:
  488. """Pack a series of arguments into the Redis protocol"""
  489. output = []
  490. # the client might have included 1 or more literal arguments in
  491. # the command name, e.g., 'CONFIG GET'. The Redis server expects these
  492. # arguments to be sent separately, so split the first argument
  493. # manually. These arguments should be bytestrings so that they are
  494. # not encoded.
  495. assert not isinstance(args[0], float)
  496. if isinstance(args[0], str):
  497. args = tuple(args[0].encode().split()) + args[1:]
  498. elif b" " in args[0]:
  499. args = tuple(args[0].split()) + args[1:]
  500. buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))
  501. buffer_cutoff = self._buffer_cutoff
  502. for arg in map(self.encoder.encode, args):
  503. # to avoid large string mallocs, chunk the command into the
  504. # output list if we're sending large values or memoryviews
  505. arg_length = len(arg)
  506. if (
  507. len(buff) > buffer_cutoff
  508. or arg_length > buffer_cutoff
  509. or isinstance(arg, memoryview)
  510. ):
  511. buff = SYM_EMPTY.join(
  512. (buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF)
  513. )
  514. output.append(buff)
  515. output.append(arg)
  516. buff = SYM_CRLF
  517. else:
  518. buff = SYM_EMPTY.join(
  519. (
  520. buff,
  521. SYM_DOLLAR,
  522. str(arg_length).encode(),
  523. SYM_CRLF,
  524. arg,
  525. SYM_CRLF,
  526. )
  527. )
  528. output.append(buff)
  529. return output
  530. def pack_commands(self, commands: Iterable[Iterable[EncodableT]]) -> List[bytes]:
  531. """Pack multiple commands into the Redis protocol"""
  532. output: List[bytes] = []
  533. pieces: List[bytes] = []
  534. buffer_length = 0
  535. buffer_cutoff = self._buffer_cutoff
  536. for cmd in commands:
  537. for chunk in self.pack_command(*cmd):
  538. chunklen = len(chunk)
  539. if (
  540. buffer_length > buffer_cutoff
  541. or chunklen > buffer_cutoff
  542. or isinstance(chunk, memoryview)
  543. ):
  544. if pieces:
  545. output.append(SYM_EMPTY.join(pieces))
  546. buffer_length = 0
  547. pieces = []
  548. if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
  549. output.append(chunk)
  550. else:
  551. pieces.append(chunk)
  552. buffer_length += chunklen
  553. if pieces:
  554. output.append(SYM_EMPTY.join(pieces))
  555. return output
  556. class Connection(AbstractConnection):
  557. "Manages TCP communication to and from a Redis server"
  558. def __init__(
  559. self,
  560. *,
  561. host: str = "localhost",
  562. port: Union[str, int] = 6379,
  563. socket_keepalive: bool = False,
  564. socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
  565. socket_type: int = 0,
  566. **kwargs,
  567. ):
  568. self.host = host
  569. self.port = int(port)
  570. self.socket_keepalive = socket_keepalive
  571. self.socket_keepalive_options = socket_keepalive_options or {}
  572. self.socket_type = socket_type
  573. super().__init__(**kwargs)
  574. def repr_pieces(self):
  575. pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
  576. if self.client_name:
  577. pieces.append(("client_name", self.client_name))
  578. return pieces
  579. def _connection_arguments(self) -> Mapping:
  580. return {"host": self.host, "port": self.port}
  581. async def _connect(self):
  582. """Create a TCP socket connection"""
  583. async with async_timeout(self.socket_connect_timeout):
  584. reader, writer = await asyncio.open_connection(
  585. **self._connection_arguments()
  586. )
  587. self._reader = reader
  588. self._writer = writer
  589. sock = writer.transport.get_extra_info("socket")
  590. if sock:
  591. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  592. try:
  593. # TCP_KEEPALIVE
  594. if self.socket_keepalive:
  595. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  596. for k, v in self.socket_keepalive_options.items():
  597. sock.setsockopt(socket.SOL_TCP, k, v)
  598. except (OSError, TypeError):
  599. # `socket_keepalive_options` might contain invalid options
  600. # causing an error. Do not leave the connection open.
  601. writer.close()
  602. raise
  603. def _host_error(self) -> str:
  604. return f"{self.host}:{self.port}"
  605. def _error_message(self, exception: BaseException) -> str:
  606. # args for socket.error can either be (errno, "message")
  607. # or just "message"
  608. host_error = self._host_error()
  609. if not exception.args:
  610. # asyncio has a bug where on Connection reset by peer, the
  611. # exception is not instanciated, so args is empty. This is the
  612. # workaround.
  613. # See: https://github.com/redis/redis-py/issues/2237
  614. # See: https://github.com/python/cpython/issues/94061
  615. return f"Error connecting to {host_error}. Connection reset by peer"
  616. elif len(exception.args) == 1:
  617. return f"Error connecting to {host_error}. {exception.args[0]}."
  618. else:
  619. return (
  620. f"Error {exception.args[0]} connecting to {host_error}. "
  621. f"{exception.args[0]}."
  622. )
  623. class SSLConnection(Connection):
  624. """Manages SSL connections to and from the Redis server(s).
  625. This class extends the Connection class, adding SSL functionality, and making
  626. use of ssl.SSLContext (https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
  627. """
  628. def __init__(
  629. self,
  630. ssl_keyfile: Optional[str] = None,
  631. ssl_certfile: Optional[str] = None,
  632. ssl_cert_reqs: str = "required",
  633. ssl_ca_certs: Optional[str] = None,
  634. ssl_ca_data: Optional[str] = None,
  635. ssl_check_hostname: bool = False,
  636. **kwargs,
  637. ):
  638. self.ssl_context: RedisSSLContext = RedisSSLContext(
  639. keyfile=ssl_keyfile,
  640. certfile=ssl_certfile,
  641. cert_reqs=ssl_cert_reqs,
  642. ca_certs=ssl_ca_certs,
  643. ca_data=ssl_ca_data,
  644. check_hostname=ssl_check_hostname,
  645. )
  646. super().__init__(**kwargs)
  647. def _connection_arguments(self) -> Mapping:
  648. kwargs = super()._connection_arguments()
  649. kwargs["ssl"] = self.ssl_context.get()
  650. return kwargs
  651. @property
  652. def keyfile(self):
  653. return self.ssl_context.keyfile
  654. @property
  655. def certfile(self):
  656. return self.ssl_context.certfile
  657. @property
  658. def cert_reqs(self):
  659. return self.ssl_context.cert_reqs
  660. @property
  661. def ca_certs(self):
  662. return self.ssl_context.ca_certs
  663. @property
  664. def ca_data(self):
  665. return self.ssl_context.ca_data
  666. @property
  667. def check_hostname(self):
  668. return self.ssl_context.check_hostname
  669. class RedisSSLContext:
  670. __slots__ = (
  671. "keyfile",
  672. "certfile",
  673. "cert_reqs",
  674. "ca_certs",
  675. "ca_data",
  676. "context",
  677. "check_hostname",
  678. )
  679. def __init__(
  680. self,
  681. keyfile: Optional[str] = None,
  682. certfile: Optional[str] = None,
  683. cert_reqs: Optional[str] = None,
  684. ca_certs: Optional[str] = None,
  685. ca_data: Optional[str] = None,
  686. check_hostname: bool = False,
  687. ):
  688. self.keyfile = keyfile
  689. self.certfile = certfile
  690. if cert_reqs is None:
  691. self.cert_reqs = ssl.CERT_NONE
  692. elif isinstance(cert_reqs, str):
  693. CERT_REQS = {
  694. "none": ssl.CERT_NONE,
  695. "optional": ssl.CERT_OPTIONAL,
  696. "required": ssl.CERT_REQUIRED,
  697. }
  698. if cert_reqs not in CERT_REQS:
  699. raise RedisError(
  700. f"Invalid SSL Certificate Requirements Flag: {cert_reqs}"
  701. )
  702. self.cert_reqs = CERT_REQS[cert_reqs]
  703. self.ca_certs = ca_certs
  704. self.ca_data = ca_data
  705. self.check_hostname = check_hostname
  706. self.context: Optional[ssl.SSLContext] = None
  707. def get(self) -> ssl.SSLContext:
  708. if not self.context:
  709. context = ssl.create_default_context()
  710. context.check_hostname = self.check_hostname
  711. context.verify_mode = self.cert_reqs
  712. if self.certfile and self.keyfile:
  713. context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
  714. if self.ca_certs or self.ca_data:
  715. context.load_verify_locations(cafile=self.ca_certs, cadata=self.ca_data)
  716. self.context = context
  717. return self.context
  718. class UnixDomainSocketConnection(AbstractConnection):
  719. "Manages UDS communication to and from a Redis server"
  720. def __init__(self, *, path: str = "", **kwargs):
  721. self.path = path
  722. super().__init__(**kwargs)
  723. def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
  724. pieces = [("path", self.path), ("db", self.db)]
  725. if self.client_name:
  726. pieces.append(("client_name", self.client_name))
  727. return pieces
  728. async def _connect(self):
  729. async with async_timeout(self.socket_connect_timeout):
  730. reader, writer = await asyncio.open_unix_connection(path=self.path)
  731. self._reader = reader
  732. self._writer = writer
  733. await self.on_connect()
  734. def _host_error(self) -> str:
  735. return self.path
  736. def _error_message(self, exception: BaseException) -> str:
  737. # args for socket.error can either be (errno, "message")
  738. # or just "message"
  739. host_error = self._host_error()
  740. if len(exception.args) == 1:
  741. return (
  742. f"Error connecting to unix socket: {host_error}. {exception.args[0]}."
  743. )
  744. else:
  745. return (
  746. f"Error {exception.args[0]} connecting to unix socket: "
  747. f"{host_error}. {exception.args[1]}."
  748. )
  749. FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO")
  750. def to_bool(value) -> Optional[bool]:
  751. if value is None or value == "":
  752. return None
  753. if isinstance(value, str) and value.upper() in FALSE_STRINGS:
  754. return False
  755. return bool(value)
  756. URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyType(
  757. {
  758. "db": int,
  759. "socket_timeout": float,
  760. "socket_connect_timeout": float,
  761. "socket_keepalive": to_bool,
  762. "retry_on_timeout": to_bool,
  763. "max_connections": int,
  764. "health_check_interval": int,
  765. "ssl_check_hostname": to_bool,
  766. }
  767. )
  768. class ConnectKwargs(TypedDict, total=False):
  769. username: str
  770. password: str
  771. connection_class: Type[AbstractConnection]
  772. host: str
  773. port: int
  774. db: int
  775. path: str
  776. def parse_url(url: str) -> ConnectKwargs:
  777. parsed: ParseResult = urlparse(url)
  778. kwargs: ConnectKwargs = {}
  779. for name, value_list in parse_qs(parsed.query).items():
  780. if value_list and len(value_list) > 0:
  781. value = unquote(value_list[0])
  782. parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
  783. if parser:
  784. try:
  785. kwargs[name] = parser(value)
  786. except (TypeError, ValueError):
  787. raise ValueError(f"Invalid value for `{name}` in connection URL.")
  788. else:
  789. kwargs[name] = value
  790. if parsed.username:
  791. kwargs["username"] = unquote(parsed.username)
  792. if parsed.password:
  793. kwargs["password"] = unquote(parsed.password)
  794. # We only support redis://, rediss:// and unix:// schemes.
  795. if parsed.scheme == "unix":
  796. if parsed.path:
  797. kwargs["path"] = unquote(parsed.path)
  798. kwargs["connection_class"] = UnixDomainSocketConnection
  799. elif parsed.scheme in ("redis", "rediss"):
  800. if parsed.hostname:
  801. kwargs["host"] = unquote(parsed.hostname)
  802. if parsed.port:
  803. kwargs["port"] = int(parsed.port)
  804. # If there's a path argument, use it as the db argument if a
  805. # querystring value wasn't specified
  806. if parsed.path and "db" not in kwargs:
  807. try:
  808. kwargs["db"] = int(unquote(parsed.path).replace("/", ""))
  809. except (AttributeError, ValueError):
  810. pass
  811. if parsed.scheme == "rediss":
  812. kwargs["connection_class"] = SSLConnection
  813. else:
  814. valid_schemes = "redis://, rediss://, unix://"
  815. raise ValueError(
  816. f"Redis URL must specify one of the following schemes ({valid_schemes})"
  817. )
  818. return kwargs
  819. _CP = TypeVar("_CP", bound="ConnectionPool")
  820. class ConnectionPool:
  821. """
  822. Create a connection pool. ``If max_connections`` is set, then this
  823. object raises :py:class:`~redis.ConnectionError` when the pool's
  824. limit is reached.
  825. By default, TCP connections are created unless ``connection_class``
  826. is specified. Use :py:class:`~redis.UnixDomainSocketConnection` for
  827. unix sockets.
  828. Any additional keyword arguments are passed to the constructor of
  829. ``connection_class``.
  830. """
  831. @classmethod
  832. def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
  833. """
  834. Return a connection pool configured from the given URL.
  835. For example::
  836. redis://[[username]:[password]]@localhost:6379/0
  837. rediss://[[username]:[password]]@localhost:6379/0
  838. unix://[username@]/path/to/socket.sock?db=0[&password=password]
  839. Three URL schemes are supported:
  840. - `redis://` creates a TCP socket connection. See more at:
  841. <https://www.iana.org/assignments/uri-schemes/prov/redis>
  842. - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
  843. <https://www.iana.org/assignments/uri-schemes/prov/rediss>
  844. - ``unix://``: creates a Unix Domain Socket connection.
  845. The username, password, hostname, path and all querystring values
  846. are passed through urllib.parse.unquote in order to replace any
  847. percent-encoded values with their corresponding characters.
  848. There are several ways to specify a database number. The first value
  849. found will be used:
  850. 1. A ``db`` querystring option, e.g. redis://localhost?db=0
  851. 2. If using the redis:// or rediss:// schemes, the path argument
  852. of the url, e.g. redis://localhost/0
  853. 3. A ``db`` keyword argument to this function.
  854. If none of these options are specified, the default db=0 is used.
  855. All querystring options are cast to their appropriate Python types.
  856. Boolean arguments can be specified with string values "True"/"False"
  857. or "Yes"/"No". Values that cannot be properly cast cause a
  858. ``ValueError`` to be raised. Once parsed, the querystring arguments
  859. and keyword arguments are passed to the ``ConnectionPool``'s
  860. class initializer. In the case of conflicting arguments, querystring
  861. arguments always win.
  862. """
  863. url_options = parse_url(url)
  864. kwargs.update(url_options)
  865. return cls(**kwargs)
  866. def __init__(
  867. self,
  868. connection_class: Type[AbstractConnection] = Connection,
  869. max_connections: Optional[int] = None,
  870. **connection_kwargs,
  871. ):
  872. max_connections = max_connections or 2**31
  873. if not isinstance(max_connections, int) or max_connections < 0:
  874. raise ValueError('"max_connections" must be a positive integer')
  875. self.connection_class = connection_class
  876. self.connection_kwargs = connection_kwargs
  877. self.max_connections = max_connections
  878. self._available_connections: List[AbstractConnection] = []
  879. self._in_use_connections: Set[AbstractConnection] = set()
  880. self.encoder_class = self.connection_kwargs.get("encoder_class", Encoder)
  881. def __repr__(self):
  882. return (
  883. f"{self.__class__.__name__}"
  884. f"<{self.connection_class(**self.connection_kwargs)!r}>"
  885. )
  886. def reset(self):
  887. self._available_connections = []
  888. self._in_use_connections = set()
  889. def can_get_connection(self) -> bool:
  890. """Return True if a connection can be retrieved from the pool."""
  891. return (
  892. self._available_connections
  893. or len(self._in_use_connections) < self.max_connections
  894. )
  895. async def get_connection(self, command_name, *keys, **options):
  896. """Get a connection from the pool"""
  897. try:
  898. connection = self._available_connections.pop()
  899. except IndexError:
  900. if len(self._in_use_connections) >= self.max_connections:
  901. raise ConnectionError("Too many connections") from None
  902. connection = self.make_connection()
  903. self._in_use_connections.add(connection)
  904. try:
  905. await self.ensure_connection(connection)
  906. except BaseException:
  907. await self.release(connection)
  908. raise
  909. return connection
  910. def get_encoder(self):
  911. """Return an encoder based on encoding settings"""
  912. kwargs = self.connection_kwargs
  913. return self.encoder_class(
  914. encoding=kwargs.get("encoding", "utf-8"),
  915. encoding_errors=kwargs.get("encoding_errors", "strict"),
  916. decode_responses=kwargs.get("decode_responses", False),
  917. )
  918. def make_connection(self):
  919. """Create a new connection. Can be overridden by child classes."""
  920. return self.connection_class(**self.connection_kwargs)
  921. async def ensure_connection(self, connection: AbstractConnection):
  922. """Ensure that the connection object is connected and valid"""
  923. await connection.connect()
  924. # connections that the pool provides should be ready to send
  925. # a command. if not, the connection was either returned to the
  926. # pool before all data has been read or the socket has been
  927. # closed. either way, reconnect and verify everything is good.
  928. try:
  929. if await connection.can_read_destructive():
  930. raise ConnectionError("Connection has data") from None
  931. except (ConnectionError, OSError):
  932. await connection.disconnect()
  933. await connection.connect()
  934. if await connection.can_read_destructive():
  935. raise ConnectionError("Connection not ready") from None
  936. async def release(self, connection: AbstractConnection):
  937. """Releases the connection back to the pool"""
  938. # Connections should always be returned to the correct pool,
  939. # not doing so is an error that will cause an exception here.
  940. self._in_use_connections.remove(connection)
  941. self._available_connections.append(connection)
  942. async def disconnect(self, inuse_connections: bool = True):
  943. """
  944. Disconnects connections in the pool
  945. If ``inuse_connections`` is True, disconnect connections that are
  946. current in use, potentially by other tasks. Otherwise only disconnect
  947. connections that are idle in the pool.
  948. """
  949. if inuse_connections:
  950. connections: Iterable[AbstractConnection] = chain(
  951. self._available_connections, self._in_use_connections
  952. )
  953. else:
  954. connections = self._available_connections
  955. resp = await asyncio.gather(
  956. *(connection.disconnect() for connection in connections),
  957. return_exceptions=True,
  958. )
  959. exc = next((r for r in resp if isinstance(r, BaseException)), None)
  960. if exc:
  961. raise exc
  962. async def aclose(self) -> None:
  963. """Close the pool, disconnecting all connections"""
  964. await self.disconnect()
  965. def set_retry(self, retry: "Retry") -> None:
  966. for conn in self._available_connections:
  967. conn.retry = retry
  968. for conn in self._in_use_connections:
  969. conn.retry = retry
  970. class BlockingConnectionPool(ConnectionPool):
  971. """
  972. A blocking connection pool::
  973. >>> from redis.asyncio import Redis, BlockingConnectionPool
  974. >>> client = Redis.from_pool(BlockingConnectionPool())
  975. It performs the same function as the default
  976. :py:class:`~redis.asyncio.ConnectionPool` implementation, in that,
  977. it maintains a pool of reusable connections that can be shared by
  978. multiple async redis clients.
  979. The difference is that, in the event that a client tries to get a
  980. connection from the pool when all of connections are in use, rather than
  981. raising a :py:class:`~redis.ConnectionError` (as the default
  982. :py:class:`~redis.asyncio.ConnectionPool` implementation does), it
  983. makes blocks the current `Task` for a specified number of seconds until
  984. a connection becomes available.
  985. Use ``max_connections`` to increase / decrease the pool size::
  986. >>> pool = BlockingConnectionPool(max_connections=10)
  987. Use ``timeout`` to tell it either how many seconds to wait for a connection
  988. to become available, or to block forever:
  989. >>> # Block forever.
  990. >>> pool = BlockingConnectionPool(timeout=None)
  991. >>> # Raise a ``ConnectionError`` after five seconds if a connection is
  992. >>> # not available.
  993. >>> pool = BlockingConnectionPool(timeout=5)
  994. """
  995. def __init__(
  996. self,
  997. max_connections: int = 50,
  998. timeout: Optional[int] = 20,
  999. connection_class: Type[AbstractConnection] = Connection,
  1000. queue_class: Type[asyncio.Queue] = asyncio.LifoQueue, # deprecated
  1001. **connection_kwargs,
  1002. ):
  1003. super().__init__(
  1004. connection_class=connection_class,
  1005. max_connections=max_connections,
  1006. **connection_kwargs,
  1007. )
  1008. self._condition = asyncio.Condition()
  1009. self.timeout = timeout
  1010. async def get_connection(self, command_name, *keys, **options):
  1011. """Gets a connection from the pool, blocking until one is available"""
  1012. try:
  1013. async with async_timeout(self.timeout):
  1014. async with self._condition:
  1015. await self._condition.wait_for(self.can_get_connection)
  1016. return await super().get_connection(command_name, *keys, **options)
  1017. except asyncio.TimeoutError as err:
  1018. raise ConnectionError("No connection available.") from err
  1019. async def release(self, connection: AbstractConnection):
  1020. """Releases the connection back to the pool."""
  1021. async with self._condition:
  1022. await super().release(connection)
  1023. self._condition.notify()