funboost 45.7__py3-none-any.whl → 45.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of funboost might be problematic. Click here for more details.

Files changed (71) hide show
  1. funboost/__init__.py +1 -1
  2. funboost/concurrent_pool/custom_threadpool_executor.py +2 -2
  3. funboost/concurrent_pool/flexible_thread_pool.py +2 -2
  4. funboost/core/func_params_model.py +1 -0
  5. funboost/core/msg_result_getter.py +15 -1
  6. funboost/function_result_web/__pycache__/app.cpython-37.pyc +0 -0
  7. funboost/function_result_web/__pycache__/functions.cpython-37.pyc +0 -0
  8. funboost/utils/dependency_packages_in_pythonpath/__pycache__/__init__.cpython-311.pyc +0 -0
  9. funboost/utils/dependency_packages_in_pythonpath/__pycache__/__init__.cpython-37.pyc +0 -0
  10. funboost/utils/dependency_packages_in_pythonpath/__pycache__/__init__.cpython-39.pyc +0 -0
  11. funboost/utils/dependency_packages_in_pythonpath/__pycache__/add_to_pythonpath.cpython-311.pyc +0 -0
  12. funboost/utils/dependency_packages_in_pythonpath/__pycache__/add_to_pythonpath.cpython-37.pyc +0 -0
  13. funboost/utils/dependency_packages_in_pythonpath/__pycache__/add_to_pythonpath.cpython-39.pyc +0 -0
  14. funboost/utils/dependency_packages_in_pythonpath/aioredis/__init__.py +59 -59
  15. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/__init__.cpython-311.pyc +0 -0
  16. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/__init__.cpython-37.pyc +0 -0
  17. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/__init__.cpython-39.pyc +0 -0
  18. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/client.cpython-311.pyc +0 -0
  19. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/client.cpython-37.pyc +0 -0
  20. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/client.cpython-39.pyc +0 -0
  21. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/compat.cpython-311.pyc +0 -0
  22. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/compat.cpython-37.pyc +0 -0
  23. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/compat.cpython-39.pyc +0 -0
  24. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/connection.cpython-311.pyc +0 -0
  25. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/connection.cpython-37.pyc +0 -0
  26. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/connection.cpython-39.pyc +0 -0
  27. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/exceptions.cpython-311.pyc +0 -0
  28. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/exceptions.cpython-37.pyc +0 -0
  29. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/exceptions.cpython-39.pyc +0 -0
  30. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/lock.cpython-311.pyc +0 -0
  31. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/lock.cpython-37.pyc +0 -0
  32. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/lock.cpython-39.pyc +0 -0
  33. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/utils.cpython-311.pyc +0 -0
  34. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/utils.cpython-37.pyc +0 -0
  35. funboost/utils/dependency_packages_in_pythonpath/aioredis/__pycache__/utils.cpython-39.pyc +0 -0
  36. funboost/utils/dependency_packages_in_pythonpath/aioredis/client.py +4804 -4804
  37. funboost/utils/dependency_packages_in_pythonpath/aioredis/compat.py +8 -8
  38. funboost/utils/dependency_packages_in_pythonpath/aioredis/connection.py +1668 -1668
  39. funboost/utils/dependency_packages_in_pythonpath/aioredis/exceptions.py +96 -96
  40. funboost/utils/dependency_packages_in_pythonpath/aioredis/lock.py +306 -306
  41. funboost/utils/dependency_packages_in_pythonpath/aioredis/log.py +15 -15
  42. funboost/utils/dependency_packages_in_pythonpath/aioredis/sentinel.py +329 -329
  43. funboost/utils/dependency_packages_in_pythonpath/aioredis/utils.py +61 -61
  44. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__init__.py +16 -16
  45. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/StoppableThread.cpython-311.pyc +0 -0
  46. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/StoppableThread.cpython-37.pyc +0 -0
  47. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/StoppableThread.cpython-39.pyc +0 -0
  48. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/__init__.cpython-311.pyc +0 -0
  49. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/__init__.cpython-37.pyc +0 -0
  50. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/__init__.cpython-39.pyc +0 -0
  51. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/dafunc.cpython-311.pyc +0 -0
  52. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/dafunc.cpython-37.pyc +0 -0
  53. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/dafunc.cpython-39.pyc +0 -0
  54. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/exceptions.cpython-311.pyc +0 -0
  55. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/exceptions.cpython-37.pyc +0 -0
  56. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/exceptions.cpython-39.pyc +0 -0
  57. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/py3_raise.cpython-311.pyc +0 -0
  58. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/py3_raise.cpython-37.pyc +0 -0
  59. funboost/utils/dependency_packages_in_pythonpath/func_timeout/__pycache__/py3_raise.cpython-39.pyc +0 -0
  60. funboost/utils/dependency_packages_in_pythonpath/func_timeout/exceptions.py +98 -98
  61. funboost/utils/dependency_packages_in_pythonpath/func_timeout/py2_raise.py +7 -7
  62. funboost/utils/dependency_packages_in_pythonpath/func_timeout/py3_raise.py +7 -7
  63. funboost/utils/times/__init__.py +85 -85
  64. funboost/utils/times/version.py +1 -1
  65. {funboost-45.7.dist-info → funboost-45.9.dist-info}/METADATA +2 -1
  66. {funboost-45.7.dist-info → funboost-45.9.dist-info}/RECORD +70 -41
  67. {funboost-45.7.dist-info → funboost-45.9.dist-info}/entry_points.txt +1 -0
  68. funboost/function_result_web/__pycache__/functions.cpython-39.pyc +0 -0
  69. {funboost-45.7.dist-info → funboost-45.9.dist-info}/LICENSE +0 -0
  70. {funboost-45.7.dist-info → funboost-45.9.dist-info}/WHEEL +0 -0
  71. {funboost-45.7.dist-info → funboost-45.9.dist-info}/top_level.txt +0 -0
@@ -1,1668 +1,1668 @@
1
- import asyncio
2
- import enum
3
- import errno
4
- import inspect
5
- import io
6
- import os
7
- import socket
8
- import ssl
9
- import threading
10
- import warnings
11
- from distutils.version import StrictVersion
12
- from itertools import chain
13
- from types import MappingProxyType
14
- from typing import (
15
- Any,
16
- Callable,
17
- Iterable,
18
- List,
19
- Mapping,
20
- Optional,
21
- Set,
22
- Tuple,
23
- Type,
24
- TypeVar,
25
- Union,
26
- cast,
27
- )
28
- from urllib.parse import ParseResult, parse_qs, unquote, urlparse
29
-
30
- import async_timeout
31
-
32
- from .compat import Protocol, TypedDict
33
- from .exceptions import (
34
- AuthenticationError,
35
- AuthenticationWrongNumberOfArgsError,
36
- BusyLoadingError,
37
- ChildDeadlockedError,
38
- ConnectionError,
39
- DataError,
40
- ExecAbortError,
41
- InvalidResponse,
42
- ModuleError,
43
- NoPermissionError,
44
- NoScriptError,
45
- ReadOnlyError,
46
- RedisError,
47
- ResponseError,
48
- TimeoutError,
49
- )
50
- from .utils import str_if_bytes
51
-
52
- NONBLOCKING_EXCEPTION_ERROR_NUMBERS = {
53
- BlockingIOError: errno.EWOULDBLOCK,
54
- ssl.SSLWantReadError: 2,
55
- ssl.SSLWantWriteError: 2,
56
- ssl.SSLError: 2,
57
- }
58
-
59
- NONBLOCKING_EXCEPTIONS = tuple(NONBLOCKING_EXCEPTION_ERROR_NUMBERS.keys())
60
-
61
- try:
62
- import hiredis
63
-
64
- except (ImportError, ModuleNotFoundError):
65
- HIREDIS_AVAILABLE = False
66
- else:
67
- HIREDIS_AVAILABLE = True
68
- hiredis_version = StrictVersion(hiredis.__version__)
69
- if hiredis_version < StrictVersion("1.0.0"):
70
- warnings.warn(
71
- "aioredis supports hiredis @ 1.0.0 or higher. "
72
- f"You have hiredis @ {hiredis.__version__}. "
73
- "Pure-python parser will be used instead."
74
- )
75
- HIREDIS_AVAILABLE = False
76
-
77
- SYM_STAR = b"*"
78
- SYM_DOLLAR = b"$"
79
- SYM_CRLF = b"\r\n"
80
- SYM_LF = b"\n"
81
- SYM_EMPTY = b""
82
-
83
- SERVER_CLOSED_CONNECTION_ERROR = "Connection closed by server."
84
-
85
-
86
- class _Sentinel(enum.Enum):
87
- sentinel = object()
88
-
89
-
90
- SENTINEL = _Sentinel.sentinel
91
- MODULE_LOAD_ERROR = "Error loading the extension. Please check the server logs."
92
- NO_SUCH_MODULE_ERROR = "Error unloading module: no such module with that name"
93
- MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not possible."
94
- MODULE_EXPORTS_DATA_TYPES_ERROR = (
95
- "Error unloading module: the module "
96
- "exports one or more module-side data "
97
- "types, can't unload"
98
- )
99
-
100
- EncodedT = Union[bytes, memoryview]
101
- DecodedT = Union[str, int, float]
102
- EncodableT = Union[EncodedT, DecodedT]
103
-
104
-
105
- class _HiredisReaderArgs(TypedDict, total=False):
106
- protocolError: Callable[[str], Exception]
107
- replyError: Callable[[str], Exception]
108
- encoding: Optional[str]
109
- errors: Optional[str]
110
-
111
-
112
- class Encoder:
113
- """Encode strings to bytes-like and decode bytes-like to strings"""
114
-
115
- __slots__ = "encoding", "encoding_errors", "decode_responses"
116
-
117
- def __init__(self, encoding: str, encoding_errors: str, decode_responses: bool):
118
- self.encoding = encoding
119
- self.encoding_errors = encoding_errors
120
- self.decode_responses = decode_responses
121
-
122
- def encode(self, value: EncodableT) -> EncodedT:
123
- """Return a bytestring or bytes-like representation of the value"""
124
- if isinstance(value, (bytes, memoryview)):
125
- return value
126
- if isinstance(value, bool):
127
- # special case bool since it is a subclass of int
128
- raise DataError(
129
- "Invalid input of type: 'bool'. "
130
- "Convert to a bytes, string, int or float first."
131
- )
132
- if isinstance(value, (int, float)):
133
- return repr(value).encode()
134
- if not isinstance(value, str):
135
- # a value we don't know how to deal with. throw an error
136
- typename = value.__class__.__name__ # type: ignore[unreachable]
137
- raise DataError(
138
- f"Invalid input of type: {typename!r}. "
139
- "Convert to a bytes, string, int or float first."
140
- )
141
- return value.encode(self.encoding, self.encoding_errors)
142
-
143
- def decode(self, value: EncodableT, force=False) -> EncodableT:
144
- """Return a unicode string from the bytes-like representation"""
145
- if self.decode_responses or force:
146
- if isinstance(value, memoryview):
147
- return value.tobytes().decode(self.encoding, self.encoding_errors)
148
- if isinstance(value, bytes):
149
- return value.decode(self.encoding, self.encoding_errors)
150
- return value
151
-
152
-
153
- ExceptionMappingT = Mapping[str, Union[Type[Exception], Mapping[str, Type[Exception]]]]
154
-
155
-
156
- class BaseParser:
157
- """Plain Python parsing class"""
158
-
159
- __slots__ = "_stream", "_buffer", "_read_size"
160
-
161
- EXCEPTION_CLASSES: ExceptionMappingT = {
162
- "ERR": {
163
- "max number of clients reached": ConnectionError,
164
- "Client sent AUTH, but no password is set": AuthenticationError,
165
- "invalid password": AuthenticationError,
166
- # some Redis server versions report invalid command syntax
167
- # in lowercase
168
- "wrong number of arguments for 'auth' command": AuthenticationWrongNumberOfArgsError,
169
- # some Redis server versions report invalid command syntax
170
- # in uppercase
171
- "wrong number of arguments for 'AUTH' command": AuthenticationWrongNumberOfArgsError,
172
- MODULE_LOAD_ERROR: ModuleError,
173
- MODULE_EXPORTS_DATA_TYPES_ERROR: ModuleError,
174
- NO_SUCH_MODULE_ERROR: ModuleError,
175
- MODULE_UNLOAD_NOT_POSSIBLE_ERROR: ModuleError,
176
- },
177
- "EXECABORT": ExecAbortError,
178
- "LOADING": BusyLoadingError,
179
- "NOSCRIPT": NoScriptError,
180
- "READONLY": ReadOnlyError,
181
- "NOAUTH": AuthenticationError,
182
- "NOPERM": NoPermissionError,
183
- }
184
-
185
- def __init__(self, socket_read_size: int):
186
- self._stream: Optional[asyncio.StreamReader] = None
187
- self._buffer: Optional[SocketBuffer] = None
188
- self._read_size = socket_read_size
189
-
190
- def __del__(self):
191
- try:
192
- self.on_disconnect()
193
- except BaseException :
194
- pass
195
-
196
- def parse_error(self, response: str) -> ResponseError:
197
- """Parse an error response"""
198
- error_code = response.split(" ")[0]
199
- if error_code in self.EXCEPTION_CLASSES:
200
- response = response[len(error_code) + 1 :]
201
- exception_class_or_dict = self.EXCEPTION_CLASSES[error_code]
202
- if isinstance(exception_class_or_dict, dict):
203
- exception_class = exception_class_or_dict.get(response, ResponseError)
204
- else:
205
- exception_class = exception_class_or_dict
206
- return exception_class(response)
207
- return ResponseError(response)
208
-
209
- def on_disconnect(self):
210
- raise NotImplementedError()
211
-
212
- def on_connect(self, connection: "Connection"):
213
- raise NotImplementedError()
214
-
215
- async def can_read(self, timeout: float) -> bool:
216
- raise NotImplementedError()
217
-
218
- async def read_response(
219
- self,
220
- ) -> Union[EncodableT, ResponseError, None, List[EncodableT]]:
221
- raise NotImplementedError()
222
-
223
-
224
- class SocketBuffer:
225
- """Async-friendly re-impl of redis-py's SocketBuffer.
226
-
227
- TODO: We're currently passing through two buffers,
228
- the asyncio.StreamReader and this. I imagine we can reduce the layers here
229
- while maintaining compliance with prior art.
230
- """
231
-
232
- def __init__(
233
- self,
234
- stream_reader: asyncio.StreamReader,
235
- socket_read_size: int,
236
- socket_timeout: Optional[float],
237
- ):
238
- self._stream: Optional[asyncio.StreamReader] = stream_reader
239
- self.socket_read_size = socket_read_size
240
- self.socket_timeout = socket_timeout
241
- self._buffer: Optional[io.BytesIO] = io.BytesIO()
242
- # number of bytes written to the buffer from the socket
243
- self.bytes_written = 0
244
- # number of bytes read from the buffer
245
- self.bytes_read = 0
246
-
247
- @property
248
- def length(self):
249
- return self.bytes_written - self.bytes_read
250
-
251
- async def _read_from_socket(
252
- self,
253
- length: Optional[int] = None,
254
- timeout: Union[float, None, _Sentinel] = SENTINEL,
255
- raise_on_timeout: bool = True,
256
- ) -> bool:
257
- buf = self._buffer
258
- if buf is None or self._stream is None:
259
- raise RedisError("Buffer is closed.")
260
- buf.seek(self.bytes_written)
261
- marker = 0
262
- timeout = timeout if timeout is not SENTINEL else self.socket_timeout
263
-
264
- try:
265
- while True:
266
- async with async_timeout.timeout(timeout):
267
- data = await self._stream.read(self.socket_read_size)
268
- # an empty string indicates the server shutdown the socket
269
- if isinstance(data, bytes) and len(data) == 0:
270
- raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
271
- buf.write(data)
272
- data_length = len(data)
273
- self.bytes_written += data_length
274
- marker += data_length
275
-
276
- if length is not None and length > marker:
277
- continue
278
- return True
279
- except (socket.timeout, asyncio.TimeoutError):
280
- if raise_on_timeout:
281
- raise TimeoutError("Timeout reading from socket")
282
- return False
283
- except NONBLOCKING_EXCEPTIONS as ex:
284
- # if we're in nonblocking mode and the recv raises a
285
- # blocking error, simply return False indicating that
286
- # there's no data to be read. otherwise raise the
287
- # original exception.
288
- allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
289
- if not raise_on_timeout and ex.errno == allowed:
290
- return False
291
- raise ConnectionError(f"Error while reading from socket: {ex.args}")
292
-
293
- async def can_read(self, timeout: float) -> bool:
294
- return bool(self.length) or await self._read_from_socket(
295
- timeout=timeout, raise_on_timeout=False
296
- )
297
-
298
- async def read(self, length: int) -> bytes:
299
- length = length + 2 # make sure to read the \r\n terminator
300
- # make sure we've read enough data from the socket
301
- if length > self.length:
302
- await self._read_from_socket(length - self.length)
303
-
304
- if self._buffer is None:
305
- raise RedisError("Buffer is closed.")
306
-
307
- self._buffer.seek(self.bytes_read)
308
- data = self._buffer.read(length)
309
- self.bytes_read += len(data)
310
-
311
- # purge the buffer when we've consumed it all so it doesn't
312
- # grow forever
313
- if self.bytes_read == self.bytes_written:
314
- self.purge()
315
-
316
- return data[:-2]
317
-
318
- async def readline(self) -> bytes:
319
- buf = self._buffer
320
- if buf is None:
321
- raise RedisError("Buffer is closed.")
322
-
323
- buf.seek(self.bytes_read)
324
- data = buf.readline()
325
- while not data.endswith(SYM_CRLF):
326
- # there's more data in the socket that we need
327
- await self._read_from_socket()
328
- buf.seek(self.bytes_read)
329
- data = buf.readline()
330
-
331
- self.bytes_read += len(data)
332
-
333
- # purge the buffer when we've consumed it all so it doesn't
334
- # grow forever
335
- if self.bytes_read == self.bytes_written:
336
- self.purge()
337
-
338
- return data[:-2]
339
-
340
- def purge(self):
341
- if self._buffer is None:
342
- raise RedisError("Buffer is closed.")
343
-
344
- self._buffer.seek(0)
345
- self._buffer.truncate()
346
- self.bytes_written = 0
347
- self.bytes_read = 0
348
-
349
- def close(self):
350
- try:
351
- self.purge()
352
- self._buffer.close() # type: ignore[union-attr]
353
- except BaseException :
354
- # issue #633 suggests the purge/close somehow raised a
355
- # BadFileDescriptor error. Perhaps the client ran out of
356
- # memory or something else? It's probably OK to ignore
357
- # any error being raised from purge/close since we're
358
- # removing the reference to the instance below.
359
- pass
360
- self._buffer = None
361
- self._stream = None
362
-
363
-
364
- class PythonParser(BaseParser):
365
- """Plain Python parsing class"""
366
-
367
- __slots__ = BaseParser.__slots__ + ("encoder",)
368
-
369
- def __init__(self, socket_read_size: int):
370
- super().__init__(socket_read_size)
371
- self.encoder: Optional[Encoder] = None
372
-
373
- def on_connect(self, connection: "Connection"):
374
- """Called when the stream connects"""
375
- self._stream = connection._reader
376
- if self._stream is None:
377
- raise RedisError("Buffer is closed.")
378
-
379
- self._buffer = SocketBuffer(
380
- self._stream, self._read_size, connection.socket_timeout
381
- )
382
- self.encoder = connection.encoder
383
-
384
- def on_disconnect(self):
385
- """Called when the stream disconnects"""
386
- if self._stream is not None:
387
- self._stream = None
388
- if self._buffer is not None:
389
- self._buffer.close()
390
- self._buffer = None
391
- self.encoder = None
392
-
393
- async def can_read(self, timeout: float):
394
- return self._buffer and bool(await self._buffer.can_read(timeout))
395
-
396
- async def read_response(self) -> Union[EncodableT, ResponseError, None]:
397
- if not self._buffer or not self.encoder:
398
- raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
399
- raw = await self._buffer.readline()
400
- if not raw:
401
- raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
402
- response: Any
403
- byte, response = raw[:1], raw[1:]
404
-
405
- if byte not in (b"-", b"+", b":", b"$", b"*"):
406
- raise InvalidResponse(f"Protocol Error: {raw!r}")
407
-
408
- # server returned an error
409
- if byte == b"-":
410
- response = response.decode("utf-8", errors="replace")
411
- error = self.parse_error(response)
412
- # if the error is a ConnectionError, raise immediately so the user
413
- # is notified
414
- if isinstance(error, ConnectionError):
415
- raise error
416
- # otherwise, we're dealing with a ResponseError that might belong
417
- # inside a pipeline response. the connection's read_response()
418
- # and/or the pipeline's execute() will raise this error if
419
- # necessary, so just return the exception instance here.
420
- return error
421
- # single value
422
- elif byte == b"+":
423
- pass
424
- # int value
425
- elif byte == b":":
426
- response = int(response)
427
- # bulk response
428
- elif byte == b"$":
429
- length = int(response)
430
- if length == -1:
431
- return None
432
- response = await self._buffer.read(length)
433
- # multi-bulk response
434
- elif byte == b"*":
435
- length = int(response)
436
- if length == -1:
437
- return None
438
- response = [(await self.read_response()) for _ in range(length)]
439
- if isinstance(response, bytes):
440
- response = self.encoder.decode(response)
441
- return response
442
-
443
-
444
- class HiredisParser(BaseParser):
445
- """Parser class for connections using Hiredis"""
446
-
447
- __slots__ = BaseParser.__slots__ + ("_next_response", "_reader", "_socket_timeout")
448
-
449
- _next_response: bool
450
-
451
- def __init__(self, socket_read_size: int):
452
- if not HIREDIS_AVAILABLE:
453
- raise RedisError("Hiredis is not available.")
454
- super().__init__(socket_read_size=socket_read_size)
455
- self._reader: Optional[hiredis.Reader] = None
456
- self._socket_timeout: Optional[float] = None
457
-
458
- def on_connect(self, connection: "Connection"):
459
- self._stream = connection._reader
460
- kwargs: _HiredisReaderArgs = {
461
- "protocolError": InvalidResponse,
462
- "replyError": self.parse_error,
463
- }
464
- if connection.encoder.decode_responses:
465
- kwargs["encoding"] = connection.encoder.encoding
466
- kwargs["errors"] = connection.encoder.encoding_errors
467
-
468
- self._reader = hiredis.Reader(**kwargs)
469
- self._next_response = False
470
- self._socket_timeout = connection.socket_timeout
471
-
472
- def on_disconnect(self):
473
- self._stream = None
474
- self._reader = None
475
- self._next_response = False
476
-
477
- async def can_read(self, timeout: float):
478
- if not self._reader:
479
- raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
480
-
481
- if self._next_response is False:
482
- self._next_response = self._reader.gets()
483
- if self._next_response is False:
484
- return await self.read_from_socket(timeout=timeout, raise_on_timeout=False)
485
- return True
486
-
487
- async def read_from_socket(
488
- self,
489
- timeout: Union[float, None, _Sentinel] = SENTINEL,
490
- raise_on_timeout: bool = True,
491
- ):
492
- if self._stream is None or self._reader is None:
493
- raise RedisError("Parser already closed.")
494
-
495
- timeout = self._socket_timeout if timeout is SENTINEL else timeout
496
- try:
497
- async with async_timeout.timeout(timeout):
498
- buffer = await self._stream.read(self._read_size)
499
- if not isinstance(buffer, bytes) or len(buffer) == 0:
500
- raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
501
- self._reader.feed(buffer)
502
- # data was read from the socket and added to the buffer.
503
- # return True to indicate that data was read.
504
- return True
505
- except asyncio.CancelledError:
506
- raise
507
- except (socket.timeout, asyncio.TimeoutError):
508
- if raise_on_timeout:
509
- raise TimeoutError("Timeout reading from socket") from None
510
- return False
511
- except NONBLOCKING_EXCEPTIONS as ex:
512
- # if we're in nonblocking mode and the recv raises a
513
- # blocking error, simply return False indicating that
514
- # there's no data to be read. otherwise raise the
515
- # original exception.
516
- allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
517
- if not raise_on_timeout and ex.errno == allowed:
518
- return False
519
- raise ConnectionError(f"Error while reading from socket: {ex.args}")
520
-
521
- async def read_response(self) -> Union[EncodableT, List[EncodableT]]:
522
- if not self._stream or not self._reader:
523
- self.on_disconnect()
524
- raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
525
-
526
- response: Union[
527
- EncodableT, ConnectionError, List[Union[EncodableT, ConnectionError]]
528
- ]
529
- # _next_response might be cached from a can_read() call
530
- if self._next_response is not False:
531
- response = self._next_response
532
- self._next_response = False
533
- return response
534
-
535
- response = self._reader.gets()
536
- while response is False:
537
- await self.read_from_socket()
538
- response = self._reader.gets()
539
-
540
- # if the response is a ConnectionError or the response is a list and
541
- # the first item is a ConnectionError, raise it as something bad
542
- # happened
543
- if isinstance(response, ConnectionError):
544
- raise response
545
- elif (
546
- isinstance(response, list)
547
- and response
548
- and isinstance(response[0], ConnectionError)
549
- ):
550
- raise response[0]
551
- # cast as there won't be a ConnectionError here.
552
- return cast(Union[EncodableT, List[EncodableT]], response)
553
-
554
-
555
- DefaultParser: Type[Union[PythonParser, HiredisParser]]
556
- if HIREDIS_AVAILABLE:
557
- DefaultParser = HiredisParser
558
- else:
559
- DefaultParser = PythonParser
560
-
561
-
562
- class ConnectCallbackProtocol(Protocol):
563
- def __call__(self, connection: "Connection"):
564
- ...
565
-
566
-
567
- class AsyncConnectCallbackProtocol(Protocol):
568
- async def __call__(self, connection: "Connection"):
569
- ...
570
-
571
-
572
- ConnectCallbackT = Union[ConnectCallbackProtocol, AsyncConnectCallbackProtocol]
573
-
574
-
575
- class Connection:
576
- """Manages TCP communication to and from a Redis server"""
577
-
578
- __slots__ = (
579
- "pid",
580
- "host",
581
- "port",
582
- "db",
583
- "username",
584
- "client_name",
585
- "password",
586
- "socket_timeout",
587
- "socket_connect_timeout",
588
- "socket_keepalive",
589
- "socket_keepalive_options",
590
- "socket_type",
591
- "retry_on_timeout",
592
- "health_check_interval",
593
- "next_health_check",
594
- "last_active_at",
595
- "encoder",
596
- "ssl_context",
597
- "_reader",
598
- "_writer",
599
- "_parser",
600
- "_connect_callbacks",
601
- "_buffer_cutoff",
602
- "_lock",
603
- "__dict__",
604
- )
605
-
606
- def __init__(
607
- self,
608
- *,
609
- host: str = "localhost",
610
- port: Union[str, int] = 6379,
611
- db: Union[str, int] = 0,
612
- password: Optional[str] = None,
613
- socket_timeout: Optional[float] = None,
614
- socket_connect_timeout: Optional[float] = None,
615
- socket_keepalive: bool = False,
616
- socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
617
- socket_type: int = 0,
618
- retry_on_timeout: bool = False,
619
- encoding: str = "utf-8",
620
- encoding_errors: str = "strict",
621
- decode_responses: bool = False,
622
- parser_class: Type[BaseParser] = DefaultParser,
623
- socket_read_size: int = 65536,
624
- health_check_interval: float = 0,
625
- client_name: Optional[str] = None,
626
- username: Optional[str] = None,
627
- encoder_class: Type[Encoder] = Encoder,
628
- ):
629
- self.pid = os.getpid()
630
- self.host = host
631
- self.port = int(port)
632
- self.db = db
633
- self.username = username
634
- self.client_name = client_name
635
- self.password = password
636
- self.socket_timeout = socket_timeout
637
- self.socket_connect_timeout = socket_connect_timeout or socket_timeout or None
638
- self.socket_keepalive = socket_keepalive
639
- self.socket_keepalive_options = socket_keepalive_options or {}
640
- self.socket_type = socket_type
641
- self.retry_on_timeout = retry_on_timeout
642
- self.health_check_interval = health_check_interval
643
- self.next_health_check: float = -1
644
- self.ssl_context: Optional[RedisSSLContext] = None
645
- self.encoder = encoder_class(encoding, encoding_errors, decode_responses)
646
- self._reader: Optional[asyncio.StreamReader] = None
647
- self._writer: Optional[asyncio.StreamWriter] = None
648
- self._parser = parser_class(
649
- socket_read_size=socket_read_size,
650
- )
651
- self._connect_callbacks: List[ConnectCallbackT] = []
652
- self._buffer_cutoff = 6000
653
- self._lock = asyncio.Lock()
654
-
655
- def __repr__(self):
656
- repr_args = ",".join((f"{k}={v}" for k, v in self.repr_pieces()))
657
- return f"{self.__class__.__name__}<{repr_args}>"
658
-
659
- def repr_pieces(self):
660
- pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
661
- if self.client_name:
662
- pieces.append(("client_name", self.client_name))
663
- return pieces
664
-
665
- def __del__(self):
666
- try:
667
- if self.is_connected:
668
- loop = asyncio.get_event_loop()
669
- coro = self.disconnect()
670
- if loop.is_running():
671
- loop.create_task(coro)
672
- else:
673
- loop.run_until_complete(coro)
674
- except BaseException :
675
- pass
676
-
677
- @property
678
- def is_connected(self):
679
- return bool(self._reader and self._writer)
680
-
681
- def register_connect_callback(self, callback):
682
- self._connect_callbacks.append(callback)
683
-
684
- def clear_connect_callbacks(self):
685
- self._connect_callbacks = []
686
-
687
- async def connect(self):
688
- """Connects to the Redis server if not already connected"""
689
- if self.is_connected:
690
- return
691
- try:
692
- await self._connect()
693
- except asyncio.CancelledError:
694
- raise
695
- except (socket.timeout, asyncio.TimeoutError):
696
- raise TimeoutError("Timeout connecting to server")
697
- except OSError as e:
698
- raise ConnectionError(self._error_message(e))
699
- except BaseException as exc:
700
- raise ConnectionError(exc) from exc
701
-
702
- try:
703
- await self.on_connect()
704
- except RedisError:
705
- # clean up after any error in on_connect
706
- await self.disconnect()
707
- raise
708
-
709
- # run any user callbacks. right now the only internal callback
710
- # is for pubsub channel/pattern resubscription
711
- for callback in self._connect_callbacks:
712
- task = callback(self)
713
- if task and inspect.isawaitable(task):
714
- await task
715
-
716
- async def _connect(self):
717
- """Create a TCP socket connection"""
718
- async with async_timeout.timeout(self.socket_connect_timeout):
719
- reader, writer = await asyncio.open_connection(
720
- host=self.host,
721
- port=self.port,
722
- ssl=self.ssl_context.get() if self.ssl_context else None,
723
- )
724
- self._reader = reader
725
- self._writer = writer
726
- sock = writer.transport.get_extra_info("socket")
727
- if sock is not None:
728
- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
729
- try:
730
- # TCP_KEEPALIVE
731
- if self.socket_keepalive:
732
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
733
- for k, v in self.socket_keepalive_options.items():
734
- sock.setsockopt(socket.SOL_TCP, k, v)
735
-
736
- except (OSError, TypeError):
737
- # `socket_keepalive_options` might contain invalid options
738
- # causing an error. Do not leave the connection open.
739
- writer.close()
740
- raise
741
-
742
- def _error_message(self, exception):
743
- # args for socket.error can either be (errno, "message")
744
- # or just "message"
745
- if len(exception.args) == 1:
746
- return f"Error connecting to {self.host}:{self.port}. {exception.args[0]}."
747
- else:
748
- return (
749
- f"Error {exception.args[0]} connecting to {self.host}:{self.port}. "
750
- f"{exception.args[0]}."
751
- )
752
-
753
- async def on_connect(self):
754
- """Initialize the connection, authenticate and select a database"""
755
- self._parser.on_connect(self)
756
-
757
- # if username and/or password are set, authenticate
758
- if self.username or self.password:
759
- auth_args: Union[Tuple[str], Tuple[str, str]]
760
- if self.username:
761
- auth_args = (self.username, self.password or "")
762
- else:
763
- # Mypy bug: https://github.com/python/mypy/issues/10944
764
- auth_args = (self.password or "",)
765
- # avoid checking health here -- PING will fail if we try
766
- # to check the health prior to the AUTH
767
- await self.send_command("AUTH", *auth_args, check_health=False)
768
-
769
- try:
770
- auth_response = await self.read_response()
771
- except AuthenticationWrongNumberOfArgsError:
772
- # a username and password were specified but the Redis
773
- # server seems to be < 6.0.0 which expects a single password
774
- # arg. retry auth with just the password.
775
- # https://github.com/andymccurdy/redis-py/issues/1274
776
- await self.send_command("AUTH", self.password, check_health=False)
777
- auth_response = await self.read_response()
778
-
779
- if str_if_bytes(auth_response) != "OK":
780
- raise AuthenticationError("Invalid Username or Password")
781
-
782
- # if a client_name is given, set it
783
- if self.client_name:
784
- await self.send_command("CLIENT", "SETNAME", self.client_name)
785
- if str_if_bytes(await self.read_response()) != "OK":
786
- raise ConnectionError("Error setting client name")
787
-
788
- # if a database is specified, switch to it
789
- if self.db:
790
- await self.send_command("SELECT", self.db)
791
- if str_if_bytes(await self.read_response()) != "OK":
792
- raise ConnectionError("Invalid Database")
793
-
794
- async def disconnect(self):
795
- """Disconnects from the Redis server"""
796
- try:
797
- async with async_timeout.timeout(self.socket_connect_timeout):
798
- self._parser.on_disconnect()
799
- if not self.is_connected:
800
- return
801
- try:
802
- if os.getpid() == self.pid:
803
- self._writer.close() # type: ignore[union-attr]
804
- # py3.6 doesn't have this method
805
- if hasattr(self._writer, "wait_closed"):
806
- await self._writer.wait_closed() # type: ignore[union-attr]
807
- except OSError:
808
- pass
809
- self._reader = None
810
- self._writer = None
811
- except asyncio.TimeoutError:
812
- raise TimeoutError(
813
- f"Timed out closing connection after {self.socket_connect_timeout}"
814
- ) from None
815
-
816
- async def check_health(self):
817
- """Check the health of the connection with a PING/PONG"""
818
- if (
819
- self.health_check_interval
820
- and asyncio.get_event_loop().time() > self.next_health_check
821
- ):
822
- try:
823
- await self.send_command("PING", check_health=False)
824
- if str_if_bytes(await self.read_response()) != "PONG":
825
- raise ConnectionError("Bad response from PING health check")
826
- except (ConnectionError, TimeoutError) as err:
827
- await self.disconnect()
828
- try:
829
- await self.send_command("PING", check_health=False)
830
- if str_if_bytes(await self.read_response()) != "PONG":
831
- raise ConnectionError(
832
- "Bad response from PING health check"
833
- ) from None
834
- except BaseException as err2:
835
- raise err2 from err
836
-
837
- async def _send_packed_command(self, command: Iterable[bytes]) -> None:
838
- if self._writer is None:
839
- raise RedisError("Connection already closed.")
840
-
841
- self._writer.writelines(command)
842
- await self._writer.drain()
843
-
844
- async def send_packed_command(
845
- self,
846
- command: Union[bytes, str, Iterable[bytes]],
847
- check_health: bool = True,
848
- ):
849
- """Send an already packed command to the Redis server"""
850
- if not self._writer:
851
- await self.connect()
852
- # guard against health check recursion
853
- if check_health:
854
- await self.check_health()
855
- try:
856
- if isinstance(command, str):
857
- command = command.encode()
858
- if isinstance(command, bytes):
859
- command = [command]
860
- await asyncio.wait_for(
861
- self._send_packed_command(command),
862
- self.socket_timeout,
863
- )
864
- except asyncio.TimeoutError:
865
- await self.disconnect()
866
- raise TimeoutError("Timeout writing to socket") from None
867
- except OSError as e:
868
- await self.disconnect()
869
- if len(e.args) == 1:
870
- err_no, errmsg = "UNKNOWN", e.args[0]
871
- else:
872
- err_no = e.args[0]
873
- errmsg = e.args[1]
874
- raise ConnectionError(
875
- f"Error {err_no} while writing to socket. {errmsg}."
876
- ) from e
877
- except BaseException:
878
- await self.disconnect()
879
- raise
880
-
881
- async def send_command(self, *args, **kwargs):
882
- """Pack and send a command to the Redis server"""
883
- if not self.is_connected:
884
- await self.connect()
885
- await self.send_packed_command(
886
- self.pack_command(*args), check_health=kwargs.get("check_health", True)
887
- )
888
-
889
- async def can_read(self, timeout: float = 0):
890
- """Poll the socket to see if there's data that can be read."""
891
- if not self.is_connected:
892
- await self.connect()
893
- return await self._parser.can_read(timeout)
894
-
895
- async def read_response(self):
896
- """Read the response from a previously sent command"""
897
- try:
898
- async with self._lock:
899
- async with async_timeout.timeout(self.socket_timeout):
900
- response = await self._parser.read_response()
901
- except asyncio.TimeoutError:
902
- await self.disconnect()
903
- raise TimeoutError(f"Timeout reading from {self.host}:{self.port}")
904
- except OSError as e:
905
- await self.disconnect()
906
- raise ConnectionError(
907
- f"Error while reading from {self.host}:{self.port} : {e.args}"
908
- )
909
- except BaseException:
910
- await self.disconnect()
911
- raise
912
-
913
- if self.health_check_interval:
914
- self.next_health_check = (
915
- asyncio.get_event_loop().time() + self.health_check_interval
916
- )
917
-
918
- if isinstance(response, ResponseError):
919
- raise response from None
920
- return response
921
-
922
- def pack_command(self, *args: EncodableT) -> List[bytes]:
923
- """Pack a series of arguments into the Redis protocol"""
924
- output = []
925
- # the client might have included 1 or more literal arguments in
926
- # the command name, e.g., 'CONFIG GET'. The Redis server expects these
927
- # arguments to be sent separately, so split the first argument
928
- # manually. These arguments should be bytestrings so that they are
929
- # not encoded.
930
- assert not isinstance(args[0], float)
931
- if isinstance(args[0], str):
932
- args = tuple(args[0].encode().split()) + args[1:]
933
- elif b" " in args[0]:
934
- args = tuple(args[0].split()) + args[1:]
935
-
936
- buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))
937
-
938
- buffer_cutoff = self._buffer_cutoff
939
- for arg in map(self.encoder.encode, args):
940
- # to avoid large string mallocs, chunk the command into the
941
- # output list if we're sending large values or memoryviews
942
- arg_length = len(arg)
943
- if (
944
- len(buff) > buffer_cutoff
945
- or arg_length > buffer_cutoff
946
- or isinstance(arg, memoryview)
947
- ):
948
- buff = SYM_EMPTY.join(
949
- (buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF)
950
- )
951
- output.append(buff)
952
- output.append(arg)
953
- buff = SYM_CRLF
954
- else:
955
- buff = SYM_EMPTY.join(
956
- (
957
- buff,
958
- SYM_DOLLAR,
959
- str(arg_length).encode(),
960
- SYM_CRLF,
961
- arg,
962
- SYM_CRLF,
963
- )
964
- )
965
- output.append(buff)
966
- return output
967
-
968
- def pack_commands(self, commands: Iterable[Iterable[EncodableT]]) -> List[bytes]:
969
- """Pack multiple commands into the Redis protocol"""
970
- output: List[bytes] = []
971
- pieces: List[bytes] = []
972
- buffer_length = 0
973
- buffer_cutoff = self._buffer_cutoff
974
-
975
- for cmd in commands:
976
- for chunk in self.pack_command(*cmd):
977
- chunklen = len(chunk)
978
- if (
979
- buffer_length > buffer_cutoff
980
- or chunklen > buffer_cutoff
981
- or isinstance(chunk, memoryview)
982
- ):
983
- output.append(SYM_EMPTY.join(pieces))
984
- buffer_length = 0
985
- pieces = []
986
-
987
- if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
988
- output.append(chunk)
989
- else:
990
- pieces.append(chunk)
991
- buffer_length += chunklen
992
-
993
- if pieces:
994
- output.append(SYM_EMPTY.join(pieces))
995
- return output
996
-
997
-
998
- class SSLConnection(Connection):
999
- def __init__(
1000
- self,
1001
- ssl_keyfile: Optional[str] = None,
1002
- ssl_certfile: Optional[str] = None,
1003
- ssl_cert_reqs: str = "required",
1004
- ssl_ca_certs: Optional[str] = None,
1005
- ssl_check_hostname: bool = False,
1006
- **kwargs,
1007
- ):
1008
- super().__init__(**kwargs)
1009
- self.ssl_context: RedisSSLContext = RedisSSLContext(
1010
- keyfile=ssl_keyfile,
1011
- certfile=ssl_certfile,
1012
- cert_reqs=ssl_cert_reqs,
1013
- ca_certs=ssl_ca_certs,
1014
- check_hostname=ssl_check_hostname,
1015
- )
1016
-
1017
- @property
1018
- def keyfile(self):
1019
- return self.ssl_context.keyfile
1020
-
1021
- @property
1022
- def certfile(self):
1023
- return self.ssl_context.certfile
1024
-
1025
- @property
1026
- def cert_reqs(self):
1027
- return self.ssl_context.cert_reqs
1028
-
1029
- @property
1030
- def ca_certs(self):
1031
- return self.ssl_context.ca_certs
1032
-
1033
- @property
1034
- def check_hostname(self):
1035
- return self.ssl_context.check_hostname
1036
-
1037
-
1038
- class RedisSSLContext:
1039
- __slots__ = (
1040
- "keyfile",
1041
- "certfile",
1042
- "cert_reqs",
1043
- "ca_certs",
1044
- "context",
1045
- "check_hostname",
1046
- )
1047
-
1048
- def __init__(
1049
- self,
1050
- keyfile: Optional[str] = None,
1051
- certfile: Optional[str] = None,
1052
- cert_reqs: Optional[str] = None,
1053
- ca_certs: Optional[str] = None,
1054
- check_hostname: bool = False,
1055
- ):
1056
- self.keyfile = keyfile
1057
- self.certfile = certfile
1058
- if cert_reqs is None:
1059
- self.cert_reqs = ssl.CERT_NONE
1060
- elif isinstance(cert_reqs, str):
1061
- CERT_REQS = {
1062
- "none": ssl.CERT_NONE,
1063
- "optional": ssl.CERT_OPTIONAL,
1064
- "required": ssl.CERT_REQUIRED,
1065
- }
1066
- if cert_reqs not in CERT_REQS:
1067
- raise RedisError(
1068
- f"Invalid SSL Certificate Requirements Flag: {cert_reqs}"
1069
- )
1070
- self.cert_reqs = CERT_REQS[cert_reqs]
1071
- self.ca_certs = ca_certs
1072
- self.check_hostname = check_hostname
1073
- self.context: Optional[ssl.SSLContext] = None
1074
-
1075
- def get(self) -> ssl.SSLContext:
1076
- if not self.context:
1077
- context = ssl.create_default_context()
1078
- context.check_hostname = self.check_hostname
1079
- context.verify_mode = self.cert_reqs
1080
- if self.certfile and self.keyfile:
1081
- context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
1082
- if self.ca_certs:
1083
- context.load_verify_locations(self.ca_certs)
1084
- self.context = context
1085
- return self.context
1086
-
1087
-
1088
- class UnixDomainSocketConnection(Connection): # lgtm [py/missing-call-to-init]
1089
- def __init__(
1090
- self,
1091
- *,
1092
- path: str = "",
1093
- db: Union[str, int] = 0,
1094
- username: Optional[str] = None,
1095
- password: Optional[str] = None,
1096
- socket_timeout: Optional[float] = None,
1097
- socket_connect_timeout: Optional[float] = None,
1098
- encoding: str = "utf-8",
1099
- encoding_errors: str = "strict",
1100
- decode_responses: bool = False,
1101
- retry_on_timeout: bool = False,
1102
- parser_class: Type[BaseParser] = DefaultParser,
1103
- socket_read_size: int = 65536,
1104
- health_check_interval: float = 0.0,
1105
- client_name=None,
1106
- ):
1107
- self.pid = os.getpid()
1108
- self.path = path
1109
- self.db = db
1110
- self.username = username
1111
- self.client_name = client_name
1112
- self.password = password
1113
- self.socket_timeout = socket_timeout
1114
- self.socket_connect_timeout = socket_connect_timeout or socket_timeout or None
1115
- self.retry_on_timeout = retry_on_timeout
1116
- self.health_check_interval = health_check_interval
1117
- self.next_health_check = -1
1118
- self.encoder = Encoder(encoding, encoding_errors, decode_responses)
1119
- self._sock = None
1120
- self._reader = None
1121
- self._writer = None
1122
- self._parser = parser_class(socket_read_size=socket_read_size)
1123
- self._connect_callbacks = []
1124
- self._buffer_cutoff = 6000
1125
- self._lock = asyncio.Lock()
1126
-
1127
- def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
1128
- pieces = [
1129
- ("path", self.path),
1130
- ("db", self.db),
1131
- ]
1132
- if self.client_name:
1133
- pieces.append(("client_name", self.client_name))
1134
- return pieces
1135
-
1136
- async def _connect(self):
1137
- async with async_timeout.timeout(self.socket_connect_timeout):
1138
- reader, writer = await asyncio.open_unix_connection(path=self.path)
1139
- self._reader = reader
1140
- self._writer = writer
1141
- await self.on_connect()
1142
-
1143
- def _error_message(self, exception):
1144
- # args for socket.error can either be (errno, "message")
1145
- # or just "message"
1146
- if len(exception.args) == 1:
1147
- return f"Error connecting to unix socket: {self.path}. {exception.args[0]}."
1148
- else:
1149
- return (
1150
- f"Error {exception.args[0]} connecting to unix socket: "
1151
- f"{self.path}. {exception.args[1]}."
1152
- )
1153
-
1154
-
1155
- FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO")
1156
-
1157
-
1158
- def to_bool(value) -> Optional[bool]:
1159
- if value is None or value == "":
1160
- return None
1161
- if isinstance(value, str) and value.upper() in FALSE_STRINGS:
1162
- return False
1163
- return bool(value)
1164
-
1165
-
1166
- URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyType(
1167
- {
1168
- "db": int,
1169
- "socket_timeout": float,
1170
- "socket_connect_timeout": float,
1171
- "socket_keepalive": to_bool,
1172
- "retry_on_timeout": to_bool,
1173
- "max_connections": int,
1174
- "health_check_interval": int,
1175
- "ssl_check_hostname": to_bool,
1176
- }
1177
- )
1178
-
1179
-
1180
- class ConnectKwargs(TypedDict, total=False):
1181
- username: str
1182
- password: str
1183
- connection_class: Type[Connection]
1184
- host: str
1185
- port: int
1186
- db: int
1187
- path: str
1188
-
1189
-
1190
- def parse_url(url: str) -> ConnectKwargs:
1191
- parsed: ParseResult = urlparse(url)
1192
- kwargs: ConnectKwargs = {}
1193
-
1194
- for name, value_list in parse_qs(parsed.query).items():
1195
- if value_list and len(value_list) > 0:
1196
- value = unquote(value_list[0])
1197
- parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
1198
- if parser:
1199
- try:
1200
- # We can't type this.
1201
- kwargs[name] = parser(value) # type: ignore[misc]
1202
- except (TypeError, ValueError):
1203
- raise ValueError(f"Invalid value for `{name}` in connection URL.")
1204
- else:
1205
- kwargs[name] = value # type: ignore[misc]
1206
-
1207
- if parsed.username:
1208
- kwargs["username"] = unquote(parsed.username)
1209
- if parsed.password:
1210
- kwargs["password"] = unquote(parsed.password)
1211
-
1212
- # We only support redis://, rediss:// and unix:// schemes.
1213
- if parsed.scheme == "unix":
1214
- if parsed.path:
1215
- kwargs["path"] = unquote(parsed.path)
1216
- kwargs["connection_class"] = UnixDomainSocketConnection
1217
-
1218
- elif parsed.scheme in ("redis", "rediss"):
1219
- if parsed.hostname:
1220
- kwargs["host"] = unquote(parsed.hostname)
1221
- if parsed.port:
1222
- kwargs["port"] = int(parsed.port)
1223
-
1224
- # If there's a path argument, use it as the db argument if a
1225
- # querystring value wasn't specified
1226
- if parsed.path and "db" not in kwargs:
1227
- try:
1228
- kwargs["db"] = int(unquote(parsed.path).replace("/", ""))
1229
- except (AttributeError, ValueError):
1230
- pass
1231
-
1232
- if parsed.scheme == "rediss":
1233
- kwargs["connection_class"] = SSLConnection
1234
- else:
1235
- valid_schemes = "redis://, rediss://, unix://"
1236
- raise ValueError(
1237
- f"Redis URL must specify one of the following schemes ({valid_schemes})"
1238
- )
1239
-
1240
- return kwargs
1241
-
1242
-
1243
- _CP = TypeVar("_CP", bound="ConnectionPool")
1244
-
1245
-
1246
- class ConnectionPool:
1247
- """
1248
- Create a connection pool. ``If max_connections`` is set, then this
1249
- object raises :py:class:`~redis.ConnectionError` when the pool's
1250
- limit is reached.
1251
-
1252
- By default, TCP connections are created unless ``connection_class``
1253
- is specified. Use :py:class:`~redis.UnixDomainSocketConnection` for
1254
- unix sockets.
1255
-
1256
- Any additional keyword arguments are passed to the constructor of
1257
- ``connection_class``.
1258
- """
1259
-
1260
- @classmethod
1261
- def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
1262
- """
1263
- Return a connection pool configured from the given URL.
1264
-
1265
- For example::
1266
-
1267
- redis://[[username]:[password]]@localhost:6379/0
1268
- rediss://[[username]:[password]]@localhost:6379/0
1269
- unix://[[username]:[password]]@/path/to/socket.sock?db=0
1270
-
1271
- Three URL schemes are supported:
1272
-
1273
- - `redis://` creates a TCP socket connection. See more at:
1274
- <https://www.iana.org/assignments/uri-schemes/prov/redis>
1275
- - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
1276
- <https://www.iana.org/assignments/uri-schemes/prov/rediss>
1277
- - ``unix://``: creates a Unix Domain Socket connection.
1278
-
1279
- The username, password, hostname, path and all querystring values
1280
- are passed through urllib.parse.unquote in order to replace any
1281
- percent-encoded values with their corresponding characters.
1282
-
1283
- There are several ways to specify a database number. The first value
1284
- found will be used:
1285
- 1. A ``db`` querystring option, e.g. redis://localhost?db=0
1286
- 2. If using the redis:// or rediss:// schemes, the path argument
1287
- of the url, e.g. redis://localhost/0
1288
- 3. A ``db`` keyword argument to this function.
1289
-
1290
- If none of these options are specified, the default db=0 is used.
1291
-
1292
- All querystring options are cast to their appropriate Python types.
1293
- Boolean arguments can be specified with string values "True"/"False"
1294
- or "Yes"/"No". Values that cannot be properly cast cause a
1295
- ``ValueError`` to be raised. Once parsed, the querystring arguments
1296
- and keyword arguments are passed to the ``ConnectionPool``'s
1297
- class initializer. In the case of conflicting arguments, querystring
1298
- arguments always win.
1299
- """
1300
- url_options = parse_url(url)
1301
- kwargs.update(url_options)
1302
- return cls(**kwargs)
1303
-
1304
- def __init__(
1305
- self,
1306
- connection_class: Type[Connection] = Connection,
1307
- max_connections: Optional[int] = None,
1308
- **connection_kwargs,
1309
- ):
1310
- max_connections = max_connections or 2 ** 31
1311
- if not isinstance(max_connections, int) or max_connections < 0:
1312
- raise ValueError('"max_connections" must be a positive integer')
1313
-
1314
- self.connection_class = connection_class
1315
- self.connection_kwargs = connection_kwargs
1316
- self.max_connections = max_connections
1317
-
1318
- # a lock to protect the critical section in _checkpid().
1319
- # this lock is acquired when the process id changes, such as
1320
- # after a fork. during this time, multiple threads in the child
1321
- # process could attempt to acquire this lock. the first thread
1322
- # to acquire the lock will reset the data structures and lock
1323
- # object of this pool. subsequent threads acquiring this lock
1324
- # will notice the first thread already did the work and simply
1325
- # release the lock.
1326
- self._fork_lock = threading.Lock()
1327
- self._lock = asyncio.Lock()
1328
- self._created_connections: int
1329
- self._available_connections: List[Connection]
1330
- self._in_use_connections: Set[Connection]
1331
- self.reset() # lgtm [py/init-calls-subclass]
1332
- self.encoder_class = self.connection_kwargs.get("encoder_class", Encoder)
1333
-
1334
- def __repr__(self):
1335
- return (
1336
- f"{self.__class__.__name__}"
1337
- f"<{self.connection_class(**self.connection_kwargs)!r}>"
1338
- )
1339
-
1340
- def reset(self):
1341
- self._lock = asyncio.Lock()
1342
- self._created_connections = 0
1343
- self._available_connections = []
1344
- self._in_use_connections = set()
1345
-
1346
- # this must be the last operation in this method. while reset() is
1347
- # called when holding _fork_lock, other threads in this process
1348
- # can call _checkpid() which compares self.pid and os.getpid() without
1349
- # holding any lock (for performance reasons). keeping this assignment
1350
- # as the last operation ensures that those other threads will also
1351
- # notice a pid difference and block waiting for the first thread to
1352
- # release _fork_lock. when each of these threads eventually acquire
1353
- # _fork_lock, they will notice that another thread already called
1354
- # reset() and they will immediately release _fork_lock and continue on.
1355
- self.pid = os.getpid()
1356
-
1357
- def _checkpid(self):
1358
- # _checkpid() attempts to keep ConnectionPool fork-safe on modern
1359
- # systems. this is called by all ConnectionPool methods that
1360
- # manipulate the pool's state such as get_connection() and release().
1361
- #
1362
- # _checkpid() determines whether the process has forked by comparing
1363
- # the current process id to the process id saved on the ConnectionPool
1364
- # instance. if these values are the same, _checkpid() simply returns.
1365
- #
1366
- # when the process ids differ, _checkpid() assumes that the process
1367
- # has forked and that we're now running in the child process. the child
1368
- # process cannot use the parent's file descriptors (e.g., sockets).
1369
- # therefore, when _checkpid() sees the process id change, it calls
1370
- # reset() in order to reinitialize the child's ConnectionPool. this
1371
- # will cause the child to make all new connection objects.
1372
- #
1373
- # _checkpid() is protected by self._fork_lock to ensure that multiple
1374
- # threads in the child process do not call reset() multiple times.
1375
- #
1376
- # there is an extremely small chance this could fail in the following
1377
- # scenario:
1378
- # 1. process A calls _checkpid() for the first time and acquires
1379
- # self._fork_lock.
1380
- # 2. while holding self._fork_lock, process A forks (the fork()
1381
- # could happen in a different thread owned by process A)
1382
- # 3. process B (the forked child process) inherits the
1383
- # ConnectionPool's state from the parent. that state includes
1384
- # a locked _fork_lock. process B will not be notified when
1385
- # process A releases the _fork_lock and will thus never be
1386
- # able to acquire the _fork_lock.
1387
- #
1388
- # to mitigate this possible deadlock, _checkpid() will only wait 5
1389
- # seconds to acquire _fork_lock. if _fork_lock cannot be acquired in
1390
- # that time it is assumed that the child is deadlocked and a
1391
- # redis.ChildDeadlockedError error is raised.
1392
- if self.pid != os.getpid():
1393
- acquired = self._fork_lock.acquire(timeout=5)
1394
- if not acquired:
1395
- raise ChildDeadlockedError
1396
- # reset() the instance for the new process if another thread
1397
- # hasn't already done so
1398
- try:
1399
- if self.pid != os.getpid():
1400
- self.reset()
1401
- finally:
1402
- self._fork_lock.release()
1403
-
1404
- async def get_connection(self, command_name, *keys, **options):
1405
- """Get a connection from the pool"""
1406
- self._checkpid()
1407
- async with self._lock:
1408
- try:
1409
- connection = self._available_connections.pop()
1410
- except IndexError:
1411
- connection = self.make_connection()
1412
- self._in_use_connections.add(connection)
1413
-
1414
- try:
1415
- # ensure this connection is connected to Redis
1416
- await connection.connect()
1417
- # connections that the pool provides should be ready to send
1418
- # a command. if not, the connection was either returned to the
1419
- # pool before all data has been read or the socket has been
1420
- # closed. either way, reconnect and verify everything is good.
1421
- try:
1422
- if await connection.can_read():
1423
- raise ConnectionError("Connection has data") from None
1424
- except ConnectionError:
1425
- await connection.disconnect()
1426
- await connection.connect()
1427
- if await connection.can_read():
1428
- raise ConnectionError("Connection not ready") from None
1429
- except BaseException:
1430
- # release the connection back to the pool so that we don't
1431
- # leak it
1432
- await self.release(connection)
1433
- raise
1434
-
1435
- return connection
1436
-
1437
- def get_encoder(self):
1438
- """Return an encoder based on encoding settings"""
1439
- kwargs = self.connection_kwargs
1440
- return self.encoder_class(
1441
- encoding=kwargs.get("encoding", "utf-8"),
1442
- encoding_errors=kwargs.get("encoding_errors", "strict"),
1443
- decode_responses=kwargs.get("decode_responses", False),
1444
- )
1445
-
1446
- def make_connection(self):
1447
- """Create a new connection"""
1448
- if self._created_connections >= self.max_connections:
1449
- raise ConnectionError("Too many connections")
1450
- self._created_connections += 1
1451
- return self.connection_class(**self.connection_kwargs)
1452
-
1453
- async def release(self, connection: Connection):
1454
- """Releases the connection back to the pool"""
1455
- self._checkpid()
1456
- async with self._lock:
1457
- try:
1458
- self._in_use_connections.remove(connection)
1459
- except KeyError:
1460
- # Gracefully fail when a connection is returned to this pool
1461
- # that the pool doesn't actually own
1462
- pass
1463
-
1464
- if self.owns_connection(connection):
1465
- self._available_connections.append(connection)
1466
- else:
1467
- # pool doesn't own this connection. do not add it back
1468
- # to the pool and decrement the count so that another
1469
- # connection can take its place if needed
1470
- self._created_connections -= 1
1471
- await connection.disconnect()
1472
- return
1473
-
1474
- def owns_connection(self, connection: Connection):
1475
- return connection.pid == self.pid
1476
-
1477
- async def disconnect(self, inuse_connections: bool = True):
1478
- """
1479
- Disconnects connections in the pool
1480
-
1481
- If ``inuse_connections`` is True, disconnect connections that are
1482
- current in use, potentially by other tasks. Otherwise only disconnect
1483
- connections that are idle in the pool.
1484
- """
1485
- self._checkpid()
1486
- async with self._lock:
1487
- if inuse_connections:
1488
- connections: Iterable[Connection] = chain(
1489
- self._available_connections, self._in_use_connections
1490
- )
1491
- else:
1492
- connections = self._available_connections
1493
- resp = await asyncio.gather(
1494
- *(connection.disconnect() for connection in connections),
1495
- return_exceptions=True,
1496
- )
1497
- exc = next((r for r in resp if isinstance(r, BaseException)), None)
1498
- if exc:
1499
- raise exc
1500
-
1501
-
1502
- class BlockingConnectionPool(ConnectionPool):
1503
- """
1504
- Thread-safe blocking connection pool::
1505
-
1506
- >>> from aioredis.client import Redis
1507
- >>> client = Redis(connection_pool=BlockingConnectionPool())
1508
-
1509
- It performs the same function as the default
1510
- :py:class:`~redis.ConnectionPool` implementation, in that,
1511
- it maintains a pool of reusable connections that can be shared by
1512
- multiple redis clients (safely across threads if required).
1513
-
1514
- The difference is that, in the event that a client tries to get a
1515
- connection from the pool when all of connections are in use, rather than
1516
- raising a :py:class:`~redis.ConnectionError` (as the default
1517
- :py:class:`~redis.ConnectionPool` implementation does), it
1518
- makes the client wait ("blocks") for a specified number of seconds until
1519
- a connection becomes available.
1520
-
1521
- Use ``max_connections`` to increase / decrease the pool size::
1522
-
1523
- >>> pool = BlockingConnectionPool(max_connections=10)
1524
-
1525
- Use ``timeout`` to tell it either how many seconds to wait for a connection
1526
- to become available, or to block forever:
1527
-
1528
- >>> # Block forever.
1529
- >>> pool = BlockingConnectionPool(timeout=None)
1530
-
1531
- >>> # Raise a ``ConnectionError`` after five seconds if a connection is
1532
- >>> # not available.
1533
- >>> pool = BlockingConnectionPool(timeout=5)
1534
- """
1535
-
1536
- def __init__(
1537
- self,
1538
- max_connections: int = 50,
1539
- timeout: Optional[int] = 20,
1540
- connection_class: Type[Connection] = Connection,
1541
- queue_class: Type[asyncio.Queue] = asyncio.LifoQueue,
1542
- **connection_kwargs,
1543
- ):
1544
-
1545
- self.queue_class = queue_class
1546
- self.timeout = timeout
1547
- self._connections: List[Connection]
1548
- super().__init__(
1549
- connection_class=connection_class,
1550
- max_connections=max_connections,
1551
- **connection_kwargs,
1552
- )
1553
-
1554
- def reset(self):
1555
- # Create and fill up a thread safe queue with ``None`` values.
1556
- self.pool = self.queue_class(self.max_connections)
1557
- while True:
1558
- try:
1559
- self.pool.put_nowait(None)
1560
- except asyncio.QueueFull:
1561
- break
1562
-
1563
- # Keep a list of actual connection instances so that we can
1564
- # disconnect them later.
1565
- self._connections = []
1566
-
1567
- # this must be the last operation in this method. while reset() is
1568
- # called when holding _fork_lock, other threads in this process
1569
- # can call _checkpid() which compares self.pid and os.getpid() without
1570
- # holding any lock (for performance reasons). keeping this assignment
1571
- # as the last operation ensures that those other threads will also
1572
- # notice a pid difference and block waiting for the first thread to
1573
- # release _fork_lock. when each of these threads eventually acquire
1574
- # _fork_lock, they will notice that another thread already called
1575
- # reset() and they will immediately release _fork_lock and continue on.
1576
- self.pid = os.getpid()
1577
-
1578
- def make_connection(self):
1579
- """Make a fresh connection."""
1580
- connection = self.connection_class(**self.connection_kwargs)
1581
- self._connections.append(connection)
1582
- return connection
1583
-
1584
- async def get_connection(self, command_name, *keys, **options):
1585
- """
1586
- Get a connection, blocking for ``self.timeout`` until a connection
1587
- is available from the pool.
1588
-
1589
- If the connection returned is ``None`` then creates a new connection.
1590
- Because we use a last-in first-out queue, the existing connections
1591
- (having been returned to the pool after the initial ``None`` values
1592
- were added) will be returned before ``None`` values. This means we only
1593
- create new connections when we need to, i.e.: the actual number of
1594
- connections will only increase in response to demand.
1595
- """
1596
- # Make sure we haven't changed process.
1597
- self._checkpid()
1598
-
1599
- # Try and get a connection from the pool. If one isn't available within
1600
- # self.timeout then raise a ``ConnectionError``.
1601
- connection = None
1602
- try:
1603
- async with async_timeout.timeout(self.timeout):
1604
- connection = await self.pool.get()
1605
- except (asyncio.QueueEmpty, asyncio.TimeoutError):
1606
- # Note that this is not caught by the redis client and will be
1607
- # raised unless handled by application code. If you want never to
1608
- raise ConnectionError("No connection available.")
1609
-
1610
- # If the ``connection`` is actually ``None`` then that's a cue to make
1611
- # a new connection to add to the pool.
1612
- if connection is None:
1613
- connection = self.make_connection()
1614
-
1615
- try:
1616
- # ensure this connection is connected to Redis
1617
- await connection.connect()
1618
- # connections that the pool provides should be ready to send
1619
- # a command. if not, the connection was either returned to the
1620
- # pool before all data has been read or the socket has been
1621
- # closed. either way, reconnect and verify everything is good.
1622
- try:
1623
- if await connection.can_read():
1624
- raise ConnectionError("Connection has data") from None
1625
- except ConnectionError:
1626
- await connection.disconnect()
1627
- await connection.connect()
1628
- if await connection.can_read():
1629
- raise ConnectionError("Connection not ready") from None
1630
- except BaseException:
1631
- # release the connection back to the pool so that we don't leak it
1632
- await self.release(connection)
1633
- raise
1634
-
1635
- return connection
1636
-
1637
- async def release(self, connection: Connection):
1638
- """Releases the connection back to the pool."""
1639
- # Make sure we haven't changed process.
1640
- self._checkpid()
1641
- if not self.owns_connection(connection):
1642
- # pool doesn't own this connection. do not add it back
1643
- # to the pool. instead add a None value which is a placeholder
1644
- # that will cause the pool to recreate the connection if
1645
- # its needed.
1646
- await connection.disconnect()
1647
- self.pool.put_nowait(None)
1648
- return
1649
-
1650
- # Put the connection back into the pool.
1651
- try:
1652
- self.pool.put_nowait(connection)
1653
- except asyncio.QueueFull:
1654
- # perhaps the pool has been reset() after a fork? regardless,
1655
- # we don't want this connection
1656
- pass
1657
-
1658
- async def disconnect(self, inuse_connections: bool = True):
1659
- """Disconnects all connections in the pool."""
1660
- self._checkpid()
1661
- async with self._lock:
1662
- resp = await asyncio.gather(
1663
- *(connection.disconnect() for connection in self._connections),
1664
- return_exceptions=True,
1665
- )
1666
- exc = next((r for r in resp if isinstance(r, BaseException)), None)
1667
- if exc:
1668
- raise exc
1
+ import asyncio
2
+ import enum
3
+ import errno
4
+ import inspect
5
+ import io
6
+ import os
7
+ import socket
8
+ import ssl
9
+ import threading
10
+ import warnings
11
+ from distutils.version import StrictVersion
12
+ from itertools import chain
13
+ from types import MappingProxyType
14
+ from typing import (
15
+ Any,
16
+ Callable,
17
+ Iterable,
18
+ List,
19
+ Mapping,
20
+ Optional,
21
+ Set,
22
+ Tuple,
23
+ Type,
24
+ TypeVar,
25
+ Union,
26
+ cast,
27
+ )
28
+ from urllib.parse import ParseResult, parse_qs, unquote, urlparse
29
+
30
+ import async_timeout
31
+
32
+ from .compat import Protocol, TypedDict
33
+ from .exceptions import (
34
+ AuthenticationError,
35
+ AuthenticationWrongNumberOfArgsError,
36
+ BusyLoadingError,
37
+ ChildDeadlockedError,
38
+ ConnectionError,
39
+ DataError,
40
+ ExecAbortError,
41
+ InvalidResponse,
42
+ ModuleError,
43
+ NoPermissionError,
44
+ NoScriptError,
45
+ ReadOnlyError,
46
+ RedisError,
47
+ ResponseError,
48
+ TimeoutError,
49
+ )
50
+ from .utils import str_if_bytes
51
+
52
+ NONBLOCKING_EXCEPTION_ERROR_NUMBERS = {
53
+ BlockingIOError: errno.EWOULDBLOCK,
54
+ ssl.SSLWantReadError: 2,
55
+ ssl.SSLWantWriteError: 2,
56
+ ssl.SSLError: 2,
57
+ }
58
+
59
+ NONBLOCKING_EXCEPTIONS = tuple(NONBLOCKING_EXCEPTION_ERROR_NUMBERS.keys())
60
+
61
+ try:
62
+ import hiredis
63
+
64
+ except (ImportError, ModuleNotFoundError):
65
+ HIREDIS_AVAILABLE = False
66
+ else:
67
+ HIREDIS_AVAILABLE = True
68
+ hiredis_version = StrictVersion(hiredis.__version__)
69
+ if hiredis_version < StrictVersion("1.0.0"):
70
+ warnings.warn(
71
+ "aioredis supports hiredis @ 1.0.0 or higher. "
72
+ f"You have hiredis @ {hiredis.__version__}. "
73
+ "Pure-python parser will be used instead."
74
+ )
75
+ HIREDIS_AVAILABLE = False
76
+
77
+ SYM_STAR = b"*"
78
+ SYM_DOLLAR = b"$"
79
+ SYM_CRLF = b"\r\n"
80
+ SYM_LF = b"\n"
81
+ SYM_EMPTY = b""
82
+
83
+ SERVER_CLOSED_CONNECTION_ERROR = "Connection closed by server."
84
+
85
+
86
+ class _Sentinel(enum.Enum):
87
+ sentinel = object()
88
+
89
+
90
+ SENTINEL = _Sentinel.sentinel
91
+ MODULE_LOAD_ERROR = "Error loading the extension. Please check the server logs."
92
+ NO_SUCH_MODULE_ERROR = "Error unloading module: no such module with that name"
93
+ MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not possible."
94
+ MODULE_EXPORTS_DATA_TYPES_ERROR = (
95
+ "Error unloading module: the module "
96
+ "exports one or more module-side data "
97
+ "types, can't unload"
98
+ )
99
+
100
+ EncodedT = Union[bytes, memoryview]
101
+ DecodedT = Union[str, int, float]
102
+ EncodableT = Union[EncodedT, DecodedT]
103
+
104
+
105
+ class _HiredisReaderArgs(TypedDict, total=False):
106
+ protocolError: Callable[[str], Exception]
107
+ replyError: Callable[[str], Exception]
108
+ encoding: Optional[str]
109
+ errors: Optional[str]
110
+
111
+
112
+ class Encoder:
113
+ """Encode strings to bytes-like and decode bytes-like to strings"""
114
+
115
+ __slots__ = "encoding", "encoding_errors", "decode_responses"
116
+
117
+ def __init__(self, encoding: str, encoding_errors: str, decode_responses: bool):
118
+ self.encoding = encoding
119
+ self.encoding_errors = encoding_errors
120
+ self.decode_responses = decode_responses
121
+
122
+ def encode(self, value: EncodableT) -> EncodedT:
123
+ """Return a bytestring or bytes-like representation of the value"""
124
+ if isinstance(value, (bytes, memoryview)):
125
+ return value
126
+ if isinstance(value, bool):
127
+ # special case bool since it is a subclass of int
128
+ raise DataError(
129
+ "Invalid input of type: 'bool'. "
130
+ "Convert to a bytes, string, int or float first."
131
+ )
132
+ if isinstance(value, (int, float)):
133
+ return repr(value).encode()
134
+ if not isinstance(value, str):
135
+ # a value we don't know how to deal with. throw an error
136
+ typename = value.__class__.__name__ # type: ignore[unreachable]
137
+ raise DataError(
138
+ f"Invalid input of type: {typename!r}. "
139
+ "Convert to a bytes, string, int or float first."
140
+ )
141
+ return value.encode(self.encoding, self.encoding_errors)
142
+
143
+ def decode(self, value: EncodableT, force=False) -> EncodableT:
144
+ """Return a unicode string from the bytes-like representation"""
145
+ if self.decode_responses or force:
146
+ if isinstance(value, memoryview):
147
+ return value.tobytes().decode(self.encoding, self.encoding_errors)
148
+ if isinstance(value, bytes):
149
+ return value.decode(self.encoding, self.encoding_errors)
150
+ return value
151
+
152
+
153
+ ExceptionMappingT = Mapping[str, Union[Type[Exception], Mapping[str, Type[Exception]]]]
154
+
155
+
156
+ class BaseParser:
157
+ """Plain Python parsing class"""
158
+
159
+ __slots__ = "_stream", "_buffer", "_read_size"
160
+
161
+ EXCEPTION_CLASSES: ExceptionMappingT = {
162
+ "ERR": {
163
+ "max number of clients reached": ConnectionError,
164
+ "Client sent AUTH, but no password is set": AuthenticationError,
165
+ "invalid password": AuthenticationError,
166
+ # some Redis server versions report invalid command syntax
167
+ # in lowercase
168
+ "wrong number of arguments for 'auth' command": AuthenticationWrongNumberOfArgsError,
169
+ # some Redis server versions report invalid command syntax
170
+ # in uppercase
171
+ "wrong number of arguments for 'AUTH' command": AuthenticationWrongNumberOfArgsError,
172
+ MODULE_LOAD_ERROR: ModuleError,
173
+ MODULE_EXPORTS_DATA_TYPES_ERROR: ModuleError,
174
+ NO_SUCH_MODULE_ERROR: ModuleError,
175
+ MODULE_UNLOAD_NOT_POSSIBLE_ERROR: ModuleError,
176
+ },
177
+ "EXECABORT": ExecAbortError,
178
+ "LOADING": BusyLoadingError,
179
+ "NOSCRIPT": NoScriptError,
180
+ "READONLY": ReadOnlyError,
181
+ "NOAUTH": AuthenticationError,
182
+ "NOPERM": NoPermissionError,
183
+ }
184
+
185
+ def __init__(self, socket_read_size: int):
186
+ self._stream: Optional[asyncio.StreamReader] = None
187
+ self._buffer: Optional[SocketBuffer] = None
188
+ self._read_size = socket_read_size
189
+
190
+ def __del__(self):
191
+ try:
192
+ self.on_disconnect()
193
+ except BaseException :
194
+ pass
195
+
196
+ def parse_error(self, response: str) -> ResponseError:
197
+ """Parse an error response"""
198
+ error_code = response.split(" ")[0]
199
+ if error_code in self.EXCEPTION_CLASSES:
200
+ response = response[len(error_code) + 1 :]
201
+ exception_class_or_dict = self.EXCEPTION_CLASSES[error_code]
202
+ if isinstance(exception_class_or_dict, dict):
203
+ exception_class = exception_class_or_dict.get(response, ResponseError)
204
+ else:
205
+ exception_class = exception_class_or_dict
206
+ return exception_class(response)
207
+ return ResponseError(response)
208
+
209
+ def on_disconnect(self):
210
+ raise NotImplementedError()
211
+
212
+ def on_connect(self, connection: "Connection"):
213
+ raise NotImplementedError()
214
+
215
+ async def can_read(self, timeout: float) -> bool:
216
+ raise NotImplementedError()
217
+
218
+ async def read_response(
219
+ self,
220
+ ) -> Union[EncodableT, ResponseError, None, List[EncodableT]]:
221
+ raise NotImplementedError()
222
+
223
+
224
+ class SocketBuffer:
225
+ """Async-friendly re-impl of redis-py's SocketBuffer.
226
+
227
+ TODO: We're currently passing through two buffers,
228
+ the asyncio.StreamReader and this. I imagine we can reduce the layers here
229
+ while maintaining compliance with prior art.
230
+ """
231
+
232
+ def __init__(
233
+ self,
234
+ stream_reader: asyncio.StreamReader,
235
+ socket_read_size: int,
236
+ socket_timeout: Optional[float],
237
+ ):
238
+ self._stream: Optional[asyncio.StreamReader] = stream_reader
239
+ self.socket_read_size = socket_read_size
240
+ self.socket_timeout = socket_timeout
241
+ self._buffer: Optional[io.BytesIO] = io.BytesIO()
242
+ # number of bytes written to the buffer from the socket
243
+ self.bytes_written = 0
244
+ # number of bytes read from the buffer
245
+ self.bytes_read = 0
246
+
247
+ @property
248
+ def length(self):
249
+ return self.bytes_written - self.bytes_read
250
+
251
+ async def _read_from_socket(
252
+ self,
253
+ length: Optional[int] = None,
254
+ timeout: Union[float, None, _Sentinel] = SENTINEL,
255
+ raise_on_timeout: bool = True,
256
+ ) -> bool:
257
+ buf = self._buffer
258
+ if buf is None or self._stream is None:
259
+ raise RedisError("Buffer is closed.")
260
+ buf.seek(self.bytes_written)
261
+ marker = 0
262
+ timeout = timeout if timeout is not SENTINEL else self.socket_timeout
263
+
264
+ try:
265
+ while True:
266
+ async with async_timeout.timeout(timeout):
267
+ data = await self._stream.read(self.socket_read_size)
268
+ # an empty string indicates the server shutdown the socket
269
+ if isinstance(data, bytes) and len(data) == 0:
270
+ raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
271
+ buf.write(data)
272
+ data_length = len(data)
273
+ self.bytes_written += data_length
274
+ marker += data_length
275
+
276
+ if length is not None and length > marker:
277
+ continue
278
+ return True
279
+ except (socket.timeout, asyncio.TimeoutError):
280
+ if raise_on_timeout:
281
+ raise TimeoutError("Timeout reading from socket")
282
+ return False
283
+ except NONBLOCKING_EXCEPTIONS as ex:
284
+ # if we're in nonblocking mode and the recv raises a
285
+ # blocking error, simply return False indicating that
286
+ # there's no data to be read. otherwise raise the
287
+ # original exception.
288
+ allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
289
+ if not raise_on_timeout and ex.errno == allowed:
290
+ return False
291
+ raise ConnectionError(f"Error while reading from socket: {ex.args}")
292
+
293
+ async def can_read(self, timeout: float) -> bool:
294
+ return bool(self.length) or await self._read_from_socket(
295
+ timeout=timeout, raise_on_timeout=False
296
+ )
297
+
298
+ async def read(self, length: int) -> bytes:
299
+ length = length + 2 # make sure to read the \r\n terminator
300
+ # make sure we've read enough data from the socket
301
+ if length > self.length:
302
+ await self._read_from_socket(length - self.length)
303
+
304
+ if self._buffer is None:
305
+ raise RedisError("Buffer is closed.")
306
+
307
+ self._buffer.seek(self.bytes_read)
308
+ data = self._buffer.read(length)
309
+ self.bytes_read += len(data)
310
+
311
+ # purge the buffer when we've consumed it all so it doesn't
312
+ # grow forever
313
+ if self.bytes_read == self.bytes_written:
314
+ self.purge()
315
+
316
+ return data[:-2]
317
+
318
+ async def readline(self) -> bytes:
319
+ buf = self._buffer
320
+ if buf is None:
321
+ raise RedisError("Buffer is closed.")
322
+
323
+ buf.seek(self.bytes_read)
324
+ data = buf.readline()
325
+ while not data.endswith(SYM_CRLF):
326
+ # there's more data in the socket that we need
327
+ await self._read_from_socket()
328
+ buf.seek(self.bytes_read)
329
+ data = buf.readline()
330
+
331
+ self.bytes_read += len(data)
332
+
333
+ # purge the buffer when we've consumed it all so it doesn't
334
+ # grow forever
335
+ if self.bytes_read == self.bytes_written:
336
+ self.purge()
337
+
338
+ return data[:-2]
339
+
340
+ def purge(self):
341
+ if self._buffer is None:
342
+ raise RedisError("Buffer is closed.")
343
+
344
+ self._buffer.seek(0)
345
+ self._buffer.truncate()
346
+ self.bytes_written = 0
347
+ self.bytes_read = 0
348
+
349
+ def close(self):
350
+ try:
351
+ self.purge()
352
+ self._buffer.close() # type: ignore[union-attr]
353
+ except BaseException :
354
+ # issue #633 suggests the purge/close somehow raised a
355
+ # BadFileDescriptor error. Perhaps the client ran out of
356
+ # memory or something else? It's probably OK to ignore
357
+ # any error being raised from purge/close since we're
358
+ # removing the reference to the instance below.
359
+ pass
360
+ self._buffer = None
361
+ self._stream = None
362
+
363
+
364
+ class PythonParser(BaseParser):
365
+ """Plain Python parsing class"""
366
+
367
+ __slots__ = BaseParser.__slots__ + ("encoder",)
368
+
369
+ def __init__(self, socket_read_size: int):
370
+ super().__init__(socket_read_size)
371
+ self.encoder: Optional[Encoder] = None
372
+
373
+ def on_connect(self, connection: "Connection"):
374
+ """Called when the stream connects"""
375
+ self._stream = connection._reader
376
+ if self._stream is None:
377
+ raise RedisError("Buffer is closed.")
378
+
379
+ self._buffer = SocketBuffer(
380
+ self._stream, self._read_size, connection.socket_timeout
381
+ )
382
+ self.encoder = connection.encoder
383
+
384
+ def on_disconnect(self):
385
+ """Called when the stream disconnects"""
386
+ if self._stream is not None:
387
+ self._stream = None
388
+ if self._buffer is not None:
389
+ self._buffer.close()
390
+ self._buffer = None
391
+ self.encoder = None
392
+
393
+ async def can_read(self, timeout: float):
394
+ return self._buffer and bool(await self._buffer.can_read(timeout))
395
+
396
+ async def read_response(self) -> Union[EncodableT, ResponseError, None]:
397
+ if not self._buffer or not self.encoder:
398
+ raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
399
+ raw = await self._buffer.readline()
400
+ if not raw:
401
+ raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
402
+ response: Any
403
+ byte, response = raw[:1], raw[1:]
404
+
405
+ if byte not in (b"-", b"+", b":", b"$", b"*"):
406
+ raise InvalidResponse(f"Protocol Error: {raw!r}")
407
+
408
+ # server returned an error
409
+ if byte == b"-":
410
+ response = response.decode("utf-8", errors="replace")
411
+ error = self.parse_error(response)
412
+ # if the error is a ConnectionError, raise immediately so the user
413
+ # is notified
414
+ if isinstance(error, ConnectionError):
415
+ raise error
416
+ # otherwise, we're dealing with a ResponseError that might belong
417
+ # inside a pipeline response. the connection's read_response()
418
+ # and/or the pipeline's execute() will raise this error if
419
+ # necessary, so just return the exception instance here.
420
+ return error
421
+ # single value
422
+ elif byte == b"+":
423
+ pass
424
+ # int value
425
+ elif byte == b":":
426
+ response = int(response)
427
+ # bulk response
428
+ elif byte == b"$":
429
+ length = int(response)
430
+ if length == -1:
431
+ return None
432
+ response = await self._buffer.read(length)
433
+ # multi-bulk response
434
+ elif byte == b"*":
435
+ length = int(response)
436
+ if length == -1:
437
+ return None
438
+ response = [(await self.read_response()) for _ in range(length)]
439
+ if isinstance(response, bytes):
440
+ response = self.encoder.decode(response)
441
+ return response
442
+
443
+
444
+ class HiredisParser(BaseParser):
445
+ """Parser class for connections using Hiredis"""
446
+
447
+ __slots__ = BaseParser.__slots__ + ("_next_response", "_reader", "_socket_timeout")
448
+
449
+ _next_response: bool
450
+
451
+ def __init__(self, socket_read_size: int):
452
+ if not HIREDIS_AVAILABLE:
453
+ raise RedisError("Hiredis is not available.")
454
+ super().__init__(socket_read_size=socket_read_size)
455
+ self._reader: Optional[hiredis.Reader] = None
456
+ self._socket_timeout: Optional[float] = None
457
+
458
+ def on_connect(self, connection: "Connection"):
459
+ self._stream = connection._reader
460
+ kwargs: _HiredisReaderArgs = {
461
+ "protocolError": InvalidResponse,
462
+ "replyError": self.parse_error,
463
+ }
464
+ if connection.encoder.decode_responses:
465
+ kwargs["encoding"] = connection.encoder.encoding
466
+ kwargs["errors"] = connection.encoder.encoding_errors
467
+
468
+ self._reader = hiredis.Reader(**kwargs)
469
+ self._next_response = False
470
+ self._socket_timeout = connection.socket_timeout
471
+
472
+ def on_disconnect(self):
473
+ self._stream = None
474
+ self._reader = None
475
+ self._next_response = False
476
+
477
+ async def can_read(self, timeout: float):
478
+ if not self._reader:
479
+ raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
480
+
481
+ if self._next_response is False:
482
+ self._next_response = self._reader.gets()
483
+ if self._next_response is False:
484
+ return await self.read_from_socket(timeout=timeout, raise_on_timeout=False)
485
+ return True
486
+
487
+ async def read_from_socket(
488
+ self,
489
+ timeout: Union[float, None, _Sentinel] = SENTINEL,
490
+ raise_on_timeout: bool = True,
491
+ ):
492
+ if self._stream is None or self._reader is None:
493
+ raise RedisError("Parser already closed.")
494
+
495
+ timeout = self._socket_timeout if timeout is SENTINEL else timeout
496
+ try:
497
+ async with async_timeout.timeout(timeout):
498
+ buffer = await self._stream.read(self._read_size)
499
+ if not isinstance(buffer, bytes) or len(buffer) == 0:
500
+ raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
501
+ self._reader.feed(buffer)
502
+ # data was read from the socket and added to the buffer.
503
+ # return True to indicate that data was read.
504
+ return True
505
+ except asyncio.CancelledError:
506
+ raise
507
+ except (socket.timeout, asyncio.TimeoutError):
508
+ if raise_on_timeout:
509
+ raise TimeoutError("Timeout reading from socket") from None
510
+ return False
511
+ except NONBLOCKING_EXCEPTIONS as ex:
512
+ # if we're in nonblocking mode and the recv raises a
513
+ # blocking error, simply return False indicating that
514
+ # there's no data to be read. otherwise raise the
515
+ # original exception.
516
+ allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
517
+ if not raise_on_timeout and ex.errno == allowed:
518
+ return False
519
+ raise ConnectionError(f"Error while reading from socket: {ex.args}")
520
+
521
+ async def read_response(self) -> Union[EncodableT, List[EncodableT]]:
522
+ if not self._stream or not self._reader:
523
+ self.on_disconnect()
524
+ raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
525
+
526
+ response: Union[
527
+ EncodableT, ConnectionError, List[Union[EncodableT, ConnectionError]]
528
+ ]
529
+ # _next_response might be cached from a can_read() call
530
+ if self._next_response is not False:
531
+ response = self._next_response
532
+ self._next_response = False
533
+ return response
534
+
535
+ response = self._reader.gets()
536
+ while response is False:
537
+ await self.read_from_socket()
538
+ response = self._reader.gets()
539
+
540
+ # if the response is a ConnectionError or the response is a list and
541
+ # the first item is a ConnectionError, raise it as something bad
542
+ # happened
543
+ if isinstance(response, ConnectionError):
544
+ raise response
545
+ elif (
546
+ isinstance(response, list)
547
+ and response
548
+ and isinstance(response[0], ConnectionError)
549
+ ):
550
+ raise response[0]
551
+ # cast as there won't be a ConnectionError here.
552
+ return cast(Union[EncodableT, List[EncodableT]], response)
553
+
554
+
555
+ DefaultParser: Type[Union[PythonParser, HiredisParser]]
556
+ if HIREDIS_AVAILABLE:
557
+ DefaultParser = HiredisParser
558
+ else:
559
+ DefaultParser = PythonParser
560
+
561
+
562
+ class ConnectCallbackProtocol(Protocol):
563
+ def __call__(self, connection: "Connection"):
564
+ ...
565
+
566
+
567
+ class AsyncConnectCallbackProtocol(Protocol):
568
+ async def __call__(self, connection: "Connection"):
569
+ ...
570
+
571
+
572
+ ConnectCallbackT = Union[ConnectCallbackProtocol, AsyncConnectCallbackProtocol]
573
+
574
+
575
+ class Connection:
576
+ """Manages TCP communication to and from a Redis server"""
577
+
578
+ __slots__ = (
579
+ "pid",
580
+ "host",
581
+ "port",
582
+ "db",
583
+ "username",
584
+ "client_name",
585
+ "password",
586
+ "socket_timeout",
587
+ "socket_connect_timeout",
588
+ "socket_keepalive",
589
+ "socket_keepalive_options",
590
+ "socket_type",
591
+ "retry_on_timeout",
592
+ "health_check_interval",
593
+ "next_health_check",
594
+ "last_active_at",
595
+ "encoder",
596
+ "ssl_context",
597
+ "_reader",
598
+ "_writer",
599
+ "_parser",
600
+ "_connect_callbacks",
601
+ "_buffer_cutoff",
602
+ "_lock",
603
+ "__dict__",
604
+ )
605
+
606
+ def __init__(
607
+ self,
608
+ *,
609
+ host: str = "localhost",
610
+ port: Union[str, int] = 6379,
611
+ db: Union[str, int] = 0,
612
+ password: Optional[str] = None,
613
+ socket_timeout: Optional[float] = None,
614
+ socket_connect_timeout: Optional[float] = None,
615
+ socket_keepalive: bool = False,
616
+ socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
617
+ socket_type: int = 0,
618
+ retry_on_timeout: bool = False,
619
+ encoding: str = "utf-8",
620
+ encoding_errors: str = "strict",
621
+ decode_responses: bool = False,
622
+ parser_class: Type[BaseParser] = DefaultParser,
623
+ socket_read_size: int = 65536,
624
+ health_check_interval: float = 0,
625
+ client_name: Optional[str] = None,
626
+ username: Optional[str] = None,
627
+ encoder_class: Type[Encoder] = Encoder,
628
+ ):
629
+ self.pid = os.getpid()
630
+ self.host = host
631
+ self.port = int(port)
632
+ self.db = db
633
+ self.username = username
634
+ self.client_name = client_name
635
+ self.password = password
636
+ self.socket_timeout = socket_timeout
637
+ self.socket_connect_timeout = socket_connect_timeout or socket_timeout or None
638
+ self.socket_keepalive = socket_keepalive
639
+ self.socket_keepalive_options = socket_keepalive_options or {}
640
+ self.socket_type = socket_type
641
+ self.retry_on_timeout = retry_on_timeout
642
+ self.health_check_interval = health_check_interval
643
+ self.next_health_check: float = -1
644
+ self.ssl_context: Optional[RedisSSLContext] = None
645
+ self.encoder = encoder_class(encoding, encoding_errors, decode_responses)
646
+ self._reader: Optional[asyncio.StreamReader] = None
647
+ self._writer: Optional[asyncio.StreamWriter] = None
648
+ self._parser = parser_class(
649
+ socket_read_size=socket_read_size,
650
+ )
651
+ self._connect_callbacks: List[ConnectCallbackT] = []
652
+ self._buffer_cutoff = 6000
653
+ self._lock = asyncio.Lock()
654
+
655
+ def __repr__(self):
656
+ repr_args = ",".join((f"{k}={v}" for k, v in self.repr_pieces()))
657
+ return f"{self.__class__.__name__}<{repr_args}>"
658
+
659
+ def repr_pieces(self):
660
+ pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
661
+ if self.client_name:
662
+ pieces.append(("client_name", self.client_name))
663
+ return pieces
664
+
665
+ def __del__(self):
666
+ try:
667
+ if self.is_connected:
668
+ loop = asyncio.get_event_loop()
669
+ coro = self.disconnect()
670
+ if loop.is_running():
671
+ loop.create_task(coro)
672
+ else:
673
+ loop.run_until_complete(coro)
674
+ except BaseException :
675
+ pass
676
+
677
+ @property
678
+ def is_connected(self):
679
+ return bool(self._reader and self._writer)
680
+
681
+ def register_connect_callback(self, callback):
682
+ self._connect_callbacks.append(callback)
683
+
684
+ def clear_connect_callbacks(self):
685
+ self._connect_callbacks = []
686
+
687
+ async def connect(self):
688
+ """Connects to the Redis server if not already connected"""
689
+ if self.is_connected:
690
+ return
691
+ try:
692
+ await self._connect()
693
+ except asyncio.CancelledError:
694
+ raise
695
+ except (socket.timeout, asyncio.TimeoutError):
696
+ raise TimeoutError("Timeout connecting to server")
697
+ except OSError as e:
698
+ raise ConnectionError(self._error_message(e))
699
+ except BaseException as exc:
700
+ raise ConnectionError(exc) from exc
701
+
702
+ try:
703
+ await self.on_connect()
704
+ except RedisError:
705
+ # clean up after any error in on_connect
706
+ await self.disconnect()
707
+ raise
708
+
709
+ # run any user callbacks. right now the only internal callback
710
+ # is for pubsub channel/pattern resubscription
711
+ for callback in self._connect_callbacks:
712
+ task = callback(self)
713
+ if task and inspect.isawaitable(task):
714
+ await task
715
+
716
+ async def _connect(self):
717
+ """Create a TCP socket connection"""
718
+ async with async_timeout.timeout(self.socket_connect_timeout):
719
+ reader, writer = await asyncio.open_connection(
720
+ host=self.host,
721
+ port=self.port,
722
+ ssl=self.ssl_context.get() if self.ssl_context else None,
723
+ )
724
+ self._reader = reader
725
+ self._writer = writer
726
+ sock = writer.transport.get_extra_info("socket")
727
+ if sock is not None:
728
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
729
+ try:
730
+ # TCP_KEEPALIVE
731
+ if self.socket_keepalive:
732
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
733
+ for k, v in self.socket_keepalive_options.items():
734
+ sock.setsockopt(socket.SOL_TCP, k, v)
735
+
736
+ except (OSError, TypeError):
737
+ # `socket_keepalive_options` might contain invalid options
738
+ # causing an error. Do not leave the connection open.
739
+ writer.close()
740
+ raise
741
+
742
+ def _error_message(self, exception):
743
+ # args for socket.error can either be (errno, "message")
744
+ # or just "message"
745
+ if len(exception.args) == 1:
746
+ return f"Error connecting to {self.host}:{self.port}. {exception.args[0]}."
747
+ else:
748
+ return (
749
+ f"Error {exception.args[0]} connecting to {self.host}:{self.port}. "
750
+ f"{exception.args[0]}."
751
+ )
752
+
753
+ async def on_connect(self):
754
+ """Initialize the connection, authenticate and select a database"""
755
+ self._parser.on_connect(self)
756
+
757
+ # if username and/or password are set, authenticate
758
+ if self.username or self.password:
759
+ auth_args: Union[Tuple[str], Tuple[str, str]]
760
+ if self.username:
761
+ auth_args = (self.username, self.password or "")
762
+ else:
763
+ # Mypy bug: https://github.com/python/mypy/issues/10944
764
+ auth_args = (self.password or "",)
765
+ # avoid checking health here -- PING will fail if we try
766
+ # to check the health prior to the AUTH
767
+ await self.send_command("AUTH", *auth_args, check_health=False)
768
+
769
+ try:
770
+ auth_response = await self.read_response()
771
+ except AuthenticationWrongNumberOfArgsError:
772
+ # a username and password were specified but the Redis
773
+ # server seems to be < 6.0.0 which expects a single password
774
+ # arg. retry auth with just the password.
775
+ # https://github.com/andymccurdy/redis-py/issues/1274
776
+ await self.send_command("AUTH", self.password, check_health=False)
777
+ auth_response = await self.read_response()
778
+
779
+ if str_if_bytes(auth_response) != "OK":
780
+ raise AuthenticationError("Invalid Username or Password")
781
+
782
+ # if a client_name is given, set it
783
+ if self.client_name:
784
+ await self.send_command("CLIENT", "SETNAME", self.client_name)
785
+ if str_if_bytes(await self.read_response()) != "OK":
786
+ raise ConnectionError("Error setting client name")
787
+
788
+ # if a database is specified, switch to it
789
+ if self.db:
790
+ await self.send_command("SELECT", self.db)
791
+ if str_if_bytes(await self.read_response()) != "OK":
792
+ raise ConnectionError("Invalid Database")
793
+
794
+ async def disconnect(self):
795
+ """Disconnects from the Redis server"""
796
+ try:
797
+ async with async_timeout.timeout(self.socket_connect_timeout):
798
+ self._parser.on_disconnect()
799
+ if not self.is_connected:
800
+ return
801
+ try:
802
+ if os.getpid() == self.pid:
803
+ self._writer.close() # type: ignore[union-attr]
804
+ # py3.6 doesn't have this method
805
+ if hasattr(self._writer, "wait_closed"):
806
+ await self._writer.wait_closed() # type: ignore[union-attr]
807
+ except OSError:
808
+ pass
809
+ self._reader = None
810
+ self._writer = None
811
+ except asyncio.TimeoutError:
812
+ raise TimeoutError(
813
+ f"Timed out closing connection after {self.socket_connect_timeout}"
814
+ ) from None
815
+
816
+ async def check_health(self):
817
+ """Check the health of the connection with a PING/PONG"""
818
+ if (
819
+ self.health_check_interval
820
+ and asyncio.get_event_loop().time() > self.next_health_check
821
+ ):
822
+ try:
823
+ await self.send_command("PING", check_health=False)
824
+ if str_if_bytes(await self.read_response()) != "PONG":
825
+ raise ConnectionError("Bad response from PING health check")
826
+ except (ConnectionError, TimeoutError) as err:
827
+ await self.disconnect()
828
+ try:
829
+ await self.send_command("PING", check_health=False)
830
+ if str_if_bytes(await self.read_response()) != "PONG":
831
+ raise ConnectionError(
832
+ "Bad response from PING health check"
833
+ ) from None
834
+ except BaseException as err2:
835
+ raise err2 from err
836
+
837
+ async def _send_packed_command(self, command: Iterable[bytes]) -> None:
838
+ if self._writer is None:
839
+ raise RedisError("Connection already closed.")
840
+
841
+ self._writer.writelines(command)
842
+ await self._writer.drain()
843
+
844
+ async def send_packed_command(
845
+ self,
846
+ command: Union[bytes, str, Iterable[bytes]],
847
+ check_health: bool = True,
848
+ ):
849
+ """Send an already packed command to the Redis server"""
850
+ if not self._writer:
851
+ await self.connect()
852
+ # guard against health check recursion
853
+ if check_health:
854
+ await self.check_health()
855
+ try:
856
+ if isinstance(command, str):
857
+ command = command.encode()
858
+ if isinstance(command, bytes):
859
+ command = [command]
860
+ await asyncio.wait_for(
861
+ self._send_packed_command(command),
862
+ self.socket_timeout,
863
+ )
864
+ except asyncio.TimeoutError:
865
+ await self.disconnect()
866
+ raise TimeoutError("Timeout writing to socket") from None
867
+ except OSError as e:
868
+ await self.disconnect()
869
+ if len(e.args) == 1:
870
+ err_no, errmsg = "UNKNOWN", e.args[0]
871
+ else:
872
+ err_no = e.args[0]
873
+ errmsg = e.args[1]
874
+ raise ConnectionError(
875
+ f"Error {err_no} while writing to socket. {errmsg}."
876
+ ) from e
877
+ except BaseException:
878
+ await self.disconnect()
879
+ raise
880
+
881
+ async def send_command(self, *args, **kwargs):
882
+ """Pack and send a command to the Redis server"""
883
+ if not self.is_connected:
884
+ await self.connect()
885
+ await self.send_packed_command(
886
+ self.pack_command(*args), check_health=kwargs.get("check_health", True)
887
+ )
888
+
889
+ async def can_read(self, timeout: float = 0):
890
+ """Poll the socket to see if there's data that can be read."""
891
+ if not self.is_connected:
892
+ await self.connect()
893
+ return await self._parser.can_read(timeout)
894
+
895
+ async def read_response(self):
896
+ """Read the response from a previously sent command"""
897
+ try:
898
+ async with self._lock:
899
+ async with async_timeout.timeout(self.socket_timeout):
900
+ response = await self._parser.read_response()
901
+ except asyncio.TimeoutError:
902
+ await self.disconnect()
903
+ raise TimeoutError(f"Timeout reading from {self.host}:{self.port}")
904
+ except OSError as e:
905
+ await self.disconnect()
906
+ raise ConnectionError(
907
+ f"Error while reading from {self.host}:{self.port} : {e.args}"
908
+ )
909
+ except BaseException:
910
+ await self.disconnect()
911
+ raise
912
+
913
+ if self.health_check_interval:
914
+ self.next_health_check = (
915
+ asyncio.get_event_loop().time() + self.health_check_interval
916
+ )
917
+
918
+ if isinstance(response, ResponseError):
919
+ raise response from None
920
+ return response
921
+
922
+ def pack_command(self, *args: EncodableT) -> List[bytes]:
923
+ """Pack a series of arguments into the Redis protocol"""
924
+ output = []
925
+ # the client might have included 1 or more literal arguments in
926
+ # the command name, e.g., 'CONFIG GET'. The Redis server expects these
927
+ # arguments to be sent separately, so split the first argument
928
+ # manually. These arguments should be bytestrings so that they are
929
+ # not encoded.
930
+ assert not isinstance(args[0], float)
931
+ if isinstance(args[0], str):
932
+ args = tuple(args[0].encode().split()) + args[1:]
933
+ elif b" " in args[0]:
934
+ args = tuple(args[0].split()) + args[1:]
935
+
936
+ buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))
937
+
938
+ buffer_cutoff = self._buffer_cutoff
939
+ for arg in map(self.encoder.encode, args):
940
+ # to avoid large string mallocs, chunk the command into the
941
+ # output list if we're sending large values or memoryviews
942
+ arg_length = len(arg)
943
+ if (
944
+ len(buff) > buffer_cutoff
945
+ or arg_length > buffer_cutoff
946
+ or isinstance(arg, memoryview)
947
+ ):
948
+ buff = SYM_EMPTY.join(
949
+ (buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF)
950
+ )
951
+ output.append(buff)
952
+ output.append(arg)
953
+ buff = SYM_CRLF
954
+ else:
955
+ buff = SYM_EMPTY.join(
956
+ (
957
+ buff,
958
+ SYM_DOLLAR,
959
+ str(arg_length).encode(),
960
+ SYM_CRLF,
961
+ arg,
962
+ SYM_CRLF,
963
+ )
964
+ )
965
+ output.append(buff)
966
+ return output
967
+
968
+ def pack_commands(self, commands: Iterable[Iterable[EncodableT]]) -> List[bytes]:
969
+ """Pack multiple commands into the Redis protocol"""
970
+ output: List[bytes] = []
971
+ pieces: List[bytes] = []
972
+ buffer_length = 0
973
+ buffer_cutoff = self._buffer_cutoff
974
+
975
+ for cmd in commands:
976
+ for chunk in self.pack_command(*cmd):
977
+ chunklen = len(chunk)
978
+ if (
979
+ buffer_length > buffer_cutoff
980
+ or chunklen > buffer_cutoff
981
+ or isinstance(chunk, memoryview)
982
+ ):
983
+ output.append(SYM_EMPTY.join(pieces))
984
+ buffer_length = 0
985
+ pieces = []
986
+
987
+ if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
988
+ output.append(chunk)
989
+ else:
990
+ pieces.append(chunk)
991
+ buffer_length += chunklen
992
+
993
+ if pieces:
994
+ output.append(SYM_EMPTY.join(pieces))
995
+ return output
996
+
997
+
998
+ class SSLConnection(Connection):
999
+ def __init__(
1000
+ self,
1001
+ ssl_keyfile: Optional[str] = None,
1002
+ ssl_certfile: Optional[str] = None,
1003
+ ssl_cert_reqs: str = "required",
1004
+ ssl_ca_certs: Optional[str] = None,
1005
+ ssl_check_hostname: bool = False,
1006
+ **kwargs,
1007
+ ):
1008
+ super().__init__(**kwargs)
1009
+ self.ssl_context: RedisSSLContext = RedisSSLContext(
1010
+ keyfile=ssl_keyfile,
1011
+ certfile=ssl_certfile,
1012
+ cert_reqs=ssl_cert_reqs,
1013
+ ca_certs=ssl_ca_certs,
1014
+ check_hostname=ssl_check_hostname,
1015
+ )
1016
+
1017
+ @property
1018
+ def keyfile(self):
1019
+ return self.ssl_context.keyfile
1020
+
1021
+ @property
1022
+ def certfile(self):
1023
+ return self.ssl_context.certfile
1024
+
1025
+ @property
1026
+ def cert_reqs(self):
1027
+ return self.ssl_context.cert_reqs
1028
+
1029
+ @property
1030
+ def ca_certs(self):
1031
+ return self.ssl_context.ca_certs
1032
+
1033
+ @property
1034
+ def check_hostname(self):
1035
+ return self.ssl_context.check_hostname
1036
+
1037
+
1038
+ class RedisSSLContext:
1039
+ __slots__ = (
1040
+ "keyfile",
1041
+ "certfile",
1042
+ "cert_reqs",
1043
+ "ca_certs",
1044
+ "context",
1045
+ "check_hostname",
1046
+ )
1047
+
1048
+ def __init__(
1049
+ self,
1050
+ keyfile: Optional[str] = None,
1051
+ certfile: Optional[str] = None,
1052
+ cert_reqs: Optional[str] = None,
1053
+ ca_certs: Optional[str] = None,
1054
+ check_hostname: bool = False,
1055
+ ):
1056
+ self.keyfile = keyfile
1057
+ self.certfile = certfile
1058
+ if cert_reqs is None:
1059
+ self.cert_reqs = ssl.CERT_NONE
1060
+ elif isinstance(cert_reqs, str):
1061
+ CERT_REQS = {
1062
+ "none": ssl.CERT_NONE,
1063
+ "optional": ssl.CERT_OPTIONAL,
1064
+ "required": ssl.CERT_REQUIRED,
1065
+ }
1066
+ if cert_reqs not in CERT_REQS:
1067
+ raise RedisError(
1068
+ f"Invalid SSL Certificate Requirements Flag: {cert_reqs}"
1069
+ )
1070
+ self.cert_reqs = CERT_REQS[cert_reqs]
1071
+ self.ca_certs = ca_certs
1072
+ self.check_hostname = check_hostname
1073
+ self.context: Optional[ssl.SSLContext] = None
1074
+
1075
+ def get(self) -> ssl.SSLContext:
1076
+ if not self.context:
1077
+ context = ssl.create_default_context()
1078
+ context.check_hostname = self.check_hostname
1079
+ context.verify_mode = self.cert_reqs
1080
+ if self.certfile and self.keyfile:
1081
+ context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
1082
+ if self.ca_certs:
1083
+ context.load_verify_locations(self.ca_certs)
1084
+ self.context = context
1085
+ return self.context
1086
+
1087
+
1088
+ class UnixDomainSocketConnection(Connection): # lgtm [py/missing-call-to-init]
1089
+ def __init__(
1090
+ self,
1091
+ *,
1092
+ path: str = "",
1093
+ db: Union[str, int] = 0,
1094
+ username: Optional[str] = None,
1095
+ password: Optional[str] = None,
1096
+ socket_timeout: Optional[float] = None,
1097
+ socket_connect_timeout: Optional[float] = None,
1098
+ encoding: str = "utf-8",
1099
+ encoding_errors: str = "strict",
1100
+ decode_responses: bool = False,
1101
+ retry_on_timeout: bool = False,
1102
+ parser_class: Type[BaseParser] = DefaultParser,
1103
+ socket_read_size: int = 65536,
1104
+ health_check_interval: float = 0.0,
1105
+ client_name=None,
1106
+ ):
1107
+ self.pid = os.getpid()
1108
+ self.path = path
1109
+ self.db = db
1110
+ self.username = username
1111
+ self.client_name = client_name
1112
+ self.password = password
1113
+ self.socket_timeout = socket_timeout
1114
+ self.socket_connect_timeout = socket_connect_timeout or socket_timeout or None
1115
+ self.retry_on_timeout = retry_on_timeout
1116
+ self.health_check_interval = health_check_interval
1117
+ self.next_health_check = -1
1118
+ self.encoder = Encoder(encoding, encoding_errors, decode_responses)
1119
+ self._sock = None
1120
+ self._reader = None
1121
+ self._writer = None
1122
+ self._parser = parser_class(socket_read_size=socket_read_size)
1123
+ self._connect_callbacks = []
1124
+ self._buffer_cutoff = 6000
1125
+ self._lock = asyncio.Lock()
1126
+
1127
+ def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
1128
+ pieces = [
1129
+ ("path", self.path),
1130
+ ("db", self.db),
1131
+ ]
1132
+ if self.client_name:
1133
+ pieces.append(("client_name", self.client_name))
1134
+ return pieces
1135
+
1136
+ async def _connect(self):
1137
+ async with async_timeout.timeout(self.socket_connect_timeout):
1138
+ reader, writer = await asyncio.open_unix_connection(path=self.path)
1139
+ self._reader = reader
1140
+ self._writer = writer
1141
+ await self.on_connect()
1142
+
1143
+ def _error_message(self, exception):
1144
+ # args for socket.error can either be (errno, "message")
1145
+ # or just "message"
1146
+ if len(exception.args) == 1:
1147
+ return f"Error connecting to unix socket: {self.path}. {exception.args[0]}."
1148
+ else:
1149
+ return (
1150
+ f"Error {exception.args[0]} connecting to unix socket: "
1151
+ f"{self.path}. {exception.args[1]}."
1152
+ )
1153
+
1154
+
1155
+ FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO")
1156
+
1157
+
1158
+ def to_bool(value) -> Optional[bool]:
1159
+ if value is None or value == "":
1160
+ return None
1161
+ if isinstance(value, str) and value.upper() in FALSE_STRINGS:
1162
+ return False
1163
+ return bool(value)
1164
+
1165
+
1166
+ URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyType(
1167
+ {
1168
+ "db": int,
1169
+ "socket_timeout": float,
1170
+ "socket_connect_timeout": float,
1171
+ "socket_keepalive": to_bool,
1172
+ "retry_on_timeout": to_bool,
1173
+ "max_connections": int,
1174
+ "health_check_interval": int,
1175
+ "ssl_check_hostname": to_bool,
1176
+ }
1177
+ )
1178
+
1179
+
1180
+ class ConnectKwargs(TypedDict, total=False):
1181
+ username: str
1182
+ password: str
1183
+ connection_class: Type[Connection]
1184
+ host: str
1185
+ port: int
1186
+ db: int
1187
+ path: str
1188
+
1189
+
1190
+ def parse_url(url: str) -> ConnectKwargs:
1191
+ parsed: ParseResult = urlparse(url)
1192
+ kwargs: ConnectKwargs = {}
1193
+
1194
+ for name, value_list in parse_qs(parsed.query).items():
1195
+ if value_list and len(value_list) > 0:
1196
+ value = unquote(value_list[0])
1197
+ parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
1198
+ if parser:
1199
+ try:
1200
+ # We can't type this.
1201
+ kwargs[name] = parser(value) # type: ignore[misc]
1202
+ except (TypeError, ValueError):
1203
+ raise ValueError(f"Invalid value for `{name}` in connection URL.")
1204
+ else:
1205
+ kwargs[name] = value # type: ignore[misc]
1206
+
1207
+ if parsed.username:
1208
+ kwargs["username"] = unquote(parsed.username)
1209
+ if parsed.password:
1210
+ kwargs["password"] = unquote(parsed.password)
1211
+
1212
+ # We only support redis://, rediss:// and unix:// schemes.
1213
+ if parsed.scheme == "unix":
1214
+ if parsed.path:
1215
+ kwargs["path"] = unquote(parsed.path)
1216
+ kwargs["connection_class"] = UnixDomainSocketConnection
1217
+
1218
+ elif parsed.scheme in ("redis", "rediss"):
1219
+ if parsed.hostname:
1220
+ kwargs["host"] = unquote(parsed.hostname)
1221
+ if parsed.port:
1222
+ kwargs["port"] = int(parsed.port)
1223
+
1224
+ # If there's a path argument, use it as the db argument if a
1225
+ # querystring value wasn't specified
1226
+ if parsed.path and "db" not in kwargs:
1227
+ try:
1228
+ kwargs["db"] = int(unquote(parsed.path).replace("/", ""))
1229
+ except (AttributeError, ValueError):
1230
+ pass
1231
+
1232
+ if parsed.scheme == "rediss":
1233
+ kwargs["connection_class"] = SSLConnection
1234
+ else:
1235
+ valid_schemes = "redis://, rediss://, unix://"
1236
+ raise ValueError(
1237
+ f"Redis URL must specify one of the following schemes ({valid_schemes})"
1238
+ )
1239
+
1240
+ return kwargs
1241
+
1242
+
1243
+ _CP = TypeVar("_CP", bound="ConnectionPool")
1244
+
1245
+
1246
+ class ConnectionPool:
1247
+ """
1248
+ Create a connection pool. ``If max_connections`` is set, then this
1249
+ object raises :py:class:`~redis.ConnectionError` when the pool's
1250
+ limit is reached.
1251
+
1252
+ By default, TCP connections are created unless ``connection_class``
1253
+ is specified. Use :py:class:`~redis.UnixDomainSocketConnection` for
1254
+ unix sockets.
1255
+
1256
+ Any additional keyword arguments are passed to the constructor of
1257
+ ``connection_class``.
1258
+ """
1259
+
1260
+ @classmethod
1261
+ def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
1262
+ """
1263
+ Return a connection pool configured from the given URL.
1264
+
1265
+ For example::
1266
+
1267
+ redis://[[username]:[password]]@localhost:6379/0
1268
+ rediss://[[username]:[password]]@localhost:6379/0
1269
+ unix://[[username]:[password]]@/path/to/socket.sock?db=0
1270
+
1271
+ Three URL schemes are supported:
1272
+
1273
+ - `redis://` creates a TCP socket connection. See more at:
1274
+ <https://www.iana.org/assignments/uri-schemes/prov/redis>
1275
+ - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
1276
+ <https://www.iana.org/assignments/uri-schemes/prov/rediss>
1277
+ - ``unix://``: creates a Unix Domain Socket connection.
1278
+
1279
+ The username, password, hostname, path and all querystring values
1280
+ are passed through urllib.parse.unquote in order to replace any
1281
+ percent-encoded values with their corresponding characters.
1282
+
1283
+ There are several ways to specify a database number. The first value
1284
+ found will be used:
1285
+ 1. A ``db`` querystring option, e.g. redis://localhost?db=0
1286
+ 2. If using the redis:// or rediss:// schemes, the path argument
1287
+ of the url, e.g. redis://localhost/0
1288
+ 3. A ``db`` keyword argument to this function.
1289
+
1290
+ If none of these options are specified, the default db=0 is used.
1291
+
1292
+ All querystring options are cast to their appropriate Python types.
1293
+ Boolean arguments can be specified with string values "True"/"False"
1294
+ or "Yes"/"No". Values that cannot be properly cast cause a
1295
+ ``ValueError`` to be raised. Once parsed, the querystring arguments
1296
+ and keyword arguments are passed to the ``ConnectionPool``'s
1297
+ class initializer. In the case of conflicting arguments, querystring
1298
+ arguments always win.
1299
+ """
1300
+ url_options = parse_url(url)
1301
+ kwargs.update(url_options)
1302
+ return cls(**kwargs)
1303
+
1304
+ def __init__(
1305
+ self,
1306
+ connection_class: Type[Connection] = Connection,
1307
+ max_connections: Optional[int] = None,
1308
+ **connection_kwargs,
1309
+ ):
1310
+ max_connections = max_connections or 2 ** 31
1311
+ if not isinstance(max_connections, int) or max_connections < 0:
1312
+ raise ValueError('"max_connections" must be a positive integer')
1313
+
1314
+ self.connection_class = connection_class
1315
+ self.connection_kwargs = connection_kwargs
1316
+ self.max_connections = max_connections
1317
+
1318
+ # a lock to protect the critical section in _checkpid().
1319
+ # this lock is acquired when the process id changes, such as
1320
+ # after a fork. during this time, multiple threads in the child
1321
+ # process could attempt to acquire this lock. the first thread
1322
+ # to acquire the lock will reset the data structures and lock
1323
+ # object of this pool. subsequent threads acquiring this lock
1324
+ # will notice the first thread already did the work and simply
1325
+ # release the lock.
1326
+ self._fork_lock = threading.Lock()
1327
+ self._lock = asyncio.Lock()
1328
+ self._created_connections: int
1329
+ self._available_connections: List[Connection]
1330
+ self._in_use_connections: Set[Connection]
1331
+ self.reset() # lgtm [py/init-calls-subclass]
1332
+ self.encoder_class = self.connection_kwargs.get("encoder_class", Encoder)
1333
+
1334
+ def __repr__(self):
1335
+ return (
1336
+ f"{self.__class__.__name__}"
1337
+ f"<{self.connection_class(**self.connection_kwargs)!r}>"
1338
+ )
1339
+
1340
+ def reset(self):
1341
+ self._lock = asyncio.Lock()
1342
+ self._created_connections = 0
1343
+ self._available_connections = []
1344
+ self._in_use_connections = set()
1345
+
1346
+ # this must be the last operation in this method. while reset() is
1347
+ # called when holding _fork_lock, other threads in this process
1348
+ # can call _checkpid() which compares self.pid and os.getpid() without
1349
+ # holding any lock (for performance reasons). keeping this assignment
1350
+ # as the last operation ensures that those other threads will also
1351
+ # notice a pid difference and block waiting for the first thread to
1352
+ # release _fork_lock. when each of these threads eventually acquire
1353
+ # _fork_lock, they will notice that another thread already called
1354
+ # reset() and they will immediately release _fork_lock and continue on.
1355
+ self.pid = os.getpid()
1356
+
1357
+ def _checkpid(self):
1358
+ # _checkpid() attempts to keep ConnectionPool fork-safe on modern
1359
+ # systems. this is called by all ConnectionPool methods that
1360
+ # manipulate the pool's state such as get_connection() and release().
1361
+ #
1362
+ # _checkpid() determines whether the process has forked by comparing
1363
+ # the current process id to the process id saved on the ConnectionPool
1364
+ # instance. if these values are the same, _checkpid() simply returns.
1365
+ #
1366
+ # when the process ids differ, _checkpid() assumes that the process
1367
+ # has forked and that we're now running in the child process. the child
1368
+ # process cannot use the parent's file descriptors (e.g., sockets).
1369
+ # therefore, when _checkpid() sees the process id change, it calls
1370
+ # reset() in order to reinitialize the child's ConnectionPool. this
1371
+ # will cause the child to make all new connection objects.
1372
+ #
1373
+ # _checkpid() is protected by self._fork_lock to ensure that multiple
1374
+ # threads in the child process do not call reset() multiple times.
1375
+ #
1376
+ # there is an extremely small chance this could fail in the following
1377
+ # scenario:
1378
+ # 1. process A calls _checkpid() for the first time and acquires
1379
+ # self._fork_lock.
1380
+ # 2. while holding self._fork_lock, process A forks (the fork()
1381
+ # could happen in a different thread owned by process A)
1382
+ # 3. process B (the forked child process) inherits the
1383
+ # ConnectionPool's state from the parent. that state includes
1384
+ # a locked _fork_lock. process B will not be notified when
1385
+ # process A releases the _fork_lock and will thus never be
1386
+ # able to acquire the _fork_lock.
1387
+ #
1388
+ # to mitigate this possible deadlock, _checkpid() will only wait 5
1389
+ # seconds to acquire _fork_lock. if _fork_lock cannot be acquired in
1390
+ # that time it is assumed that the child is deadlocked and a
1391
+ # redis.ChildDeadlockedError error is raised.
1392
+ if self.pid != os.getpid():
1393
+ acquired = self._fork_lock.acquire(timeout=5)
1394
+ if not acquired:
1395
+ raise ChildDeadlockedError
1396
+ # reset() the instance for the new process if another thread
1397
+ # hasn't already done so
1398
+ try:
1399
+ if self.pid != os.getpid():
1400
+ self.reset()
1401
+ finally:
1402
+ self._fork_lock.release()
1403
+
1404
+ async def get_connection(self, command_name, *keys, **options):
1405
+ """Get a connection from the pool"""
1406
+ self._checkpid()
1407
+ async with self._lock:
1408
+ try:
1409
+ connection = self._available_connections.pop()
1410
+ except IndexError:
1411
+ connection = self.make_connection()
1412
+ self._in_use_connections.add(connection)
1413
+
1414
+ try:
1415
+ # ensure this connection is connected to Redis
1416
+ await connection.connect()
1417
+ # connections that the pool provides should be ready to send
1418
+ # a command. if not, the connection was either returned to the
1419
+ # pool before all data has been read or the socket has been
1420
+ # closed. either way, reconnect and verify everything is good.
1421
+ try:
1422
+ if await connection.can_read():
1423
+ raise ConnectionError("Connection has data") from None
1424
+ except ConnectionError:
1425
+ await connection.disconnect()
1426
+ await connection.connect()
1427
+ if await connection.can_read():
1428
+ raise ConnectionError("Connection not ready") from None
1429
+ except BaseException:
1430
+ # release the connection back to the pool so that we don't
1431
+ # leak it
1432
+ await self.release(connection)
1433
+ raise
1434
+
1435
+ return connection
1436
+
1437
+ def get_encoder(self):
1438
+ """Return an encoder based on encoding settings"""
1439
+ kwargs = self.connection_kwargs
1440
+ return self.encoder_class(
1441
+ encoding=kwargs.get("encoding", "utf-8"),
1442
+ encoding_errors=kwargs.get("encoding_errors", "strict"),
1443
+ decode_responses=kwargs.get("decode_responses", False),
1444
+ )
1445
+
1446
+ def make_connection(self):
1447
+ """Create a new connection"""
1448
+ if self._created_connections >= self.max_connections:
1449
+ raise ConnectionError("Too many connections")
1450
+ self._created_connections += 1
1451
+ return self.connection_class(**self.connection_kwargs)
1452
+
1453
+ async def release(self, connection: Connection):
1454
+ """Releases the connection back to the pool"""
1455
+ self._checkpid()
1456
+ async with self._lock:
1457
+ try:
1458
+ self._in_use_connections.remove(connection)
1459
+ except KeyError:
1460
+ # Gracefully fail when a connection is returned to this pool
1461
+ # that the pool doesn't actually own
1462
+ pass
1463
+
1464
+ if self.owns_connection(connection):
1465
+ self._available_connections.append(connection)
1466
+ else:
1467
+ # pool doesn't own this connection. do not add it back
1468
+ # to the pool and decrement the count so that another
1469
+ # connection can take its place if needed
1470
+ self._created_connections -= 1
1471
+ await connection.disconnect()
1472
+ return
1473
+
1474
+ def owns_connection(self, connection: Connection):
1475
+ return connection.pid == self.pid
1476
+
1477
+ async def disconnect(self, inuse_connections: bool = True):
1478
+ """
1479
+ Disconnects connections in the pool
1480
+
1481
+ If ``inuse_connections`` is True, disconnect connections that are
1482
+ current in use, potentially by other tasks. Otherwise only disconnect
1483
+ connections that are idle in the pool.
1484
+ """
1485
+ self._checkpid()
1486
+ async with self._lock:
1487
+ if inuse_connections:
1488
+ connections: Iterable[Connection] = chain(
1489
+ self._available_connections, self._in_use_connections
1490
+ )
1491
+ else:
1492
+ connections = self._available_connections
1493
+ resp = await asyncio.gather(
1494
+ *(connection.disconnect() for connection in connections),
1495
+ return_exceptions=True,
1496
+ )
1497
+ exc = next((r for r in resp if isinstance(r, BaseException)), None)
1498
+ if exc:
1499
+ raise exc
1500
+
1501
+
1502
+ class BlockingConnectionPool(ConnectionPool):
1503
+ """
1504
+ Thread-safe blocking connection pool::
1505
+
1506
+ >>> from aioredis.client import Redis
1507
+ >>> client = Redis(connection_pool=BlockingConnectionPool())
1508
+
1509
+ It performs the same function as the default
1510
+ :py:class:`~redis.ConnectionPool` implementation, in that,
1511
+ it maintains a pool of reusable connections that can be shared by
1512
+ multiple redis clients (safely across threads if required).
1513
+
1514
+ The difference is that, in the event that a client tries to get a
1515
+ connection from the pool when all of connections are in use, rather than
1516
+ raising a :py:class:`~redis.ConnectionError` (as the default
1517
+ :py:class:`~redis.ConnectionPool` implementation does), it
1518
+ makes the client wait ("blocks") for a specified number of seconds until
1519
+ a connection becomes available.
1520
+
1521
+ Use ``max_connections`` to increase / decrease the pool size::
1522
+
1523
+ >>> pool = BlockingConnectionPool(max_connections=10)
1524
+
1525
+ Use ``timeout`` to tell it either how many seconds to wait for a connection
1526
+ to become available, or to block forever:
1527
+
1528
+ >>> # Block forever.
1529
+ >>> pool = BlockingConnectionPool(timeout=None)
1530
+
1531
+ >>> # Raise a ``ConnectionError`` after five seconds if a connection is
1532
+ >>> # not available.
1533
+ >>> pool = BlockingConnectionPool(timeout=5)
1534
+ """
1535
+
1536
+ def __init__(
1537
+ self,
1538
+ max_connections: int = 50,
1539
+ timeout: Optional[int] = 20,
1540
+ connection_class: Type[Connection] = Connection,
1541
+ queue_class: Type[asyncio.Queue] = asyncio.LifoQueue,
1542
+ **connection_kwargs,
1543
+ ):
1544
+
1545
+ self.queue_class = queue_class
1546
+ self.timeout = timeout
1547
+ self._connections: List[Connection]
1548
+ super().__init__(
1549
+ connection_class=connection_class,
1550
+ max_connections=max_connections,
1551
+ **connection_kwargs,
1552
+ )
1553
+
1554
+ def reset(self):
1555
+ # Create and fill up a thread safe queue with ``None`` values.
1556
+ self.pool = self.queue_class(self.max_connections)
1557
+ while True:
1558
+ try:
1559
+ self.pool.put_nowait(None)
1560
+ except asyncio.QueueFull:
1561
+ break
1562
+
1563
+ # Keep a list of actual connection instances so that we can
1564
+ # disconnect them later.
1565
+ self._connections = []
1566
+
1567
+ # this must be the last operation in this method. while reset() is
1568
+ # called when holding _fork_lock, other threads in this process
1569
+ # can call _checkpid() which compares self.pid and os.getpid() without
1570
+ # holding any lock (for performance reasons). keeping this assignment
1571
+ # as the last operation ensures that those other threads will also
1572
+ # notice a pid difference and block waiting for the first thread to
1573
+ # release _fork_lock. when each of these threads eventually acquire
1574
+ # _fork_lock, they will notice that another thread already called
1575
+ # reset() and they will immediately release _fork_lock and continue on.
1576
+ self.pid = os.getpid()
1577
+
1578
+ def make_connection(self):
1579
+ """Make a fresh connection."""
1580
+ connection = self.connection_class(**self.connection_kwargs)
1581
+ self._connections.append(connection)
1582
+ return connection
1583
+
1584
+ async def get_connection(self, command_name, *keys, **options):
1585
+ """
1586
+ Get a connection, blocking for ``self.timeout`` until a connection
1587
+ is available from the pool.
1588
+
1589
+ If the connection returned is ``None`` then creates a new connection.
1590
+ Because we use a last-in first-out queue, the existing connections
1591
+ (having been returned to the pool after the initial ``None`` values
1592
+ were added) will be returned before ``None`` values. This means we only
1593
+ create new connections when we need to, i.e.: the actual number of
1594
+ connections will only increase in response to demand.
1595
+ """
1596
+ # Make sure we haven't changed process.
1597
+ self._checkpid()
1598
+
1599
+ # Try and get a connection from the pool. If one isn't available within
1600
+ # self.timeout then raise a ``ConnectionError``.
1601
+ connection = None
1602
+ try:
1603
+ async with async_timeout.timeout(self.timeout):
1604
+ connection = await self.pool.get()
1605
+ except (asyncio.QueueEmpty, asyncio.TimeoutError):
1606
+ # Note that this is not caught by the redis client and will be
1607
+ # raised unless handled by application code. If you want never to
1608
+ raise ConnectionError("No connection available.")
1609
+
1610
+ # If the ``connection`` is actually ``None`` then that's a cue to make
1611
+ # a new connection to add to the pool.
1612
+ if connection is None:
1613
+ connection = self.make_connection()
1614
+
1615
+ try:
1616
+ # ensure this connection is connected to Redis
1617
+ await connection.connect()
1618
+ # connections that the pool provides should be ready to send
1619
+ # a command. if not, the connection was either returned to the
1620
+ # pool before all data has been read or the socket has been
1621
+ # closed. either way, reconnect and verify everything is good.
1622
+ try:
1623
+ if await connection.can_read():
1624
+ raise ConnectionError("Connection has data") from None
1625
+ except ConnectionError:
1626
+ await connection.disconnect()
1627
+ await connection.connect()
1628
+ if await connection.can_read():
1629
+ raise ConnectionError("Connection not ready") from None
1630
+ except BaseException:
1631
+ # release the connection back to the pool so that we don't leak it
1632
+ await self.release(connection)
1633
+ raise
1634
+
1635
+ return connection
1636
+
1637
+ async def release(self, connection: Connection):
1638
+ """Releases the connection back to the pool."""
1639
+ # Make sure we haven't changed process.
1640
+ self._checkpid()
1641
+ if not self.owns_connection(connection):
1642
+ # pool doesn't own this connection. do not add it back
1643
+ # to the pool. instead add a None value which is a placeholder
1644
+ # that will cause the pool to recreate the connection if
1645
+ # its needed.
1646
+ await connection.disconnect()
1647
+ self.pool.put_nowait(None)
1648
+ return
1649
+
1650
+ # Put the connection back into the pool.
1651
+ try:
1652
+ self.pool.put_nowait(connection)
1653
+ except asyncio.QueueFull:
1654
+ # perhaps the pool has been reset() after a fork? regardless,
1655
+ # we don't want this connection
1656
+ pass
1657
+
1658
+ async def disconnect(self, inuse_connections: bool = True):
1659
+ """Disconnects all connections in the pool."""
1660
+ self._checkpid()
1661
+ async with self._lock:
1662
+ resp = await asyncio.gather(
1663
+ *(connection.disconnect() for connection in self._connections),
1664
+ return_exceptions=True,
1665
+ )
1666
+ exc = next((r for r in resp if isinstance(r, BaseException)), None)
1667
+ if exc:
1668
+ raise exc