resp3.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. from logging import getLogger
  2. from typing import Any, Union
  3. from ..exceptions import ConnectionError, InvalidResponse, ResponseError
  4. from ..typing import EncodableT
  5. from .base import _AsyncRESPBase, _RESPBase
  6. from .socket import SERVER_CLOSED_CONNECTION_ERROR
  7. class _RESP3Parser(_RESPBase):
  8. """RESP3 protocol implementation"""
  9. def __init__(self, socket_read_size):
  10. super().__init__(socket_read_size)
  11. self.push_handler_func = self.handle_push_response
  12. def handle_push_response(self, response):
  13. logger = getLogger("push_response")
  14. logger.info("Push response: " + str(response))
  15. return response
  16. def read_response(self, disable_decoding=False, push_request=False):
  17. pos = self._buffer.get_pos() if self._buffer else None
  18. try:
  19. result = self._read_response(
  20. disable_decoding=disable_decoding, push_request=push_request
  21. )
  22. except BaseException:
  23. if self._buffer:
  24. self._buffer.rewind(pos)
  25. raise
  26. else:
  27. self._buffer.purge()
  28. return result
  29. def _read_response(self, disable_decoding=False, push_request=False):
  30. raw = self._buffer.readline()
  31. if not raw:
  32. raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
  33. byte, response = raw[:1], raw[1:]
  34. # server returned an error
  35. if byte in (b"-", b"!"):
  36. if byte == b"!":
  37. response = self._buffer.read(int(response))
  38. response = response.decode("utf-8", errors="replace")
  39. error = self.parse_error(response)
  40. # if the error is a ConnectionError, raise immediately so the user
  41. # is notified
  42. if isinstance(error, ConnectionError):
  43. raise error
  44. # otherwise, we're dealing with a ResponseError that might belong
  45. # inside a pipeline response. the connection's read_response()
  46. # and/or the pipeline's execute() will raise this error if
  47. # necessary, so just return the exception instance here.
  48. return error
  49. # single value
  50. elif byte == b"+":
  51. pass
  52. # null value
  53. elif byte == b"_":
  54. return None
  55. # int and big int values
  56. elif byte in (b":", b"("):
  57. return int(response)
  58. # double value
  59. elif byte == b",":
  60. return float(response)
  61. # bool value
  62. elif byte == b"#":
  63. return response == b"t"
  64. # bulk response
  65. elif byte == b"$":
  66. response = self._buffer.read(int(response))
  67. # verbatim string response
  68. elif byte == b"=":
  69. response = self._buffer.read(int(response))[4:]
  70. # array response
  71. elif byte == b"*":
  72. response = [
  73. self._read_response(disable_decoding=disable_decoding)
  74. for _ in range(int(response))
  75. ]
  76. # set response
  77. elif byte == b"~":
  78. # redis can return unhashable types (like dict) in a set,
  79. # so we need to first convert to a list, and then try to convert it to a set
  80. response = [
  81. self._read_response(disable_decoding=disable_decoding)
  82. for _ in range(int(response))
  83. ]
  84. try:
  85. response = set(response)
  86. except TypeError:
  87. pass
  88. # map response
  89. elif byte == b"%":
  90. # we use this approach and not dict comprehension here
  91. # because this dict comprehension fails in python 3.7
  92. resp_dict = {}
  93. for _ in range(int(response)):
  94. key = self._read_response(disable_decoding=disable_decoding)
  95. resp_dict[key] = self._read_response(
  96. disable_decoding=disable_decoding, push_request=push_request
  97. )
  98. response = resp_dict
  99. # push response
  100. elif byte == b">":
  101. response = [
  102. self._read_response(
  103. disable_decoding=disable_decoding, push_request=push_request
  104. )
  105. for _ in range(int(response))
  106. ]
  107. res = self.push_handler_func(response)
  108. if not push_request:
  109. return self._read_response(
  110. disable_decoding=disable_decoding, push_request=push_request
  111. )
  112. else:
  113. return res
  114. else:
  115. raise InvalidResponse(f"Protocol Error: {raw!r}")
  116. if isinstance(response, bytes) and disable_decoding is False:
  117. response = self.encoder.decode(response)
  118. return response
  119. def set_push_handler(self, push_handler_func):
  120. self.push_handler_func = push_handler_func
  121. class _AsyncRESP3Parser(_AsyncRESPBase):
  122. def __init__(self, socket_read_size):
  123. super().__init__(socket_read_size)
  124. self.push_handler_func = self.handle_push_response
  125. def handle_push_response(self, response):
  126. logger = getLogger("push_response")
  127. logger.info("Push response: " + str(response))
  128. return response
  129. async def read_response(
  130. self, disable_decoding: bool = False, push_request: bool = False
  131. ):
  132. if self._chunks:
  133. # augment parsing buffer with previously read data
  134. self._buffer += b"".join(self._chunks)
  135. self._chunks.clear()
  136. self._pos = 0
  137. response = await self._read_response(
  138. disable_decoding=disable_decoding, push_request=push_request
  139. )
  140. # Successfully parsing a response allows us to clear our parsing buffer
  141. self._clear()
  142. return response
  143. async def _read_response(
  144. self, disable_decoding: bool = False, push_request: bool = False
  145. ) -> Union[EncodableT, ResponseError, None]:
  146. if not self._stream or not self.encoder:
  147. raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
  148. raw = await self._readline()
  149. response: Any
  150. byte, response = raw[:1], raw[1:]
  151. # if byte not in (b"-", b"+", b":", b"$", b"*"):
  152. # raise InvalidResponse(f"Protocol Error: {raw!r}")
  153. # server returned an error
  154. if byte in (b"-", b"!"):
  155. if byte == b"!":
  156. response = await self._read(int(response))
  157. response = response.decode("utf-8", errors="replace")
  158. error = self.parse_error(response)
  159. # if the error is a ConnectionError, raise immediately so the user
  160. # is notified
  161. if isinstance(error, ConnectionError):
  162. self._clear() # Successful parse
  163. raise error
  164. # otherwise, we're dealing with a ResponseError that might belong
  165. # inside a pipeline response. the connection's read_response()
  166. # and/or the pipeline's execute() will raise this error if
  167. # necessary, so just return the exception instance here.
  168. return error
  169. # single value
  170. elif byte == b"+":
  171. pass
  172. # null value
  173. elif byte == b"_":
  174. return None
  175. # int and big int values
  176. elif byte in (b":", b"("):
  177. return int(response)
  178. # double value
  179. elif byte == b",":
  180. return float(response)
  181. # bool value
  182. elif byte == b"#":
  183. return response == b"t"
  184. # bulk response
  185. elif byte == b"$":
  186. response = await self._read(int(response))
  187. # verbatim string response
  188. elif byte == b"=":
  189. response = (await self._read(int(response)))[4:]
  190. # array response
  191. elif byte == b"*":
  192. response = [
  193. (await self._read_response(disable_decoding=disable_decoding))
  194. for _ in range(int(response))
  195. ]
  196. # set response
  197. elif byte == b"~":
  198. # redis can return unhashable types (like dict) in a set,
  199. # so we need to first convert to a list, and then try to convert it to a set
  200. response = [
  201. (await self._read_response(disable_decoding=disable_decoding))
  202. for _ in range(int(response))
  203. ]
  204. try:
  205. response = set(response)
  206. except TypeError:
  207. pass
  208. # map response
  209. elif byte == b"%":
  210. response = {
  211. (await self._read_response(disable_decoding=disable_decoding)): (
  212. await self._read_response(disable_decoding=disable_decoding)
  213. )
  214. for _ in range(int(response))
  215. }
  216. # push response
  217. elif byte == b">":
  218. response = [
  219. (
  220. await self._read_response(
  221. disable_decoding=disable_decoding, push_request=push_request
  222. )
  223. )
  224. for _ in range(int(response))
  225. ]
  226. res = self.push_handler_func(response)
  227. if not push_request:
  228. return await self._read_response(
  229. disable_decoding=disable_decoding, push_request=push_request
  230. )
  231. else:
  232. return res
  233. else:
  234. raise InvalidResponse(f"Protocol Error: {raw!r}")
  235. if isinstance(response, bytes) and disable_decoding is False:
  236. response = self.encoder.decode(response)
  237. return response
  238. def set_push_handler(self, push_handler_func):
  239. self.push_handler_func = push_handler_func