-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathconnection.py
1760 lines (1504 loc) · 63.4 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import os
import socket
import ssl
import sys
import threading
import weakref
from abc import abstractmethod
from itertools import chain
from queue import Empty, Full, LifoQueue
from time import time
from typing import Any, Callable, Dict, List, Optional, Type, Union
from urllib.parse import parse_qs, unquote, urlparse
from redis.cache import (
CacheEntry,
CacheEntryStatus,
CacheFactory,
CacheFactoryInterface,
CacheInterface,
CacheKey,
)
from ._parsers import Encoder, _HiredisParser, _RESP2Parser, _RESP3Parser
from .auth.token import TokenInterface
from .backoff import NoBackoff
from .credentials import CredentialProvider, UsernamePasswordCredentialProvider
from .event import AfterConnectionReleasedEvent, EventDispatcher
from .exceptions import (
AuthenticationError,
AuthenticationWrongNumberOfArgsError,
ChildDeadlockedError,
ConnectionError,
DataError,
RedisError,
ResponseError,
TimeoutError,
)
from .retry import Retry
from .utils import (
CRYPTOGRAPHY_AVAILABLE,
HIREDIS_AVAILABLE,
SSL_AVAILABLE,
compare_versions,
ensure_string,
format_error_message,
get_lib_version,
str_if_bytes,
)
if HIREDIS_AVAILABLE:
import hiredis
SYM_STAR = b"*"
SYM_DOLLAR = b"$"
SYM_CRLF = b"\r\n"
SYM_EMPTY = b""
DEFAULT_RESP_VERSION = 2
SENTINEL = object()
DefaultParser: Type[Union[_RESP2Parser, _RESP3Parser, _HiredisParser]]
if HIREDIS_AVAILABLE:
DefaultParser = _HiredisParser
else:
DefaultParser = _RESP2Parser
class HiredisRespSerializer:
def pack(self, *args: List):
"""Pack a series of arguments into the Redis protocol"""
output = []
if isinstance(args[0], str):
args = tuple(args[0].encode().split()) + args[1:]
elif b" " in args[0]:
args = tuple(args[0].split()) + args[1:]
try:
output.append(hiredis.pack_command(args))
except TypeError:
_, value, traceback = sys.exc_info()
raise DataError(value).with_traceback(traceback)
return output
class PythonRespSerializer:
def __init__(self, buffer_cutoff, encode) -> None:
self._buffer_cutoff = buffer_cutoff
self.encode = encode
def pack(self, *args):
"""Pack a series of arguments into the Redis protocol"""
output = []
# the client might have included 1 or more literal arguments in
# the command name, e.g., 'CONFIG GET'. The Redis server expects these
# arguments to be sent separately, so split the first argument
# manually. These arguments should be bytestrings so that they are
# not encoded.
if isinstance(args[0], str):
args = tuple(args[0].encode().split()) + args[1:]
elif b" " in args[0]:
args = tuple(args[0].split()) + args[1:]
buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))
buffer_cutoff = self._buffer_cutoff
for arg in map(self.encode, args):
# to avoid large string mallocs, chunk the command into the
# output list if we're sending large values or memoryviews
arg_length = len(arg)
if (
len(buff) > buffer_cutoff
or arg_length > buffer_cutoff
or isinstance(arg, memoryview)
):
buff = SYM_EMPTY.join(
(buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF)
)
output.append(buff)
output.append(arg)
buff = SYM_CRLF
else:
buff = SYM_EMPTY.join(
(
buff,
SYM_DOLLAR,
str(arg_length).encode(),
SYM_CRLF,
arg,
SYM_CRLF,
)
)
output.append(buff)
return output
class ConnectionInterface:
@abstractmethod
def repr_pieces(self):
pass
@abstractmethod
def register_connect_callback(self, callback):
pass
@abstractmethod
def deregister_connect_callback(self, callback):
pass
@abstractmethod
def set_parser(self, parser_class):
pass
@abstractmethod
def get_protocol(self):
pass
@abstractmethod
def connect(self):
pass
@abstractmethod
def on_connect(self):
pass
@abstractmethod
def disconnect(self, *args):
pass
@abstractmethod
def check_health(self):
pass
@abstractmethod
def send_packed_command(self, command, check_health=True):
pass
@abstractmethod
def send_command(self, *args, **kwargs):
pass
@abstractmethod
def can_read(self, timeout=0):
pass
@abstractmethod
def read_response(
self,
disable_decoding=False,
*,
disconnect_on_error=True,
push_request=False,
):
pass
@abstractmethod
def pack_command(self, *args):
pass
@abstractmethod
def pack_commands(self, commands):
pass
@property
@abstractmethod
def handshake_metadata(self) -> Union[Dict[bytes, bytes], Dict[str, str]]:
pass
@abstractmethod
def set_re_auth_token(self, token: TokenInterface):
pass
@abstractmethod
def re_auth(self):
pass
class AbstractConnection(ConnectionInterface):
"Manages communication to and from a Redis server"
def __init__(
self,
db: int = 0,
password: Optional[str] = None,
socket_timeout: Optional[float] = None,
socket_connect_timeout: Optional[float] = None,
retry_on_timeout: bool = False,
retry_on_error=SENTINEL,
encoding: str = "utf-8",
encoding_errors: str = "strict",
decode_responses: bool = False,
parser_class=DefaultParser,
socket_read_size: int = 65536,
health_check_interval: int = 0,
client_name: Optional[str] = None,
lib_name: Optional[str] = "redis-py",
lib_version: Optional[str] = get_lib_version(),
username: Optional[str] = None,
retry: Union[Any, None] = None,
redis_connect_func: Optional[Callable[[], None]] = None,
credential_provider: Optional[CredentialProvider] = None,
protocol: Optional[int] = 2,
command_packer: Optional[Callable[[], None]] = None,
event_dispatcher: Optional[EventDispatcher] = None,
):
"""
Initialize a new Connection.
To specify a retry policy for specific errors, first set
`retry_on_error` to a list of the error/s to retry on, then set
`retry` to a valid `Retry` object.
To retry on TimeoutError, `retry_on_timeout` can also be set to `True`.
"""
if (username or password) and credential_provider is not None:
raise DataError(
"'username' and 'password' cannot be passed along with 'credential_"
"provider'. Please provide only one of the following arguments: \n"
"1. 'password' and (optional) 'username'\n"
"2. 'credential_provider'"
)
if event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
else:
self._event_dispatcher = event_dispatcher
self.pid = os.getpid()
self.db = db
self.client_name = client_name
self.lib_name = lib_name
self.lib_version = lib_version
self.credential_provider = credential_provider
self.password = password
self.username = username
self.socket_timeout = socket_timeout
if socket_connect_timeout is None:
socket_connect_timeout = socket_timeout
self.socket_connect_timeout = socket_connect_timeout
self.retry_on_timeout = retry_on_timeout
if retry_on_error is SENTINEL:
retry_on_error = []
if retry_on_timeout:
# Add TimeoutError to the errors list to retry on
retry_on_error.append(TimeoutError)
self.retry_on_error = retry_on_error
if retry or retry_on_error:
if retry is None:
self.retry = Retry(NoBackoff(), 1)
else:
# deep-copy the Retry object as it is mutable
self.retry = copy.deepcopy(retry)
# Update the retry's supported errors with the specified errors
self.retry.update_supported_errors(retry_on_error)
else:
self.retry = Retry(NoBackoff(), 0)
self.health_check_interval = health_check_interval
self.next_health_check = 0
self.redis_connect_func = redis_connect_func
self.encoder = Encoder(encoding, encoding_errors, decode_responses)
self.handshake_metadata = None
self._sock = None
self._socket_read_size = socket_read_size
self.set_parser(parser_class)
self._connect_callbacks = []
self._buffer_cutoff = 6000
self._re_auth_token: Optional[TokenInterface] = None
try:
p = int(protocol)
except TypeError:
p = DEFAULT_RESP_VERSION
except ValueError:
raise ConnectionError("protocol must be an integer")
finally:
if p < 2 or p > 3:
raise ConnectionError("protocol must be either 2 or 3")
# p = DEFAULT_RESP_VERSION
self.protocol = p
self._command_packer = self._construct_command_packer(command_packer)
def __repr__(self):
repr_args = ",".join([f"{k}={v}" for k, v in self.repr_pieces()])
return f"<{self.__class__.__module__}.{self.__class__.__name__}({repr_args})>"
@abstractmethod
def repr_pieces(self):
pass
def __del__(self):
try:
self.disconnect()
except Exception:
pass
def _construct_command_packer(self, packer):
if packer is not None:
return packer
elif HIREDIS_AVAILABLE:
return HiredisRespSerializer()
else:
return PythonRespSerializer(self._buffer_cutoff, self.encoder.encode)
def register_connect_callback(self, callback):
"""
Register a callback to be called when the connection is established either
initially or reconnected. This allows listeners to issue commands that
are ephemeral to the connection, for example pub/sub subscription or
key tracking. The callback must be a _method_ and will be kept as
a weak reference.
"""
wm = weakref.WeakMethod(callback)
if wm not in self._connect_callbacks:
self._connect_callbacks.append(wm)
def deregister_connect_callback(self, callback):
"""
De-register a previously registered callback. It will no-longer receive
notifications on connection events. Calling this is not required when the
listener goes away, since the callbacks are kept as weak methods.
"""
try:
self._connect_callbacks.remove(weakref.WeakMethod(callback))
except ValueError:
pass
def set_parser(self, parser_class):
"""
Creates a new instance of parser_class with socket size:
_socket_read_size and assigns it to the parser for the connection
:param parser_class: The required parser class
"""
self._parser = parser_class(socket_read_size=self._socket_read_size)
def connect(self):
"Connects to the Redis server if not already connected"
if self._sock:
return
try:
sock = self.retry.call_with_retry(
lambda: self._connect(), lambda error: self.disconnect(error)
)
except socket.timeout:
raise TimeoutError("Timeout connecting to server")
except OSError as e:
raise ConnectionError(self._error_message(e))
self._sock = sock
try:
if self.redis_connect_func is None:
# Use the default on_connect function
self.on_connect()
else:
# Use the passed function redis_connect_func
self.redis_connect_func(self)
except RedisError:
# clean up after any error in on_connect
self.disconnect()
raise
# run any user callbacks. right now the only internal callback
# is for pubsub channel/pattern resubscription
# first, remove any dead weakrefs
self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()]
for ref in self._connect_callbacks:
callback = ref()
if callback:
callback(self)
@abstractmethod
def _connect(self):
pass
@abstractmethod
def _host_error(self):
pass
def _error_message(self, exception):
return format_error_message(self._host_error(), exception)
def on_connect(self):
"Initialize the connection, authenticate and select a database"
self._parser.on_connect(self)
parser = self._parser
auth_args = None
# if credential provider or username and/or password are set, authenticate
if self.credential_provider or (self.username or self.password):
cred_provider = (
self.credential_provider
or UsernamePasswordCredentialProvider(self.username, self.password)
)
auth_args = cred_provider.get_credentials()
# if resp version is specified and we have auth args,
# we need to send them via HELLO
if auth_args and self.protocol not in [2, "2"]:
if isinstance(self._parser, _RESP2Parser):
self.set_parser(_RESP3Parser)
# update cluster exception classes
self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
self._parser.on_connect(self)
if len(auth_args) == 1:
auth_args = ["default", auth_args[0]]
self.send_command("HELLO", self.protocol, "AUTH", *auth_args)
self.handshake_metadata = self.read_response()
# if response.get(b"proto") != self.protocol and response.get(
# "proto"
# ) != self.protocol:
# raise ConnectionError("Invalid RESP version")
elif auth_args:
# avoid checking health here -- PING will fail if we try
# to check the health prior to the AUTH
self.send_command("AUTH", *auth_args, check_health=False)
try:
auth_response = self.read_response()
except AuthenticationWrongNumberOfArgsError:
# a username and password were specified but the Redis
# server seems to be < 6.0.0 which expects a single password
# arg. retry auth with just the password.
# /~https://github.com/andymccurdy/redis-py/issues/1274
self.send_command("AUTH", auth_args[-1], check_health=False)
auth_response = self.read_response()
if str_if_bytes(auth_response) != "OK":
raise AuthenticationError("Invalid Username or Password")
# if resp version is specified, switch to it
elif self.protocol not in [2, "2"]:
if isinstance(self._parser, _RESP2Parser):
self.set_parser(_RESP3Parser)
# update cluster exception classes
self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
self._parser.on_connect(self)
self.send_command("HELLO", self.protocol)
self.handshake_metadata = self.read_response()
if (
self.handshake_metadata.get(b"proto") != self.protocol
and self.handshake_metadata.get("proto") != self.protocol
):
raise ConnectionError("Invalid RESP version")
# if a client_name is given, set it
if self.client_name:
self.send_command("CLIENT", "SETNAME", self.client_name)
if str_if_bytes(self.read_response()) != "OK":
raise ConnectionError("Error setting client name")
try:
# set the library name and version
if self.lib_name:
self.send_command("CLIENT", "SETINFO", "LIB-NAME", self.lib_name)
self.read_response()
except ResponseError:
pass
try:
if self.lib_version:
self.send_command("CLIENT", "SETINFO", "LIB-VER", self.lib_version)
self.read_response()
except ResponseError:
pass
# if a database is specified, switch to it
if self.db:
self.send_command("SELECT", self.db)
if str_if_bytes(self.read_response()) != "OK":
raise ConnectionError("Invalid Database")
def disconnect(self, *args):
"Disconnects from the Redis server"
self._parser.on_disconnect()
conn_sock = self._sock
self._sock = None
if conn_sock is None:
return
if os.getpid() == self.pid:
try:
conn_sock.shutdown(socket.SHUT_RDWR)
except (OSError, TypeError):
pass
try:
conn_sock.close()
except OSError:
pass
def _send_ping(self):
"""Send PING, expect PONG in return"""
self.send_command("PING", check_health=False)
if str_if_bytes(self.read_response()) != "PONG":
raise ConnectionError("Bad response from PING health check")
def _ping_failed(self, error):
"""Function to call when PING fails"""
self.disconnect()
def check_health(self):
"""Check the health of the connection with a PING/PONG"""
if self.health_check_interval and time() > self.next_health_check:
self.retry.call_with_retry(self._send_ping, self._ping_failed)
def send_packed_command(self, command, check_health=True):
"""Send an already packed command to the Redis server"""
if not self._sock:
self.connect()
# guard against health check recursion
if check_health:
self.check_health()
try:
if isinstance(command, str):
command = [command]
for item in command:
self._sock.sendall(item)
except socket.timeout:
self.disconnect()
raise TimeoutError("Timeout writing to socket")
except OSError as e:
self.disconnect()
if len(e.args) == 1:
errno, errmsg = "UNKNOWN", e.args[0]
else:
errno = e.args[0]
errmsg = e.args[1]
raise ConnectionError(f"Error {errno} while writing to socket. {errmsg}.")
except BaseException:
# BaseExceptions can be raised when a socket send operation is not
# finished, e.g. due to a timeout. Ideally, a caller could then re-try
# to send un-sent data. However, the send_packed_command() API
# does not support it so there is no point in keeping the connection open.
self.disconnect()
raise
def send_command(self, *args, **kwargs):
"""Pack and send a command to the Redis server"""
self.send_packed_command(
self._command_packer.pack(*args),
check_health=kwargs.get("check_health", True),
)
def can_read(self, timeout=0):
"""Poll the socket to see if there's data that can be read."""
sock = self._sock
if not sock:
self.connect()
host_error = self._host_error()
try:
return self._parser.can_read(timeout)
except OSError as e:
self.disconnect()
raise ConnectionError(f"Error while reading from {host_error}: {e.args}")
def read_response(
self,
disable_decoding=False,
*,
disconnect_on_error=True,
push_request=False,
):
"""Read the response from a previously sent command"""
host_error = self._host_error()
try:
if self.protocol in ["3", 3] and not HIREDIS_AVAILABLE:
response = self._parser.read_response(
disable_decoding=disable_decoding, push_request=push_request
)
else:
response = self._parser.read_response(disable_decoding=disable_decoding)
except socket.timeout:
if disconnect_on_error:
self.disconnect()
raise TimeoutError(f"Timeout reading from {host_error}")
except OSError as e:
if disconnect_on_error:
self.disconnect()
raise ConnectionError(
f"Error while reading from {host_error}" f" : {e.args}"
)
except BaseException:
# Also by default close in case of BaseException. A lot of code
# relies on this behaviour when doing Command/Response pairs.
# See #1128.
if disconnect_on_error:
self.disconnect()
raise
if self.health_check_interval:
self.next_health_check = time() + self.health_check_interval
if isinstance(response, ResponseError):
try:
raise response
finally:
del response # avoid creating ref cycles
return response
def pack_command(self, *args):
"""Pack a series of arguments into the Redis protocol"""
return self._command_packer.pack(*args)
def pack_commands(self, commands):
"""Pack multiple commands into the Redis protocol"""
output = []
pieces = []
buffer_length = 0
buffer_cutoff = self._buffer_cutoff
for cmd in commands:
for chunk in self._command_packer.pack(*cmd):
chunklen = len(chunk)
if (
buffer_length > buffer_cutoff
or chunklen > buffer_cutoff
or isinstance(chunk, memoryview)
):
if pieces:
output.append(SYM_EMPTY.join(pieces))
buffer_length = 0
pieces = []
if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
output.append(chunk)
else:
pieces.append(chunk)
buffer_length += chunklen
if pieces:
output.append(SYM_EMPTY.join(pieces))
return output
def get_protocol(self) -> int or str:
return self.protocol
@property
def handshake_metadata(self) -> Union[Dict[bytes, bytes], Dict[str, str]]:
return self._handshake_metadata
@handshake_metadata.setter
def handshake_metadata(self, value: Union[Dict[bytes, bytes], Dict[str, str]]):
self._handshake_metadata = value
def set_re_auth_token(self, token: TokenInterface):
self._re_auth_token = token
def re_auth(self):
if self._re_auth_token is not None:
self.send_command(
"AUTH",
self._re_auth_token.try_get("oid"),
self._re_auth_token.get_value(),
)
self.read_response()
self._re_auth_token = None
class Connection(AbstractConnection):
"Manages TCP communication to and from a Redis server"
def __init__(
self,
host="localhost",
port=6379,
socket_keepalive=False,
socket_keepalive_options=None,
socket_type=0,
**kwargs,
):
self.host = host
self.port = int(port)
self.socket_keepalive = socket_keepalive
self.socket_keepalive_options = socket_keepalive_options or {}
self.socket_type = socket_type
super().__init__(**kwargs)
def repr_pieces(self):
pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
if self.client_name:
pieces.append(("client_name", self.client_name))
return pieces
def _connect(self):
"Create a TCP socket connection"
# we want to mimic what socket.create_connection does to support
# ipv4/ipv6, but we want to set options prior to calling
# socket.connect()
err = None
for res in socket.getaddrinfo(
self.host, self.port, self.socket_type, socket.SOCK_STREAM
):
family, socktype, proto, canonname, socket_address = res
sock = None
try:
sock = socket.socket(family, socktype, proto)
# TCP_NODELAY
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# TCP_KEEPALIVE
if self.socket_keepalive:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
for k, v in self.socket_keepalive_options.items():
sock.setsockopt(socket.IPPROTO_TCP, k, v)
# set the socket_connect_timeout before we connect
sock.settimeout(self.socket_connect_timeout)
# connect
sock.connect(socket_address)
# set the socket_timeout now that we're connected
sock.settimeout(self.socket_timeout)
return sock
except OSError as _:
err = _
if sock is not None:
sock.close()
if err is not None:
raise err
raise OSError("socket.getaddrinfo returned an empty list")
def _host_error(self):
return f"{self.host}:{self.port}"
class CacheProxyConnection(ConnectionInterface):
DUMMY_CACHE_VALUE = b"foo"
MIN_ALLOWED_VERSION = "7.4.0"
DEFAULT_SERVER_NAME = "redis"
def __init__(
self,
conn: ConnectionInterface,
cache: CacheInterface,
pool_lock: threading.Lock,
):
self.pid = os.getpid()
self._conn = conn
self.retry = self._conn.retry
self.host = self._conn.host
self.port = self._conn.port
self.credential_provider = conn.credential_provider
self._pool_lock = pool_lock
self._cache = cache
self._cache_lock = threading.Lock()
self._current_command_cache_key = None
self._current_options = None
self.register_connect_callback(self._enable_tracking_callback)
def repr_pieces(self):
return self._conn.repr_pieces()
def register_connect_callback(self, callback):
self._conn.register_connect_callback(callback)
def deregister_connect_callback(self, callback):
self._conn.deregister_connect_callback(callback)
def set_parser(self, parser_class):
self._conn.set_parser(parser_class)
def connect(self):
self._conn.connect()
server_name = self._conn.handshake_metadata.get(b"server", None)
if server_name is None:
server_name = self._conn.handshake_metadata.get("server", None)
server_ver = self._conn.handshake_metadata.get(b"version", None)
if server_ver is None:
server_ver = self._conn.handshake_metadata.get("version", None)
if server_ver is None or server_ver is None:
raise ConnectionError("Cannot retrieve information about server version")
server_ver = ensure_string(server_ver)
server_name = ensure_string(server_name)
if (
server_name != self.DEFAULT_SERVER_NAME
or compare_versions(server_ver, self.MIN_ALLOWED_VERSION) == 1
):
raise ConnectionError(
"To maximize compatibility with all Redis products, client-side caching is supported by Redis 7.4 or later" # noqa: E501
)
def on_connect(self):
self._conn.on_connect()
def disconnect(self, *args):
with self._cache_lock:
self._cache.flush()
self._conn.disconnect(*args)
def check_health(self):
self._conn.check_health()
def send_packed_command(self, command, check_health=True):
# TODO: Investigate if it's possible to unpack command
# or extract keys from packed command
self._conn.send_packed_command(command)
def send_command(self, *args, **kwargs):
self._process_pending_invalidations()
with self._cache_lock:
# Command is write command or not allowed
# to be cached.
if not self._cache.is_cachable(CacheKey(command=args[0], redis_keys=())):
self._current_command_cache_key = None
self._conn.send_command(*args, **kwargs)
return
if kwargs.get("keys") is None:
raise ValueError("Cannot create cache key.")
# Creates cache key.
self._current_command_cache_key = CacheKey(
command=args[0], redis_keys=tuple(kwargs.get("keys"))
)
with self._cache_lock:
# We have to trigger invalidation processing in case if
# it was cached by another connection to avoid
# queueing invalidations in stale connections.
if self._cache.get(self._current_command_cache_key):
entry = self._cache.get(self._current_command_cache_key)
if entry.connection_ref != self._conn:
with self._pool_lock:
while entry.connection_ref.can_read():
entry.connection_ref.read_response(push_request=True)
return
# Set temporary entry value to prevent
# race condition from another connection.
self._cache.set(
CacheEntry(
cache_key=self._current_command_cache_key,
cache_value=self.DUMMY_CACHE_VALUE,
status=CacheEntryStatus.IN_PROGRESS,
connection_ref=self._conn,
)
)
# Send command over socket only if it's allowed
# read-only command that not yet cached.
self._conn.send_command(*args, **kwargs)
def can_read(self, timeout=0):
return self._conn.can_read(timeout)
def read_response(
self, disable_decoding=False, *, disconnect_on_error=True, push_request=False
):
with self._cache_lock:
# Check if command response exists in a cache and it's not in progress.
if (
self._current_command_cache_key is not None
and self._cache.get(self._current_command_cache_key) is not None
and self._cache.get(self._current_command_cache_key).status
!= CacheEntryStatus.IN_PROGRESS
):
res = copy.deepcopy(
self._cache.get(self._current_command_cache_key).cache_value
)
self._current_command_cache_key = None
return res
response = self._conn.read_response(
disable_decoding=disable_decoding,
disconnect_on_error=disconnect_on_error,
push_request=push_request,
)
with self._cache_lock:
# Prevent not-allowed command from caching.
if self._current_command_cache_key is None:
return response
# If response is None prevent from caching.
if response is None:
self._cache.delete_by_cache_keys([self._current_command_cache_key])
return response
cache_entry = self._cache.get(self._current_command_cache_key)
# Cache only responses that still valid
# and wasn't invalidated by another connection in meantime.
if cache_entry is not None:
cache_entry.status = CacheEntryStatus.VALID
cache_entry.cache_value = response
self._cache.set(cache_entry)
self._current_command_cache_key = None
return response
def pack_command(self, *args):
return self._conn.pack_command(*args)
def pack_commands(self, commands):
return self._conn.pack_commands(commands)
@property
def handshake_metadata(self) -> Union[Dict[bytes, bytes], Dict[str, str]]:
return self._conn.handshake_metadata
def _connect(self):
self._conn._connect()
def _host_error(self):
self._conn._host_error()
def _enable_tracking_callback(self, conn: ConnectionInterface) -> None:
conn.send_command("CLIENT", "TRACKING", "ON")
conn.read_response()
conn._parser.set_invalidation_push_handler(self._on_invalidation_callback)
def _process_pending_invalidations(self):
while self.can_read():
self._conn.read_response(push_request=True)
def _on_invalidation_callback(self, data: List[Union[str, Optional[List[bytes]]]]):
with self._cache_lock:
# Flush cache when DB flushed on server-side
if data[1] is None:
self._cache.flush()
else:
self._cache.delete_by_redis_keys(data[1])
def get_protocol(self):
return self._conn.get_protocol()
def set_re_auth_token(self, token: TokenInterface):
self._conn.set_re_auth_token(token)
def re_auth(self):
self._conn.re_auth()
class SSLConnection(Connection):
"""Manages SSL connections to and from the Redis server(s).
This class extends the Connection class, adding SSL functionality, and making
use of ssl.SSLContext (https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
""" # noqa
def __init__(
self,
ssl_keyfile=None,
ssl_certfile=None,
ssl_cert_reqs="required",
ssl_ca_certs=None,
ssl_ca_data=None,
ssl_check_hostname=False,
ssl_ca_path=None,
ssl_password=None,
ssl_validate_ocsp=False,