connection.py 48 KB

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