Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/_parsers/resp3.py: 11%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from logging import getLogger
2from typing import Any, Union
4from ..exceptions import ConnectionError, InvalidResponse, ResponseError
5from ..typing import EncodableT
6from ..utils import SENTINEL
7from .base import (
8 AsyncPushNotificationsParser,
9 PushNotificationsParser,
10 _AsyncRESPBase,
11 _parse_float,
12 _parse_int,
13 _RESPBase,
14)
15from .socket import SERVER_CLOSED_CONNECTION_ERROR
18class _RESP3Parser(_RESPBase, PushNotificationsParser):
19 """RESP3 protocol implementation"""
21 def __init__(self, socket_read_size):
22 super().__init__(socket_read_size)
23 self.pubsub_push_handler_func = self.handle_pubsub_push_response
24 self.node_moving_push_handler_func = None
25 self.maintenance_push_handler_func = None
26 self.oss_cluster_maint_push_handler_func = None
27 self.invalidation_push_handler_func = None
29 def handle_pubsub_push_response(self, response):
30 logger = getLogger("push_response")
31 logger.debug("Push response: %s", response)
32 return response
34 def read_response(
35 self,
36 disable_decoding=False,
37 push_request=False,
38 timeout: Union[float, object] = SENTINEL,
39 ):
40 pos = self._buffer.get_pos() if self._buffer is not None else None
41 try:
42 result = self._read_response(
43 disable_decoding=disable_decoding,
44 push_request=push_request,
45 timeout=timeout,
46 )
47 except BaseException:
48 if self._buffer is not None:
49 self._buffer.rewind(pos)
50 raise
51 else:
52 if self._buffer is not None:
53 try:
54 self._buffer.purge()
55 except AttributeError:
56 # Buffer may have been set to None by another thread after
57 # the check above; result is still valid so we don't raise
58 pass
59 return result
61 def _read_response(
62 self,
63 disable_decoding=False,
64 push_request=False,
65 timeout: Union[float, object] = SENTINEL,
66 ):
67 while True:
68 raw = self._buffer.readline(timeout=timeout)
69 if not raw:
70 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
72 byte, response = raw[:1], raw[1:]
74 # server returned an error
75 if byte in (b"-", b"!"):
76 if byte == b"!":
77 response = self._buffer.read(
78 _parse_int(response, raw), timeout=timeout
79 )
80 response = response.decode("utf-8", errors="replace")
81 error = self.parse_error(response)
82 # if the error is a ConnectionError, raise immediately so the user
83 # is notified
84 if isinstance(error, ConnectionError):
85 raise error
86 # otherwise, we're dealing with a ResponseError that might belong
87 # inside a pipeline response. the connection's read_response()
88 # and/or the pipeline's execute() will raise this error if
89 # necessary, so just return the exception instance here.
90 return error
91 # single value
92 elif byte == b"+":
93 pass
94 # null value
95 elif byte == b"_":
96 return None
97 # int and big int values
98 elif byte in (b":", b"("):
99 return _parse_int(response, raw)
100 # double value
101 elif byte == b",":
102 return _parse_float(response, raw)
103 # bool value
104 elif byte == b"#":
105 return response == b"t"
106 # bulk response
107 elif byte == b"$":
108 response = self._buffer.read(_parse_int(response, raw), timeout=timeout)
109 # verbatim string response
110 elif byte == b"=":
111 response = self._buffer.read(
112 _parse_int(response, raw), timeout=timeout
113 )[4:]
114 # array response
115 elif byte == b"*":
116 response = [
117 self._read_response(
118 disable_decoding=disable_decoding, timeout=timeout
119 )
120 for _ in range(_parse_int(response, raw))
121 ]
122 # set response
123 elif byte == b"~":
124 # redis can return unhashable types (like dict) in a set,
125 # so we return sets as list, all the time, for predictability
126 response = [
127 self._read_response(
128 disable_decoding=disable_decoding, timeout=timeout
129 )
130 for _ in range(_parse_int(response, raw))
131 ]
132 # map response
133 elif byte == b"%":
134 # We cannot use a dict-comprehension to parse stream.
135 # Evaluation order of key:val expression in dict comprehension only
136 # became defined to be left-right in version 3.8
137 resp_dict = {}
138 for _ in range(_parse_int(response, raw)):
139 key = self._read_response(
140 disable_decoding=disable_decoding, timeout=timeout
141 )
142 resp_dict[key] = self._read_response(
143 disable_decoding=disable_decoding,
144 push_request=push_request,
145 timeout=timeout,
146 )
147 response = resp_dict
148 # push response
149 elif byte == b">":
150 response = [
151 self._read_response(
152 disable_decoding=disable_decoding,
153 push_request=push_request,
154 timeout=timeout,
155 )
156 for _ in range(_parse_int(response, raw))
157 ]
158 response = self.handle_push_response(response)
160 # if this is a push request return the push response
161 if push_request:
162 return response
164 # Otherwise read the reply the push interleaved with. Looping
165 # instead of recursing keeps a burst of consecutive push frames
166 # from growing the stack, and keeps `timeout`, the caller's bound
167 # for this whole read, in force for the rest of the response.
168 # A push handler may have disconnected, so check before reading on.
169 if self._buffer is None:
170 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
171 continue
172 else:
173 raise InvalidResponse(f"Protocol Error: {raw!r}")
175 if isinstance(response, bytes) and disable_decoding is False:
176 response = self.encoder.decode(response)
178 return response
181class _AsyncRESP3Parser(_AsyncRESPBase, AsyncPushNotificationsParser):
182 def __init__(self, socket_read_size):
183 super().__init__(socket_read_size)
184 self.pubsub_push_handler_func = self.handle_pubsub_push_response
185 self.invalidation_push_handler_func = None
187 async def handle_pubsub_push_response(self, response):
188 logger = getLogger("push_response")
189 logger.debug("Push response: %s", response)
190 return response
192 async def read_response(
193 self, disable_decoding: bool = False, push_request: bool = False
194 ):
195 if not self._connected:
196 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
197 if self._chunks:
198 # augment parsing buffer with previously read data
199 self._buffer += b"".join(self._chunks)
200 self._chunks.clear()
201 self._pos = 0
202 response = await self._read_response(
203 disable_decoding=disable_decoding, push_request=push_request
204 )
205 # Successfully parsing a response allows us to clear our parsing buffer
206 self._clear()
207 return response
209 async def _read_response(
210 self, disable_decoding: bool = False, push_request: bool = False
211 ) -> Union[EncodableT, ResponseError, None]:
212 while True:
213 if not self._stream or not self.encoder:
214 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
215 raw = await self._readline()
216 response: Any
217 byte, response = raw[:1], raw[1:]
219 # if byte not in (b"-", b"+", b":", b"$", b"*"):
220 # raise InvalidResponse(f"Protocol Error: {raw!r}")
222 # server returned an error
223 if byte in (b"-", b"!"):
224 if byte == b"!":
225 response = await self._read(_parse_int(response, raw))
226 response = response.decode("utf-8", errors="replace")
227 error = self.parse_error(response)
228 # if the error is a ConnectionError, raise immediately so the user
229 # is notified
230 if isinstance(error, ConnectionError):
231 self._clear() # Successful parse
232 raise error
233 # otherwise, we're dealing with a ResponseError that might belong
234 # inside a pipeline response. the connection's read_response()
235 # and/or the pipeline's execute() will raise this error if
236 # necessary, so just return the exception instance here.
237 return error
238 # single value
239 elif byte == b"+":
240 pass
241 # null value
242 elif byte == b"_":
243 return None
244 # int and big int values
245 elif byte in (b":", b"("):
246 return _parse_int(response, raw)
247 # double value
248 elif byte == b",":
249 return _parse_float(response, raw)
250 # bool value
251 elif byte == b"#":
252 return response == b"t"
253 # bulk response
254 elif byte == b"$":
255 response = await self._read(_parse_int(response, raw))
256 # verbatim string response
257 elif byte == b"=":
258 response = (await self._read(_parse_int(response, raw)))[4:]
259 # array response
260 elif byte == b"*":
261 response = [
262 (await self._read_response(disable_decoding=disable_decoding))
263 for _ in range(_parse_int(response, raw))
264 ]
265 # set response
266 elif byte == b"~":
267 # redis can return unhashable types (like dict) in a set,
268 # so we always convert to a list, to have predictable return types
269 response = [
270 (await self._read_response(disable_decoding=disable_decoding))
271 for _ in range(_parse_int(response, raw))
272 ]
273 # map response
274 elif byte == b"%":
275 # We cannot use a dict-comprehension to parse stream.
276 # Evaluation order of key:val expression in dict comprehension only
277 # became defined to be left-right in version 3.8
278 resp_dict = {}
279 for _ in range(_parse_int(response, raw)):
280 key = await self._read_response(disable_decoding=disable_decoding)
281 resp_dict[key] = await self._read_response(
282 disable_decoding=disable_decoding, push_request=push_request
283 )
284 response = resp_dict
285 # push response
286 elif byte == b">":
287 response = [
288 (
289 await self._read_response(
290 disable_decoding=disable_decoding, push_request=push_request
291 )
292 )
293 for _ in range(_parse_int(response, raw))
294 ]
295 response = await self.handle_push_response(response)
296 if push_request:
297 return response
298 # Otherwise read the reply the push interleaved with. Looping
299 # instead of recursing keeps a burst of consecutive push frames
300 # from growing the stack.
301 # A push handler may have disconnected, so check before reading on.
302 if not self._connected:
303 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
304 continue
305 else:
306 raise InvalidResponse(f"Protocol Error: {raw!r}")
308 if isinstance(response, bytes) and disable_decoding is False:
309 response = self.encoder.decode(response)
310 return response