client_ws.py 11 KB

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