-
Notifications
You must be signed in to change notification settings - Fork 73
/
protocol.py
3062 lines (2531 loc) · 99.4 KB
/
protocol.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
#!/usr/bin/env python3
import asyncio
import enum
import logging
import types
from collections import deque
from functools import wraps
from inspect import getcallargs, getfullargspec, signature
from .cursors import Cursor, DictCursor, SetCursor, ZCursor
from .encoders import BaseEncoder, UTF8Encoder
from .exceptions import (
ConnectionLostError,
Error,
ErrorReply,
NoRunningScriptError,
NotConnectedError,
ScriptKilledError,
TimeoutError,
TransactionError,
)
from .log import logger
from .replies import (
BlockingPopReply,
ClientListReply,
ConfigPairReply,
DictReply,
EvalScriptReply,
InfoReply,
ListReply,
PubSubReply,
SetReply,
StatusReply,
ZRangeReply,
)
try:
import hiredis
except ImportError:
hiredis = None
NoneType = type(None)
class _NoTransactionType(object):
"""
Instance of this object can be passed to a @_command when it's not part of
a transaction. We need this because we need a singleton which is different
from None. (None could be a valid input for a @_command, so there is no way
to see whether this would be an extra 'transaction' value.)
"""
_NoTransaction = _NoTransactionType()
class ZScoreBoundary:
"""Score boundary for a sorted set,
for queries like zrangebyscore and similar.
:param value: Value for the boundary.
:type value: float
:param exclude_boundary: Exclude the boundary.
:type exclude_boundary: bool
"""
def __init__(self, value, exclude_boundary=False):
assert isinstance(value, float) or value in ("+inf", "-inf")
self.value = value
self.exclude_boundary = exclude_boundary
def __repr__(self):
return "ZScoreBoundary(value=%r, exclude_boundary=%r)" % (
self.value,
self.exclude_boundary,
)
ZScoreBoundary.MIN_VALUE = ZScoreBoundary("-inf")
ZScoreBoundary.MAX_VALUE = ZScoreBoundary("+inf")
class ZAggregate(enum.Enum):
"""Aggregation method for zinterstore and zunionstore
"""
SUM = "SUM"
MIN = "MIN"
MAX = "MAX"
class PipelinedCall:
"""Track record for call that is being executed in a protocol
"""
__slots__ = ("cmd", "is_blocking")
def __init__(self, cmd, is_blocking):
self.cmd = cmd
self.is_blocking = is_blocking
class MultiBulkReply:
"""Container for a multi bulk reply.
"""
def __init__(self, protocol, count):
#: Buffer of incoming, undelivered data, received from the parser.
self._data_queue = []
#: Incoming read queries.
#: Contains (read_count, Future, decode_flag, one_only_flag) tuples.
self._f_queue = deque()
self.protocol = protocol
self.count = int(count)
def _feed_received(self, item):
"""Feed entry for the parser
"""
# Push received items on the queue
self._data_queue.append(item)
self._flush()
def _flush(self):
"""Answer read queries when we have enough data in our multibulk reply
"""
# As long as we have more data in our queue then we require for a read
# query -> answer queries.
while self._f_queue and self._f_queue[0][0] <= len(self._data_queue):
# Pop query.
count, f, decode, one_only = self._f_queue.popleft()
# Slice data buffer.
data, self._data_queue = self._data_queue[:count], self._data_queue[count:]
# When the decode flag is given, decode bytes to native types.
if decode:
data = [self._decode(d) for d in data]
# When one_only flag has been given, don't return an array.
if one_only:
assert len(data) == 1
f.set_result(data[0])
else:
f.set_result(data)
def _decode(self, result):
"""Decode bytes to native Python types
"""
if isinstance(result, (StatusReply, int, float, MultiBulkReply)):
# Note that MultiBulkReplies can be nested. e.g. in the 'scan' operation.
return result
elif isinstance(result, bytes):
return self.protocol.decode_to_native(result)
elif result is None:
return result
else:
raise AssertionError("Invalid type: %r" % type(result))
def _read(self, decode=True, count=1, _one=False):
"""Do read operation on the queue. Return future.
"""
f = asyncio.Future()
self._f_queue.append((count, f, decode, _one))
# If there is enough data on the queue, answer future immediately.
self._flush()
return f
def iter_raw(self):
"""Iterate over all multi bulk packets.
This yields futures that won't decode bytes yet.
"""
for i in range(self.count):
yield self._read(decode=False, _one=True)
def __iter__(self):
"""Iterate over the reply. This yields coroutines of the decoded packets.
It decodes bytes automatically using protocol.decode_to_native.
"""
for i in range(self.count):
yield self._read(_one=True)
def __repr__(self):
return "MultiBulkReply(protocol=%r, count=%r)" % (self.protocol, self.count)
class _ScanPart:
"""Internal: result chunk of a scan operation
"""
def __init__(self, new_cursor_pos, items):
self.new_cursor_pos = new_cursor_pos
self.items = items
class PostProcessors:
"""At the protocol level, we only know about a few basic classes; they
include: bool, int, StatusReply, MultiBulkReply and bytes.
This will return a postprocessor function that turns these into more
meaningful objects.
For some methods, we have several post processors. E.g. a list can be
returned either as a ListReply (which has some special streaming
functionality), but also as a Python list.
"""
@classmethod
def get_all(cls, return_type):
"""Return list of (suffix, return_type, post_processor)
"""
default = cls.get_default(return_type)
alternate = cls.get_alternate_post_processor(return_type)
result = [("", return_type, default)]
if alternate:
result.append(alternate)
return result
@classmethod
def get_default(cls, return_type):
"""Give post processor function for return type
"""
return {
ListReply: cls.multibulk_as_list,
SetReply: cls.multibulk_as_set,
DictReply: cls.multibulk_as_dict,
float: cls.bytes_to_float,
(float, NoneType): cls.bytes_to_float_or_none,
NativeType: cls.bytes_to_native,
(NativeType, NoneType): cls.bytes_to_native_or_none,
InfoReply: cls.bytes_to_info,
ClientListReply: cls.bytes_to_clientlist,
str: cls.bytes_to_str,
bool: cls.int_to_bool,
BlockingPopReply: cls.multibulk_as_blocking_pop_reply,
ZRangeReply: cls.multibulk_as_zrangereply,
StatusReply: cls.bytes_to_status_reply,
(StatusReply, NoneType): cls.bytes_to_status_reply_or_none,
int: None,
(int, NoneType): None,
ConfigPairReply: cls.multibulk_as_configpair,
ListOf(bool): cls.multibulk_as_boolean_list,
_ScanPart: cls.multibulk_as_scanpart,
EvalScriptReply: cls.any_to_evalscript,
NoneType: None,
}[return_type]
@classmethod
def get_alternate_post_processor(cls, return_type):
"""For list/set/dict. Create additional post processors that return
python classes rather than ListReply/SetReply/DictReply.
"""
original_post_processor = cls.get_default(return_type)
if return_type == ListReply:
async def as_list(protocol, result):
result = await original_post_processor(protocol, result)
return await result.aslist()
return "_aslist", list, as_list
elif return_type == SetReply:
async def as_set(protocol, result):
result = await original_post_processor(protocol, result)
return await result.asset()
return "_asset", set, as_set
elif return_type in (DictReply, ZRangeReply):
async def as_dict(protocol, result):
result = await original_post_processor(protocol, result)
return await result.asdict()
return "_asdict", dict, as_dict
# === Post processor handlers below. ===
async def multibulk_as_list(protocol, result):
assert isinstance(result, MultiBulkReply)
return ListReply(result)
async def multibulk_as_boolean_list(protocol, result):
# Turn the array of integers into booleans.
assert isinstance(result, MultiBulkReply)
values = await ListReply(result).aslist()
return [bool(v) for v in values]
async def multibulk_as_set(protocol, result):
assert isinstance(result, MultiBulkReply)
return SetReply(result)
async def multibulk_as_dict(protocol, result):
assert isinstance(result, MultiBulkReply)
return DictReply(result)
async def multibulk_as_zrangereply(protocol, result):
assert isinstance(result, MultiBulkReply)
return ZRangeReply(result)
async def multibulk_as_blocking_pop_reply(protocol, result):
if result is None:
raise TimeoutError("Timeout in blocking pop")
else:
assert isinstance(result, MultiBulkReply)
list_name, value = await ListReply(result).aslist()
return BlockingPopReply(list_name, value)
async def multibulk_as_configpair(protocol, result):
assert isinstance(result, MultiBulkReply)
parameter, value = await ListReply(result).aslist()
return ConfigPairReply(parameter, value)
async def multibulk_as_scanpart(protocol, result):
"""Process scanpart result.
This is a multibulk reply of length two, where the first item is the
new cursor position and the second item is a nested multi bulk reply
containing all the elements.
"""
# Get outer multi bulk reply.
assert isinstance(result, MultiBulkReply)
new_cursor_pos, items_bulk = await ListReply(result).aslist()
assert isinstance(items_bulk, MultiBulkReply)
# Read all items for scan chunk in memory. This is fine, because it's
# transmitted in chunks of about 10.
items = await ListReply(items_bulk).aslist()
return _ScanPart(int(new_cursor_pos), items)
async def bytes_to_info(protocol, result):
assert isinstance(result, bytes)
return InfoReply(result)
async def bytes_to_status_reply(protocol, result):
assert isinstance(result, bytes)
return StatusReply(result.decode("utf-8"))
async def bytes_to_status_reply_or_none(protocol, result):
assert isinstance(result, (bytes, NoneType))
if result:
return StatusReply(result.decode("utf-8"))
async def bytes_to_clientlist(protocol, result):
assert isinstance(result, bytes)
return ClientListReply(result)
async def int_to_bool(protocol, result):
assert isinstance(result, int)
return bool(result) # Convert int to bool
async def bytes_to_native(protocol, result):
assert isinstance(result, bytes)
return protocol.decode_to_native(result)
async def bytes_to_str(protocol, result):
assert isinstance(result, bytes)
return result.decode("ascii")
async def bytes_to_native_or_none(protocol, result):
if result is None:
return result
else:
assert isinstance(result, bytes)
return protocol.decode_to_native(result)
async def bytes_to_float_or_none(protocol, result):
if result is None:
return result
assert isinstance(result, bytes)
return float(result)
async def bytes_to_float(protocol, result):
assert isinstance(result, bytes)
return float(result)
async def any_to_evalscript(protocol, result):
# Result can be native, int, MultiBulkReply or even a nested structure
assert isinstance(result, (int, bytes, MultiBulkReply, NoneType))
return EvalScriptReply(protocol, result)
class ListOf:
"""Annotation helper for protocol methods
"""
def __init__(self, type_):
self.type = type_
def __repr__(self):
return "ListOf(%r)" % self.type
def __eq__(self, other):
return isinstance(other, ListOf) and other.type == self.type
def __hash__(self):
return hash((ListOf, self.type))
class NativeType:
"""Constant which represents the native Python type that's used
"""
def __new__(cls):
raise Exception("NativeType is not meant to be initialized.")
class CommandCreator:
"""Utility for creating a wrapper around the Redis protocol methods.
This will also do type checking.
This wrapper handles (optionally) post processing of the returned data and
implements some logic where commands behave different in case of a
transaction or pubsub.
Warning: We use the annotations of `method` extensively for type checking
and determining which post processor to choose.
"""
def __init__(self, method):
self.method = method
@property
def specs(self):
"""Argspecs
"""
return getfullargspec(self.method)
@property
def return_type(self):
"""Return type as defined in the method's annotation
"""
return self.specs.annotations.get("return", None)
@property
def params(self):
return {k: v for k, v in self.specs.annotations.items() if k != "return"}
@classmethod
def get_real_type(cls, protocol, type_):
"""Given a protocol instance, and type annotation, return something that
we can pass to isinstance for the typechecking.
"""
# If NativeType was given, replace it with the type of the protocol
# itself.
if isinstance(type_, tuple):
return tuple(cls.get_real_type(protocol, t) for t in type_)
if type_ == NativeType:
return protocol.native_type
elif isinstance(type_, ListOf):
return (
list,
types.GeneratorType,
) # We don't check the content of the list.
else:
return type_
def _create_input_typechecker(self):
"""Return function that does typechecking on input data
"""
params = self.params
if params:
def typecheck_input(protocol, *a, **kw):
"""Given a protocol instance and *a/**kw of this method, raise TypeError
when the signature doesn't match.
"""
if protocol.enable_typechecking:
# All @_command/@_query_command methods can take
# *optionally* a Transaction instance as first argument.
if a and isinstance(a[0], (Transaction, _NoTransactionType)):
a = a[1:]
for name, value in getcallargs(
self.method, None, _NoTransaction, *a, **kw
).items():
if name in params:
real_type = self.get_real_type(protocol, params[name])
if not isinstance(value, real_type):
raise TypeError(
"RedisProtocol.%s received %r, expected %r"
% (
self.method.__name__,
type(value).__name__,
real_type,
)
)
else:
def typecheck_input(protocol, *a, **kw):
pass
return typecheck_input
def _create_return_typechecker(self, return_type):
"""Return function that does typechecking on output data
"""
if return_type and not isinstance(
return_type, str
): # Exclude 'Transaction'/'Subscription' which are 'str'
def typecheck_return(protocol, result):
"""Given protocol and result value. Raise TypeError if the result is of
the wrong type.
"""
if protocol.enable_typechecking:
expected_type = self.get_real_type(protocol, return_type)
if not isinstance(result, expected_type):
raise TypeError(
f"Got unexpected return type {type(result).__name__!r} in "
f"RedisProtocol.{self.method.__name__}, "
f"expected {expected_type!r}"
)
else:
def typecheck_return(protocol, result):
pass
return typecheck_return
def _get_docstring(self, suffix, return_type):
# Append the real signature as the first line in the docstring.
# (This will make the sphinx docs show the real signature instead of
# (*a, **kw) of the wrapper.)
# (But don't put the annotations inside the copied signature, that's rather
# ugly in the docs.)
parameters = signature(self.method).parameters
# The below differs from tuple(parameters.keys()) as it preserves the
# * and ** prefixes of variadic arguments
argnames = tuple(str(p).split(":")[0] for p in parameters.values())
# Use function annotations to generate param documentation.
def get_name(type_):
"""Turn type annotation into doc string
"""
try:
return {
BlockingPopReply: ":class:`BlockingPopReply <asyncio_redis.replies.BlockingPopReply>`", # noqa: E501
ConfigPairReply: ":class:`ConfigPairReply <asyncio_redis.replies.ConfigPairReply>`", # noqa: E501
DictReply: ":class:`DictReply <asyncio_redis.replies.DictReply>`",
InfoReply: ":class:`InfoReply <asyncio_redis.replies.InfoReply>`",
ClientListReply: ":class:`InfoReply <asyncio_redis.replies.ClientListReply>`", # noqa: E501
ListReply: ":class:`ListReply <asyncio_redis.replies.ListReply>`",
MultiBulkReply: ":class:`MultiBulkReply <asyncio_redis.replies.MultiBulkReply>`", # noqa: E501
NativeType: "Native Python type, as defined by :attr:`~asyncio_redis.encoders.BaseEncoder.native_type`", # noqa: E501
NoneType: "None",
SetReply: ":class:`SetReply <asyncio_redis.replies.SetReply>`",
StatusReply: ":class:`StatusReply <asyncio_redis.replies.StatusReply>`", # noqa: E501
ZRangeReply: ":class:`ZRangeReply <asyncio_redis.replies.ZRangeReply>`", # noqa: E501
ZScoreBoundary: ":class:`ZScoreBoundary <asyncio_redis.ZScoreBoundary>`", # noqa: E501
EvalScriptReply: ":class:`EvalScriptReply <asyncio_redis.replies.EvalScriptReply>`", # noqa: E501
Cursor: ":class:`Cursor <asyncio_redis.cursors.Cursor>`",
SetCursor: ":class:`SetCursor <asyncio_redis.cursors.SetCursor>`",
DictCursor: ":class:`DictCursor <asyncio_redis.cursors.DictCursor>`", # noqa: E501
ZCursor: ":class:`ZCursor <asyncio_redis.cursors.ZCursor>`",
_ScanPart: ":class:`_ScanPart",
int: "int",
bool: "bool",
dict: "dict",
float: "float",
str: "str",
bytes: "bytes",
list: "list",
set: "set",
# Because of circular references, we cannot use the real types here.
"Transaction": ":class:`asyncio_redis.Transaction`",
"Subscription": ":class:`asyncio_redis.Subscription`",
"Script": ":class:`~asyncio_redis.Script`",
}[type_]
except KeyError:
if isinstance(type_, ListOf):
return "List or iterable of %s" % get_name(type_.type)
if isinstance(type_, tuple):
return " or ".join(get_name(t) for t in type_)
raise TypeError("Unknown annotation %r" % type_)
def get_param(k, v):
return ":param %s: %s\n" % (k, get_name(v))
params_str = [get_param(k, v) for k, v in self.params.items()]
returns = (
":returns: (Future of) %s\n" % get_name(return_type) if return_type else ""
)
return "%s(%s)\n%s\n\n%s%s" % (
self.method.__name__ + suffix,
", ".join(argnames),
self.method.__doc__,
"".join(params_str),
returns,
)
def get_methods(self):
"""Return all the methods to be used in the RedisProtocol class.
"""
return [("", self._get_wrapped_method(None, "", self.return_type))]
def _get_wrapped_method(self, post_process, suffix, return_type):
"""Return the wrapped method for use in the `RedisProtocol` class.
"""
typecheck_input = self._create_input_typechecker()
typecheck_return = self._create_return_typechecker(return_type)
method = self.method
# Wrap it into a check which allows this command to be run either
# directly on the protocol, outside of transactions or from the
# transaction object.
@wraps(method)
async def wrapper(protocol_self, *a, **kw):
if a and isinstance(a[0], (Transaction, _NoTransactionType)):
transaction = a[0]
a = a[1:]
else:
transaction = _NoTransaction
# When calling from a transaction
if transaction != _NoTransaction:
# In case of a transaction, we receive a Future from the command.
typecheck_input(protocol_self, *a, **kw)
future = await method(protocol_self, transaction, *a, **kw)
future2 = asyncio.Future()
# Typecheck the future when the result is available.
async def done(result):
if post_process:
result = await post_process(protocol_self, result)
typecheck_return(protocol_self, result)
future2.set_result(result)
loop = asyncio.get_event_loop()
future.add_done_callback(lambda f: loop.create_task(done(f.result())))
return future2
# When calling from a pubsub context
elif protocol_self.in_pubsub:
if not a or a[0] != protocol_self._subscription:
raise Error("Cannot run command inside pubsub subscription.")
else:
typecheck_input(protocol_self, *a[1:], **kw)
result = await method(protocol_self, _NoTransaction, *a[1:], **kw)
if post_process:
result = await post_process(protocol_self, result)
typecheck_return(protocol_self, result)
return result
else:
typecheck_input(protocol_self, *a, **kw)
result = await method(protocol_self, _NoTransaction, *a, **kw)
if post_process:
result = await post_process(protocol_self, result)
typecheck_return(protocol_self, result)
return result
wrapper.__doc__ = self._get_docstring(suffix, return_type)
return wrapper
class QueryCommandCreator(CommandCreator):
"""Like `CommandCreator`, but for methods registered with `_query_command`.
This are the methods that cause commands to be send to the server.
Most of the commands get a reply from the server that needs to be post
processed to get the right Python type. We inspect here the
'returns'-annotation to determine the correct post processor.
"""
def get_methods(self):
# (Some commands, e.g. those that return a ListReply can generate
# multiple protocol methods. One that does return the ListReply, but
# also one with the 'aslist' suffix that returns a Python list.)
all_post_processors = PostProcessors.get_all(self.return_type)
result = []
for suffix, return_type, post_processor in all_post_processors:
result.append(
(suffix, self._get_wrapped_method(post_processor, suffix, return_type))
)
return result
_SMALL_INTS = list(str(i).encode("ascii") for i in range(1000))
# List of all command methods.
_all_commands = []
class _command:
"""Mark method as command (to be passed through CommandCreator for the
creation of a protocol method)
"""
creator = CommandCreator
def __init__(self, method):
self.method = method
class _query_command(_command):
"""Mark method as query command: This will pass through QueryCommandCreator.
.. note::
Be sure to choose the correct 'returns'-annotation. This will automatically
determine the correct post processor function in :class:`PostProcessors`.
"""
creator = QueryCommandCreator
def __init__(self, method):
super().__init__(method)
class _RedisProtocolMeta(type):
"""Metaclass for `RedisProtocol` which applies the _command decorator.
"""
def __new__(cls, name, bases, attrs):
for attr_name, value in dict(attrs).items():
if isinstance(value, _command):
creator = value.creator(value.method)
for suffix, method in creator.get_methods():
attrs[attr_name + suffix] = method
# Register command.
_all_commands.append(attr_name + suffix)
return type.__new__(cls, name, bases, attrs)
class RedisProtocol(asyncio.Protocol, metaclass=_RedisProtocolMeta):
"""The Redis Protocol implementation.
::
loop = asyncio.get_event_loop()
transport, protocol = await loop.create_connection(
RedisProtocol, 'localhost', 6379
)
:param password:
Redis database password
:type password:
Native Python type as defined by the ``encoder`` parameter
:param encoder:
Encoder to use for encoding to or decoding from redis bytes to a native type.
(Defaults to :class:`~asyncio_redis.encoders.UTF8Encoder`)
:type encoder:
:class:`~asyncio_redis.encoders.BaseEncoder` instance.
:param int db:
Redis database
:param bool enable_typechecking:
When True, check argument types for all redis commands.
Normally you want to have this enabled.
"""
def __init__(
self,
*,
password=None,
db=0,
encoder=None,
connection_lost_callback=None,
enable_typechecking=True,
):
if encoder is None:
encoder = UTF8Encoder()
assert isinstance(db, int)
assert isinstance(encoder, BaseEncoder)
assert encoder.native_type, "Encoder.native_type not defined"
assert not password or isinstance(password, encoder.native_type)
self.password = password
self.db = db
self._connection_lost_callback = connection_lost_callback
# Take encode / decode settings from encoder
self.encode_from_native = encoder.encode_from_native
self.decode_to_native = encoder.decode_to_native
self.native_type = encoder.native_type
self.enable_typechecking = enable_typechecking
self.transport = None
self._queue = deque() # Input parser queues
self._messages_queue = None # Pubsub queue
self._is_connected = (
False # True as long as the underlying transport is connected.
)
# Pubsub state
self._in_pubsub = False
self._subscription = None
self._pubsub_channels = set() # Set of channels
self._pubsub_patterns = set() # Set of patterns
# Transaction related stuff.
self._transaction_lock = asyncio.Lock()
self._transaction = None
self._transaction_response_queue = None # Transaction answer queue
self._line_received_handlers = {
b"+": self._handle_status_reply,
b"-": self._handle_error_reply,
b"$": self._handle_bulk_reply,
b"*": self._handle_multi_bulk_reply,
b":": self._handle_int_reply,
}
def connection_made(self, transport):
self.transport = transport
self._is_connected = True
logger.log(logging.INFO, "Redis connection made")
# Pipelined calls
self._pipelined_calls = set() # Set of all the pipelined calls.
# Start parsing reader stream.
self._reader = asyncio.StreamReader()
self._reader.set_transport(transport)
self._reader_f = asyncio.get_event_loop().create_task(self._reader_coroutine())
async def initialize():
# If a password or database was been given, first connect to that one.
if self.password:
await self.auth(self.password)
if self.db:
await self.select(self.db)
# If we are in pubsub mode, send channel subscriptions again.
if self._in_pubsub:
if self._pubsub_channels:
await self._subscribe(
self._subscription, list(self._pubsub_channels)
) # TODO: unittest this
if self._pubsub_patterns:
await self._psubscribe(
self._subscription, list(self._pubsub_patterns)
)
loop = asyncio.get_event_loop()
loop.create_task(initialize())
def data_received(self, data):
"""Process data received from Redis server
"""
self._reader.feed_data(data)
def _encode_int(self, value: int) -> bytes:
"""Encodes an integer to bytes. (always ascii)
"""
if 0 < value < 1000: # For small values, take pre-encoded string.
return _SMALL_INTS[value]
else:
return str(value).encode("ascii")
def _encode_float(self, value: float) -> bytes:
"""Encodes a float to bytes. (always ascii)
"""
return str(value).encode("ascii")
def _encode_zscore_boundary(self, value: ZScoreBoundary) -> str:
"""Encodes a zscore boundary. (always ascii)
"""
if isinstance(value.value, str):
return str(value.value).encode("ascii") # +inf and -inf
elif value.exclude_boundary:
return str("(%f" % value.value).encode("ascii")
else:
return str("%f" % value.value).encode("ascii")
def eof_received(self):
logger.log(logging.INFO, "EOF received in RedisProtocol")
self._reader.feed_eof()
def connection_lost(self, exc):
if exc is None:
self._reader.feed_eof()
else:
logger.info("Connection lost with exec: %s" % exc)
self._reader.set_exception(exc)
if self._reader_f:
self._reader_f.cancel()
self._is_connected = False
self.transport = None
self._reader = None
self._reader_f = None
# Raise exception on all waiting futures.
while self._queue:
f = self._queue.popleft()
if not f.cancelled():
f.set_exception(ConnectionLostError(exc))
logger.log(logging.INFO, "Redis connection lost")
# Call connection_lost callback
if self._connection_lost_callback:
self._connection_lost_callback()
# Request state
@property
def in_blocking_call(self):
"""True when waiting for answer to blocking command
"""
return any(c.is_blocking for c in self._pipelined_calls)
@property
def in_pubsub(self):
"""True when the protocol is in pubsub mode
"""
return self._in_pubsub
@property
def in_transaction(self):
"""True when we're inside a transaction
"""
return bool(self._transaction)
@property
def in_use(self):
"""True when this protocol is in use
"""
return self.in_blocking_call or self.in_pubsub or self.in_transaction
@property
def is_connected(self):
"""True when the underlying transport is connected
"""
return self._is_connected
# Handle replies
async def _reader_coroutine(self):
"""Coroutine which reads input from the stream reader and processes it.
"""
while True:
try:
await self._handle_item(self._push_answer)
except ConnectionLostError:
return
except asyncio.IncompleteReadError:
return
async def _handle_item(self, cb):
c = await self._reader.readexactly(1)
if c:
await self._line_received_handlers[c](cb)
else:
raise ConnectionLostError(None)
async def _handle_status_reply(self, cb):
line = (await self._reader.readline()).rstrip(b"\r\n")
cb(line)
async def _handle_int_reply(self, cb):
line = (await self._reader.readline()).rstrip(b"\r\n")
cb(int(line))
async def _handle_error_reply(self, cb):
line = (await self._reader.readline()).rstrip(b"\r\n")
cb(ErrorReply(line.decode("ascii")))
async def _handle_bulk_reply(self, cb):
length = int((await self._reader.readline()).rstrip(b"\r\n"))
if length == -1:
# None bulk reply
cb(None)
else:
# Read data
data = await self._reader.readexactly(length)
cb(data)
# Ignore trailing newline.
remaining = await self._reader.readline()
assert remaining.rstrip(b"\r\n") == b""
async def _handle_multi_bulk_reply(self, cb):
# NOTE: the reason for passing the callback `cb` in here is
# mainly because we want to return the result object
# especially in this case before the input is read
# completely. This allows a streaming API.