client_ws.py 10 KB

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