You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

278 lines
9.8 KiB

4 years ago
  1. """WebSocket client for asyncio."""
  2. import asyncio
  3. from typing import Any, Optional
  4. import async_timeout
  5. from .client_exceptions import ClientError
  6. from .helpers import call_later, set_result
  7. from .http import (WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE, WebSocketError,
  8. WSMessage, WSMsgType)
  9. from .streams import EofStream
  10. from .typedefs import (DEFAULT_JSON_DECODER, DEFAULT_JSON_ENCODER, Byteish,
  11. JSONDecoder, JSONEncoder)
  12. class ClientWebSocketResponse:
  13. def __init__(self, reader, writer, protocol,
  14. response, timeout, autoclose, autoping, loop, *,
  15. receive_timeout=None, heartbeat=None,
  16. compress=0, client_notakeover=False):
  17. self._response = response
  18. self._conn = response.connection
  19. self._writer = writer
  20. self._reader = reader
  21. self._protocol = protocol
  22. self._closed = False
  23. self._closing = False
  24. self._close_code = None
  25. self._timeout = timeout
  26. self._receive_timeout = receive_timeout
  27. self._autoclose = autoclose
  28. self._autoping = autoping
  29. self._heartbeat = heartbeat
  30. self._heartbeat_cb = None
  31. if heartbeat is not None:
  32. self._pong_heartbeat = heartbeat / 2.0
  33. self._pong_response_cb = None
  34. self._loop = loop
  35. self._waiting = None
  36. self._exception = None
  37. self._compress = compress
  38. self._client_notakeover = client_notakeover
  39. self._reset_heartbeat()
  40. def _cancel_heartbeat(self):
  41. if self._pong_response_cb is not None:
  42. self._pong_response_cb.cancel()
  43. self._pong_response_cb = None
  44. if self._heartbeat_cb is not None:
  45. self._heartbeat_cb.cancel()
  46. self._heartbeat_cb = None
  47. def _reset_heartbeat(self):
  48. self._cancel_heartbeat()
  49. if self._heartbeat is not None:
  50. self._heartbeat_cb = call_later(
  51. self._send_heartbeat, self._heartbeat, self._loop)
  52. def _send_heartbeat(self):
  53. if self._heartbeat is not None and not self._closed:
  54. # fire-and-forget a task is not perfect but maybe ok for
  55. # sending ping. Otherwise we need a long-living heartbeat
  56. # task in the class.
  57. self._loop.create_task(self._writer.ping())
  58. if self._pong_response_cb is not None:
  59. self._pong_response_cb.cancel()
  60. self._pong_response_cb = call_later(
  61. self._pong_not_received, self._pong_heartbeat, self._loop)
  62. def _pong_not_received(self):
  63. if not self._closed:
  64. self._closed = True
  65. self._close_code = 1006
  66. self._exception = asyncio.TimeoutError()
  67. self._response.close()
  68. @property
  69. def closed(self) -> bool:
  70. return self._closed
  71. @property
  72. def close_code(self) -> Optional[int]:
  73. return self._close_code
  74. @property
  75. def protocol(self):
  76. return self._protocol
  77. @property
  78. def compress(self) -> int:
  79. return self._compress
  80. @property
  81. def client_notakeover(self) -> bool:
  82. return self._client_notakeover
  83. def get_extra_info(self, name: str, default: Any=None):
  84. """extra info from connection transport"""
  85. try:
  86. return self._response.connection.transport.get_extra_info(
  87. name, default)
  88. except Exception:
  89. return default
  90. def exception(self) -> Optional[BaseException]:
  91. return self._exception
  92. async def ping(self, message: bytes=b'') -> None:
  93. await self._writer.ping(message)
  94. async def pong(self, message: bytes=b'') -> None:
  95. await self._writer.pong(message)
  96. async def send_str(self, data: str,
  97. compress: Optional[int]=None) -> None:
  98. if not isinstance(data, str):
  99. raise TypeError('data argument must be str (%r)' % type(data))
  100. await self._writer.send(data, binary=False, compress=compress)
  101. async def send_bytes(self, data: Byteish,
  102. compress: Optional[int]=None) -> None:
  103. if not isinstance(data, (bytes, bytearray, memoryview)):
  104. raise TypeError('data argument must be byte-ish (%r)' %
  105. type(data))
  106. await self._writer.send(data, binary=True, compress=compress)
  107. async def send_json(self, data: Any,
  108. compress: Optional[int]=None,
  109. *, dumps: JSONEncoder=DEFAULT_JSON_ENCODER) -> None:
  110. await self.send_str(dumps(data), compress=compress)
  111. async def close(self, *, code: int=1000, message: bytes=b''):
  112. # we need to break `receive()` cycle first,
  113. # `close()` may be called from different task
  114. if self._waiting is not None and not self._closed:
  115. self._reader.feed_data(WS_CLOSING_MESSAGE, 0)
  116. await self._waiting
  117. if not self._closed:
  118. self._cancel_heartbeat()
  119. self._closed = True
  120. try:
  121. await self._writer.close(code, message)
  122. except asyncio.CancelledError:
  123. self._close_code = 1006
  124. self._response.close()
  125. raise
  126. except Exception as exc:
  127. self._close_code = 1006
  128. self._exception = exc
  129. self._response.close()
  130. return True
  131. if self._closing:
  132. self._response.close()
  133. return True
  134. while True:
  135. try:
  136. with async_timeout.timeout(self._timeout, loop=self._loop):
  137. msg = await self._reader.read()
  138. except asyncio.CancelledError:
  139. self._close_code = 1006
  140. self._response.close()
  141. raise
  142. except Exception as exc:
  143. self._close_code = 1006
  144. self._exception = exc
  145. self._response.close()
  146. return True
  147. if msg.type == WSMsgType.CLOSE:
  148. self._close_code = msg.data
  149. self._response.close()
  150. return True
  151. else:
  152. return False
  153. async def receive(self, timeout: Optional[float]=None) -> WSMessage:
  154. while True:
  155. if self._waiting is not None:
  156. raise RuntimeError(
  157. 'Concurrent call to receive() is not allowed')
  158. if self._closed:
  159. return WS_CLOSED_MESSAGE
  160. elif self._closing:
  161. await self.close()
  162. return WS_CLOSED_MESSAGE
  163. try:
  164. self._waiting = self._loop.create_future()
  165. try:
  166. with async_timeout.timeout(
  167. timeout or self._receive_timeout,
  168. loop=self._loop):
  169. msg = await self._reader.read()
  170. self._reset_heartbeat()
  171. finally:
  172. waiter = self._waiting
  173. self._waiting = None
  174. set_result(waiter, True)
  175. except (asyncio.CancelledError, asyncio.TimeoutError):
  176. self._close_code = 1006
  177. raise
  178. except EofStream:
  179. self._close_code = 1000
  180. await self.close()
  181. return WSMessage(WSMsgType.CLOSED, None, None)
  182. except ClientError:
  183. self._closed = True
  184. self._close_code = 1006
  185. return WS_CLOSED_MESSAGE
  186. except WebSocketError as exc:
  187. self._close_code = exc.code
  188. await self.close(code=exc.code)
  189. return WSMessage(WSMsgType.ERROR, exc, None)
  190. except Exception as exc:
  191. self._exception = exc
  192. self._closing = True
  193. self._close_code = 1006
  194. await self.close()
  195. return WSMessage(WSMsgType.ERROR, exc, None)
  196. if msg.type == WSMsgType.CLOSE:
  197. self._closing = True
  198. self._close_code = msg.data
  199. if not self._closed and self._autoclose:
  200. await self.close()
  201. elif msg.type == WSMsgType.CLOSING:
  202. self._closing = True
  203. elif msg.type == WSMsgType.PING and self._autoping:
  204. await self.pong(msg.data)
  205. continue
  206. elif msg.type == WSMsgType.PONG and self._autoping:
  207. continue
  208. return msg
  209. async def receive_str(self, *, timeout: Optional[float]=None) -> str:
  210. msg = await self.receive(timeout)
  211. if msg.type != WSMsgType.TEXT:
  212. raise TypeError(
  213. "Received message {}:{!r} is not str".format(msg.type,
  214. msg.data))
  215. return msg.data
  216. async def receive_bytes(self, *, timeout: Optional[float]=None) -> bytes:
  217. msg = await self.receive(timeout)
  218. if msg.type != WSMsgType.BINARY:
  219. raise TypeError(
  220. "Received message {}:{!r} is not bytes".format(msg.type,
  221. msg.data))
  222. return msg.data
  223. async def receive_json(self,
  224. *, loads: JSONDecoder=DEFAULT_JSON_DECODER,
  225. timeout: Optional[float]=None) -> Any:
  226. data = await self.receive_str(timeout=timeout)
  227. return loads(data)
  228. def __aiter__(self) -> 'ClientWebSocketResponse':
  229. return self
  230. async def __anext__(self) -> WSMessage:
  231. msg = await self.receive()
  232. if msg.type in (WSMsgType.CLOSE,
  233. WSMsgType.CLOSING,
  234. WSMsgType.CLOSED):
  235. raise StopAsyncIteration # NOQA
  236. return msg