connection.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. from __future__ import annotations
  2. import asyncio
  3. import collections
  4. import contextlib
  5. import logging
  6. import random
  7. import struct
  8. import sys
  9. import traceback
  10. import uuid
  11. from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping
  12. from types import TracebackType
  13. from typing import Any, Literal, cast, overload
  14. from ..exceptions import (
  15. ConcurrencyError,
  16. ConnectionClosed,
  17. ConnectionClosedOK,
  18. ProtocolError,
  19. )
  20. from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode
  21. from ..http11 import Request, Response
  22. from ..protocol import CLOSED, OPEN, Event, Protocol, State
  23. from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol
  24. from .compatibility import (
  25. TimeoutError,
  26. aiter,
  27. anext,
  28. asyncio_timeout,
  29. asyncio_timeout_at,
  30. )
  31. from .messages import Assembler
  32. __all__ = ["Connection"]
  33. class Connection(asyncio.Protocol):
  34. """
  35. :mod:`asyncio` implementation of a WebSocket connection.
  36. :class:`Connection` provides APIs shared between WebSocket servers and
  37. clients.
  38. You shouldn't use it directly. Instead, use
  39. :class:`~websockets.asyncio.client.ClientConnection` or
  40. :class:`~websockets.asyncio.server.ServerConnection`.
  41. """
  42. def __init__(
  43. self,
  44. protocol: Protocol,
  45. *,
  46. ping_interval: float | None = 20,
  47. ping_timeout: float | None = 20,
  48. close_timeout: float | None = 10,
  49. max_queue: int | None | tuple[int | None, int | None] = 16,
  50. write_limit: int | tuple[int, int | None] = 2**15,
  51. ) -> None:
  52. self.protocol = protocol
  53. self.ping_interval = ping_interval
  54. self.ping_timeout = ping_timeout
  55. self.close_timeout = close_timeout
  56. if isinstance(max_queue, int) or max_queue is None:
  57. self.max_queue_high, self.max_queue_low = max_queue, None
  58. else:
  59. self.max_queue_high, self.max_queue_low = max_queue
  60. if isinstance(write_limit, int):
  61. self.write_limit_high, self.write_limit_low = write_limit, None
  62. else:
  63. self.write_limit_high, self.write_limit_low = write_limit
  64. # Inject reference to this instance in the protocol's logger.
  65. self.protocol.logger = logging.LoggerAdapter(
  66. self.protocol.logger,
  67. {"websocket": self},
  68. )
  69. # Copy attributes from the protocol for convenience.
  70. self.id: uuid.UUID = self.protocol.id
  71. """Unique identifier of the connection. Useful in logs."""
  72. self.logger: LoggerLike = self.protocol.logger
  73. """Logger for this connection."""
  74. self.debug = self.protocol.debug
  75. # HTTP handshake request and response.
  76. self.request: Request | None = None
  77. """Opening handshake request."""
  78. self.response: Response | None = None
  79. """Opening handshake response."""
  80. # Event loop running this connection.
  81. self.loop = asyncio.get_running_loop()
  82. # Assembler turning frames into messages and serializing reads.
  83. self.recv_messages: Assembler # initialized in connection_made
  84. # Deadline for the closing handshake.
  85. self.close_deadline: float | None = None
  86. # Whether we are busy sending a fragmented message.
  87. self.send_in_progress: asyncio.Future[None] | None = None
  88. # Mapping of ping IDs to pong waiters, in chronological order.
  89. self.pending_pings: dict[bytes, tuple[asyncio.Future[float], float]] = {}
  90. self.latency: float = 0.0
  91. """
  92. Latency of the connection, in seconds.
  93. Latency is defined as the round-trip time of the connection. It is
  94. measured by sending a Ping frame and waiting for a matching Pong frame.
  95. Before the first measurement, :attr:`latency` is ``0.0``.
  96. By default, websockets enables a :ref:`keepalive <keepalive>` mechanism
  97. that sends Ping frames automatically at regular intervals. You can also
  98. send Ping frames and measure latency with :meth:`ping`.
  99. """
  100. # Task that sends keepalive pings. None when ping_interval is None.
  101. self.keepalive_task: asyncio.Task[None] | None = None
  102. # Exception raised while reading from the connection, to be chained to
  103. # ConnectionClosed in order to show why the TCP connection dropped.
  104. self.recv_exc: BaseException | None = None
  105. # Completed when the TCP connection is closed and the WebSocket
  106. # connection state becomes CLOSED.
  107. self.connection_lost_waiter: asyncio.Future[None] = self.loop.create_future()
  108. # Adapted from asyncio.FlowControlMixin.
  109. self.paused: bool = False
  110. self.drain_waiters: collections.deque[asyncio.Future[None]] = (
  111. collections.deque()
  112. )
  113. # Public attributes
  114. @property
  115. def local_address(self) -> Any:
  116. """
  117. Local address of the connection.
  118. For IPv4 connections, this is a ``(host, port)`` tuple.
  119. The format of the address depends on the address family.
  120. See :meth:`~socket.socket.getsockname`.
  121. """
  122. return self.transport.get_extra_info("sockname")
  123. @property
  124. def remote_address(self) -> Any:
  125. """
  126. Remote address of the connection.
  127. For IPv4 connections, this is a ``(host, port)`` tuple.
  128. The format of the address depends on the address family.
  129. See :meth:`~socket.socket.getpeername`.
  130. """
  131. return self.transport.get_extra_info("peername")
  132. @property
  133. def state(self) -> State:
  134. """
  135. State of the WebSocket connection, defined in :rfc:`6455`.
  136. This attribute is provided for completeness. Typical applications
  137. shouldn't check its value. Instead, they should call :meth:`~recv` or
  138. :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed`
  139. exceptions.
  140. """
  141. return self.protocol.state
  142. @property
  143. def subprotocol(self) -> Subprotocol | None:
  144. """
  145. Subprotocol negotiated during the opening handshake.
  146. :obj:`None` if no subprotocol was negotiated.
  147. """
  148. return self.protocol.subprotocol
  149. @property
  150. def close_code(self) -> int | None:
  151. """
  152. State of the WebSocket connection, defined in :rfc:`6455`.
  153. This attribute is provided for completeness. Typical applications
  154. shouldn't check its value. Instead, they should inspect attributes
  155. of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
  156. """
  157. return self.protocol.close_code
  158. @property
  159. def close_reason(self) -> str | None:
  160. """
  161. State of the WebSocket connection, defined in :rfc:`6455`.
  162. This attribute is provided for completeness. Typical applications
  163. shouldn't check its value. Instead, they should inspect attributes
  164. of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
  165. """
  166. return self.protocol.close_reason
  167. # Public methods
  168. async def __aenter__(self) -> Connection:
  169. return self
  170. async def __aexit__(
  171. self,
  172. exc_type: type[BaseException] | None,
  173. exc_value: BaseException | None,
  174. traceback: TracebackType | None,
  175. ) -> None:
  176. if exc_type is None:
  177. await self.close()
  178. else:
  179. await self.close(CloseCode.INTERNAL_ERROR)
  180. async def __aiter__(self) -> AsyncIterator[Data]:
  181. """
  182. Iterate on incoming messages.
  183. The iterator calls :meth:`recv` and yields messages asynchronously in an
  184. infinite loop.
  185. It exits when the connection is closed normally. It raises a
  186. :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
  187. protocol error or a network failure.
  188. """
  189. try:
  190. while True:
  191. yield await self.recv()
  192. except ConnectionClosedOK:
  193. return
  194. @overload
  195. async def recv(self, decode: Literal[True]) -> str: ...
  196. @overload
  197. async def recv(self, decode: Literal[False]) -> bytes: ...
  198. @overload
  199. async def recv(self, decode: bool | None = None) -> Data: ...
  200. async def recv(self, decode: bool | None = None) -> Data:
  201. """
  202. Receive the next message.
  203. When the connection is closed, :meth:`recv` raises
  204. :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
  205. :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure
  206. and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
  207. error or a network failure. This is how you detect the end of the
  208. message stream.
  209. Canceling :meth:`recv` is safe. There's no risk of losing data. The next
  210. invocation of :meth:`recv` will return the next message.
  211. This makes it possible to enforce a timeout by wrapping :meth:`recv` in
  212. :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
  213. When the message is fragmented, :meth:`recv` waits until all fragments
  214. are received, reassembles them, and returns the whole message.
  215. Args:
  216. decode: Set this flag to override the default behavior of returning
  217. :class:`str` or :class:`bytes`. See below for details.
  218. Returns:
  219. A string (:class:`str`) for a Text_ frame or a bytestring
  220. (:class:`bytes`) for a Binary_ frame.
  221. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  222. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  223. You may override this behavior with the ``decode`` argument:
  224. * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
  225. return a bytestring (:class:`bytes`). This improves performance
  226. when decoding isn't needed, for example if the message contains
  227. JSON and you're using a JSON library that expects a bytestring.
  228. * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and
  229. return strings (:class:`str`). This may be useful for servers that
  230. send binary frames instead of text frames.
  231. Raises:
  232. ConnectionClosed: When the connection is closed.
  233. ConcurrencyError: If two coroutines call :meth:`recv` or
  234. :meth:`recv_streaming` concurrently.
  235. """
  236. try:
  237. return await self.recv_messages.get(decode)
  238. except EOFError:
  239. pass
  240. # fallthrough
  241. except ConcurrencyError:
  242. raise ConcurrencyError(
  243. "cannot call recv while another coroutine "
  244. "is already running recv or recv_streaming"
  245. ) from None
  246. except UnicodeDecodeError as exc:
  247. async with self.send_context():
  248. self.protocol.fail(
  249. CloseCode.INVALID_DATA,
  250. f"{exc.reason} at position {exc.start}",
  251. )
  252. # fallthrough
  253. # Wait for the protocol state to be CLOSED before accessing close_exc.
  254. await asyncio.shield(self.connection_lost_waiter)
  255. raise self.protocol.close_exc from self.recv_exc
  256. @overload
  257. def recv_streaming(self, decode: Literal[True]) -> AsyncIterator[str]: ...
  258. @overload
  259. def recv_streaming(self, decode: Literal[False]) -> AsyncIterator[bytes]: ...
  260. @overload
  261. def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: ...
  262. async def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]:
  263. """
  264. Receive the next message frame by frame.
  265. This method is designed for receiving fragmented messages. It returns an
  266. asynchronous iterator that yields each fragment as it is received. This
  267. iterator must be fully consumed. Else, future calls to :meth:`recv` or
  268. :meth:`recv_streaming` will raise
  269. :exc:`~websockets.exceptions.ConcurrencyError`, making the connection
  270. unusable.
  271. :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.
  272. Canceling :meth:`recv_streaming` before receiving the first frame is
  273. safe. Canceling it after receiving one or more frames leaves the
  274. iterator in a partially consumed state, making the connection unusable.
  275. Instead, you should close the connection with :meth:`close`.
  276. Args:
  277. decode: Set this flag to override the default behavior of returning
  278. :class:`str` or :class:`bytes`. See below for details.
  279. Returns:
  280. An iterator of strings (:class:`str`) for a Text_ frame or
  281. bytestrings (:class:`bytes`) for a Binary_ frame.
  282. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  283. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  284. You may override this behavior with the ``decode`` argument:
  285. * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
  286. yield bytestrings (:class:`bytes`). This improves performance
  287. when decoding isn't needed.
  288. * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and
  289. yield strings (:class:`str`). This may be useful for servers that
  290. send binary frames instead of text frames.
  291. Raises:
  292. ConnectionClosed: When the connection is closed.
  293. ConcurrencyError: If two coroutines call :meth:`recv` or
  294. :meth:`recv_streaming` concurrently.
  295. """
  296. try:
  297. async for frame in self.recv_messages.get_iter(decode):
  298. yield frame
  299. return
  300. except EOFError:
  301. pass
  302. # fallthrough
  303. except ConcurrencyError:
  304. raise ConcurrencyError(
  305. "cannot call recv_streaming while another coroutine "
  306. "is already running recv or recv_streaming"
  307. ) from None
  308. except UnicodeDecodeError as exc:
  309. async with self.send_context():
  310. self.protocol.fail(
  311. CloseCode.INVALID_DATA,
  312. f"{exc.reason} at position {exc.start}",
  313. )
  314. # fallthrough
  315. # Wait for the protocol state to be CLOSED before accessing close_exc.
  316. await asyncio.shield(self.connection_lost_waiter)
  317. raise self.protocol.close_exc from self.recv_exc
  318. async def send(
  319. self,
  320. message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike],
  321. text: bool | None = None,
  322. ) -> None:
  323. """
  324. Send a message.
  325. A string (:class:`str`) is sent as a Text_ frame. A bytestring or
  326. bytes-like object (:class:`bytes`, :class:`bytearray`, or
  327. :class:`memoryview`) is sent as a Binary_ frame.
  328. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  329. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  330. You may override this behavior with the ``text`` argument:
  331. * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object
  332. (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a
  333. Text_ frame. This improves performance when the message is already
  334. UTF-8 encoded, for example if the message contains JSON and you're
  335. using a JSON library that produces a bytestring.
  336. * Set ``text=False`` to send a string (:class:`str`) in a Binary_
  337. frame. This may be useful for servers that expect binary frames
  338. instead of text frames.
  339. :meth:`send` also accepts an iterable or asynchronous iterable of
  340. strings, bytestrings, or bytes-like objects to enable fragmentation_.
  341. Each item is treated as a message fragment and sent in its own frame.
  342. All items must be of the same type, or else :meth:`send` will raise a
  343. :exc:`TypeError` and the connection will be closed.
  344. .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
  345. :meth:`send` rejects dict-like objects because this is often an error.
  346. (If you really want to send the keys of a dict-like object as fragments,
  347. call its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
  348. Canceling :meth:`send` is discouraged. Instead, you should close the
  349. connection with :meth:`close`. Indeed, there are only two situations
  350. where :meth:`send` may yield control to the event loop and then get
  351. canceled; in both cases, :meth:`close` has the same effect and the
  352. effect is more obvious:
  353. 1. The write buffer is full. If you don't want to wait until enough
  354. data is sent, your only alternative is to close the connection.
  355. :meth:`close` will likely time out then abort the TCP connection.
  356. 2. ``message`` is an asynchronous iterator that yields control.
  357. Stopping in the middle of a fragmented message will cause a
  358. protocol error and the connection will be closed.
  359. When the connection is closed, :meth:`send` raises
  360. :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
  361. raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
  362. connection closure and
  363. :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
  364. error or a network failure.
  365. Args:
  366. message: Message to send.
  367. text: Force sending in a Text_ or Binary_ frame.
  368. Raises:
  369. ConnectionClosed: When the connection is closed.
  370. TypeError: If ``message`` doesn't have a supported type.
  371. """
  372. # While sending a fragmented message, prevent sending other messages
  373. # until all fragments are sent.
  374. while self.send_in_progress is not None:
  375. await asyncio.shield(self.send_in_progress)
  376. # Unfragmented message -- this case must be handled first because
  377. # strings and bytes-like objects are iterable.
  378. if isinstance(message, str):
  379. async with self.send_context():
  380. if text is False:
  381. self.protocol.send_binary(message.encode())
  382. else:
  383. self.protocol.send_text(message.encode())
  384. elif isinstance(message, BytesLike):
  385. async with self.send_context():
  386. if text is True:
  387. self.protocol.send_text(message)
  388. else:
  389. self.protocol.send_binary(message)
  390. # Catch a common mistake -- passing a dict to send().
  391. elif isinstance(message, Mapping):
  392. raise TypeError("data is a dict-like object")
  393. # Fragmented message -- regular iterator.
  394. elif isinstance(message, Iterable):
  395. chunks = iter(message)
  396. try:
  397. chunk = next(chunks)
  398. except StopIteration:
  399. return
  400. assert self.send_in_progress is None
  401. self.send_in_progress = self.loop.create_future()
  402. try:
  403. # First fragment.
  404. if isinstance(chunk, str):
  405. async with self.send_context():
  406. if text is False:
  407. self.protocol.send_binary(chunk.encode(), fin=False)
  408. else:
  409. self.protocol.send_text(chunk.encode(), fin=False)
  410. encode = True
  411. elif isinstance(chunk, BytesLike):
  412. async with self.send_context():
  413. if text is True:
  414. self.protocol.send_text(chunk, fin=False)
  415. else:
  416. self.protocol.send_binary(chunk, fin=False)
  417. encode = False
  418. else:
  419. raise TypeError("iterable must contain bytes or str")
  420. # Other fragments
  421. for chunk in chunks:
  422. if isinstance(chunk, str) and encode:
  423. async with self.send_context():
  424. self.protocol.send_continuation(chunk.encode(), fin=False)
  425. elif isinstance(chunk, BytesLike) and not encode:
  426. async with self.send_context():
  427. self.protocol.send_continuation(chunk, fin=False)
  428. else:
  429. raise TypeError("iterable must contain uniform types")
  430. # Final fragment.
  431. async with self.send_context():
  432. self.protocol.send_continuation(b"", fin=True)
  433. except Exception:
  434. # We're half-way through a fragmented message and we can't
  435. # complete it. This makes the connection unusable.
  436. async with self.send_context():
  437. self.protocol.fail(
  438. CloseCode.INTERNAL_ERROR,
  439. "error in fragmented message",
  440. )
  441. raise
  442. finally:
  443. self.send_in_progress.set_result(None)
  444. self.send_in_progress = None
  445. # Fragmented message -- async iterator.
  446. elif isinstance(message, AsyncIterable):
  447. achunks = aiter(message)
  448. try:
  449. chunk = await anext(achunks)
  450. except StopAsyncIteration:
  451. return
  452. assert self.send_in_progress is None
  453. self.send_in_progress = self.loop.create_future()
  454. try:
  455. # First fragment.
  456. if isinstance(chunk, str):
  457. if text is False:
  458. async with self.send_context():
  459. self.protocol.send_binary(chunk.encode(), fin=False)
  460. else:
  461. async with self.send_context():
  462. self.protocol.send_text(chunk.encode(), fin=False)
  463. encode = True
  464. elif isinstance(chunk, BytesLike):
  465. if text is True:
  466. async with self.send_context():
  467. self.protocol.send_text(chunk, fin=False)
  468. else:
  469. async with self.send_context():
  470. self.protocol.send_binary(chunk, fin=False)
  471. encode = False
  472. else:
  473. raise TypeError("async iterable must contain bytes or str")
  474. # Other fragments
  475. async for chunk in achunks:
  476. if isinstance(chunk, str) and encode:
  477. async with self.send_context():
  478. self.protocol.send_continuation(chunk.encode(), fin=False)
  479. elif isinstance(chunk, BytesLike) and not encode:
  480. async with self.send_context():
  481. self.protocol.send_continuation(chunk, fin=False)
  482. else:
  483. raise TypeError("async iterable must contain uniform types")
  484. # Final fragment.
  485. async with self.send_context():
  486. self.protocol.send_continuation(b"", fin=True)
  487. except Exception:
  488. # We're half-way through a fragmented message and we can't
  489. # complete it. This makes the connection unusable.
  490. async with self.send_context():
  491. self.protocol.fail(
  492. CloseCode.INTERNAL_ERROR,
  493. "error in fragmented message",
  494. )
  495. raise
  496. finally:
  497. self.send_in_progress.set_result(None)
  498. self.send_in_progress = None
  499. else:
  500. raise TypeError("data must be str, bytes, iterable, or async iterable")
  501. async def close(
  502. self,
  503. code: CloseCode | int = CloseCode.NORMAL_CLOSURE,
  504. reason: str = "",
  505. ) -> None:
  506. """
  507. Perform the closing handshake.
  508. :meth:`close` waits for the other end to complete the handshake and
  509. for the TCP connection to terminate.
  510. :meth:`close` is idempotent: it doesn't do anything once the
  511. connection is closed.
  512. Args:
  513. code: WebSocket close code.
  514. reason: WebSocket close reason.
  515. """
  516. try:
  517. # The context manager takes care of waiting for the TCP connection
  518. # to terminate after calling a method that sends a close frame.
  519. async with self.send_context():
  520. if self.send_in_progress is not None:
  521. self.protocol.fail(
  522. CloseCode.INTERNAL_ERROR,
  523. "close during fragmented message",
  524. )
  525. else:
  526. self.protocol.send_close(code, reason)
  527. except ConnectionClosed:
  528. # Ignore ConnectionClosed exceptions raised from send_context().
  529. # They mean that the connection is closed, which was the goal.
  530. pass
  531. async def wait_closed(self) -> None:
  532. """
  533. Wait until the connection is closed.
  534. :meth:`wait_closed` waits for the closing handshake to complete and for
  535. the TCP connection to terminate.
  536. """
  537. await asyncio.shield(self.connection_lost_waiter)
  538. async def ping(self, data: DataLike | None = None) -> Awaitable[float]:
  539. """
  540. Send a Ping_.
  541. .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
  542. A ping may serve as a keepalive or as a check that the remote endpoint
  543. received all messages up to this point
  544. Args:
  545. data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
  546. If ``data`` is :obj:`None`, the payload is four random bytes.
  547. Returns:
  548. A future that will be completed when the corresponding pong is
  549. received. You can ignore it if you don't intend to wait. The result
  550. of the future is the latency of the connection in seconds.
  551. ::
  552. pong_received = await ws.ping()
  553. # only if you want to wait for the corresponding pong
  554. latency = await pong_received
  555. Raises:
  556. ConnectionClosed: When the connection is closed.
  557. ConcurrencyError: If another ping was sent with the same data and
  558. the corresponding pong wasn't received yet.
  559. """
  560. if isinstance(data, BytesLike):
  561. data = bytes(data)
  562. elif isinstance(data, str):
  563. data = data.encode()
  564. elif data is not None:
  565. raise TypeError("data must be str or bytes-like")
  566. async with self.send_context():
  567. # Protect against duplicates if a payload is explicitly set.
  568. if data in self.pending_pings:
  569. raise ConcurrencyError("already waiting for a pong with the same data")
  570. # Generate a unique random payload otherwise.
  571. while data is None or data in self.pending_pings:
  572. data = struct.pack("!I", random.getrandbits(32))
  573. pong_received = self.loop.create_future()
  574. ping_timestamp = self.loop.time()
  575. # The event loop's default clock is time.monotonic(). Its resolution
  576. # is a bit low on Windows (~16ms). This is improved in Python 3.13.
  577. self.pending_pings[data] = (pong_received, ping_timestamp)
  578. self.protocol.send_ping(data)
  579. return pong_received
  580. async def pong(self, data: DataLike = b"") -> None:
  581. """
  582. Send a Pong_.
  583. .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
  584. An unsolicited pong may serve as a unidirectional heartbeat.
  585. Args:
  586. data: Payload of the pong. A :class:`str` will be encoded to UTF-8.
  587. Raises:
  588. ConnectionClosed: When the connection is closed.
  589. """
  590. if isinstance(data, BytesLike):
  591. data = bytes(data)
  592. elif isinstance(data, str):
  593. data = data.encode()
  594. else:
  595. raise TypeError("data must be str or bytes-like")
  596. async with self.send_context():
  597. self.protocol.send_pong(data)
  598. # Private methods
  599. def process_event(self, event: Event) -> None:
  600. """
  601. Process one incoming event.
  602. This method is overridden in subclasses to handle the handshake.
  603. """
  604. assert isinstance(event, Frame)
  605. if event.opcode in DATA_OPCODES:
  606. self.recv_messages.put(event)
  607. if event.opcode is Opcode.PONG:
  608. self.acknowledge_pings(bytes(event.data))
  609. def acknowledge_pings(self, data: bytes) -> None:
  610. """
  611. Acknowledge pings when receiving a pong.
  612. """
  613. # Ignore unsolicited pong.
  614. if data not in self.pending_pings:
  615. return
  616. pong_timestamp = self.loop.time()
  617. # Sending a pong for only the most recent ping is legal.
  618. # Acknowledge all previous pings too in that case.
  619. ping_id = None
  620. ping_ids = []
  621. for ping_id, (pong_received, ping_timestamp) in self.pending_pings.items():
  622. ping_ids.append(ping_id)
  623. latency = pong_timestamp - ping_timestamp
  624. if not pong_received.done():
  625. pong_received.set_result(latency)
  626. if ping_id == data:
  627. self.latency = latency
  628. break
  629. else:
  630. raise AssertionError("solicited pong not found in pings")
  631. # Remove acknowledged pings from self.pending_pings.
  632. for ping_id in ping_ids:
  633. del self.pending_pings[ping_id]
  634. def terminate_pending_pings(self) -> None:
  635. """
  636. Raise ConnectionClosed in pending pings when the connection is closed.
  637. """
  638. assert self.protocol.state is CLOSED
  639. exc = self.protocol.close_exc
  640. for pong_received, _ping_timestamp in self.pending_pings.values():
  641. if not pong_received.done():
  642. pong_received.set_exception(exc)
  643. # If the exception is never retrieved, it will be logged when ping
  644. # is garbage-collected. This is confusing for users.
  645. # Given that ping is done (with an exception), canceling it does
  646. # nothing, but it prevents logging the exception.
  647. pong_received.cancel()
  648. self.pending_pings.clear()
  649. async def keepalive(self) -> None:
  650. """
  651. Send a Ping frame and wait for a Pong frame at regular intervals.
  652. """
  653. assert self.ping_interval is not None
  654. latency = 0.0
  655. try:
  656. while True:
  657. # If self.ping_timeout > latency > self.ping_interval,
  658. # pings will be sent immediately after receiving pongs.
  659. # The period will be longer than self.ping_interval.
  660. await asyncio.sleep(self.ping_interval - latency)
  661. # This cannot raise ConnectionClosed when the connection is
  662. # closing because ping(), via send_context(), waits for the
  663. # connection to be closed before raising ConnectionClosed.
  664. # However, connection_lost() cancels keepalive_task before
  665. # it gets a chance to resume executing.
  666. pong_received = await self.ping()
  667. if self.debug:
  668. self.logger.debug("% sent keepalive ping")
  669. if self.ping_timeout is not None:
  670. try:
  671. async with asyncio_timeout(self.ping_timeout):
  672. # connection_lost cancels keepalive immediately
  673. # after setting a ConnectionClosed exception on
  674. # pong_received. A CancelledError is raised here,
  675. # not a ConnectionClosed exception.
  676. latency = await pong_received
  677. if self.debug:
  678. self.logger.debug("% received keepalive pong")
  679. except asyncio.TimeoutError:
  680. if self.debug:
  681. self.logger.debug("- timed out waiting for keepalive pong")
  682. async with self.send_context():
  683. self.protocol.fail(
  684. CloseCode.INTERNAL_ERROR,
  685. "keepalive ping timeout",
  686. )
  687. raise AssertionError(
  688. "send_context() should wait for connection_lost(), "
  689. "which cancels keepalive()"
  690. )
  691. except Exception:
  692. self.logger.error("keepalive ping failed", exc_info=True)
  693. def start_keepalive(self) -> None:
  694. """
  695. Run :meth:`keepalive` in a task, unless keepalive is disabled.
  696. """
  697. if self.ping_interval is not None:
  698. self.keepalive_task = self.loop.create_task(self.keepalive())
  699. @contextlib.asynccontextmanager
  700. async def send_context(
  701. self,
  702. *,
  703. expected_state: State = OPEN, # CONNECTING during the opening handshake
  704. ) -> AsyncIterator[None]:
  705. """
  706. Create a context for writing to the connection from user code.
  707. On entry, :meth:`send_context` checks that the connection is open; on
  708. exit, it writes outgoing data to the socket::
  709. async with self.send_context():
  710. self.protocol.send_text(message.encode())
  711. When the connection isn't open on entry, when the connection is expected
  712. to close on exit, or when an unexpected error happens, terminating the
  713. connection, :meth:`send_context` waits until the connection is closed
  714. then raises :exc:`~websockets.exceptions.ConnectionClosed`.
  715. """
  716. # Should we wait until the connection is closed?
  717. wait_for_close = False
  718. # Should we close the transport and raise ConnectionClosed?
  719. raise_close_exc = False
  720. # What exception should we chain ConnectionClosed to?
  721. original_exc: BaseException | None = None
  722. if self.protocol.state is expected_state:
  723. # Let the caller interact with the protocol.
  724. try:
  725. yield
  726. except (ProtocolError, ConcurrencyError):
  727. # The protocol state wasn't changed. Exit immediately.
  728. raise
  729. except Exception as exc:
  730. self.logger.error("unexpected internal error", exc_info=True)
  731. # This branch should never run. It's a safety net in case of
  732. # bugs. Since we don't know what happened, we will close the
  733. # connection and raise the exception to the caller.
  734. wait_for_close = False
  735. raise_close_exc = True
  736. original_exc = exc
  737. else:
  738. # Check if the connection is expected to close soon.
  739. if self.protocol.close_expected():
  740. wait_for_close = True
  741. # Set the close deadline based on the close timeout.
  742. # Since we tested earlier that protocol.state is OPEN
  743. # (or CONNECTING), self.close_deadline is still None.
  744. assert self.close_deadline is None
  745. if self.close_timeout is not None:
  746. self.close_deadline = self.loop.time() + self.close_timeout
  747. # Write outgoing data to the socket with flow control.
  748. try:
  749. self.send_data()
  750. await self.drain()
  751. except Exception as exc:
  752. if self.debug:
  753. self.logger.debug(
  754. "! error while sending data",
  755. exc_info=True,
  756. )
  757. # While the only expected exception here is OSError,
  758. # other exceptions would be treated identically.
  759. wait_for_close = False
  760. raise_close_exc = True
  761. original_exc = exc
  762. else: # self.protocol.state is not expected_state
  763. # Minor layering violation: we assume that the connection
  764. # will be closing soon if it isn't in the expected state.
  765. wait_for_close = True
  766. # Calculate close_deadline if it wasn't set yet.
  767. if self.close_deadline is None:
  768. if self.close_timeout is not None:
  769. self.close_deadline = self.loop.time() + self.close_timeout
  770. raise_close_exc = True
  771. # If the connection is expected to close soon and the close timeout
  772. # elapses, close the socket to terminate the connection.
  773. if wait_for_close:
  774. try:
  775. async with asyncio_timeout_at(self.close_deadline):
  776. await asyncio.shield(self.connection_lost_waiter)
  777. except TimeoutError:
  778. # There's no risk of overwriting another error because
  779. # original_exc is never set when wait_for_close is True.
  780. assert original_exc is None
  781. original_exc = TimeoutError("timed out while closing connection")
  782. # Set recv_exc before closing the transport in order to get
  783. # proper exception reporting.
  784. raise_close_exc = True
  785. self.set_recv_exc(original_exc)
  786. # If an error occurred, close the transport to terminate the connection and
  787. # raise an exception.
  788. if raise_close_exc:
  789. self.transport.abort()
  790. # Wait for the protocol state to be CLOSED before accessing close_exc.
  791. await asyncio.shield(self.connection_lost_waiter)
  792. raise self.protocol.close_exc from original_exc
  793. def send_data(self) -> None:
  794. """
  795. Send outgoing data.
  796. """
  797. for data in self.protocol.data_to_send():
  798. if data:
  799. self.transport.write(data)
  800. else:
  801. # Half-close the TCP connection when possible i.e. no TLS.
  802. if self.transport.can_write_eof():
  803. if self.debug:
  804. self.logger.debug("x half-closing TCP connection")
  805. # write_eof() doesn't document which exceptions it raises.
  806. # OSError is plausible. uvloop can raise RuntimeError here.
  807. try:
  808. self.transport.write_eof()
  809. except Exception: # pragma: no cover
  810. pass
  811. # Else, close the TCP connection.
  812. else: # pragma: no cover
  813. if self.debug:
  814. self.logger.debug("x closing TCP connection")
  815. self.transport.close()
  816. def set_recv_exc(self, exc: BaseException | None) -> None:
  817. """
  818. Set recv_exc, if not set yet.
  819. This method must be called only from connection callbacks.
  820. """
  821. if self.recv_exc is None:
  822. self.recv_exc = exc
  823. # asyncio.Protocol methods
  824. # Connection callbacks
  825. def connection_made(self, transport: asyncio.BaseTransport) -> None:
  826. transport = cast(asyncio.Transport, transport)
  827. self.recv_messages = Assembler(
  828. self.max_queue_high,
  829. self.max_queue_low,
  830. pause=transport.pause_reading,
  831. resume=transport.resume_reading,
  832. )
  833. transport.set_write_buffer_limits(
  834. self.write_limit_high,
  835. self.write_limit_low,
  836. )
  837. self.transport = transport
  838. def connection_lost(self, exc: Exception | None) -> None:
  839. # Calling protocol.receive_eof() is safe because it's idempotent.
  840. # This guarantees that the protocol state becomes CLOSED.
  841. self.protocol.receive_eof()
  842. assert self.protocol.state is CLOSED
  843. self.set_recv_exc(exc)
  844. # Abort recv() and pending pings with a ConnectionClosed exception.
  845. self.recv_messages.close()
  846. self.terminate_pending_pings()
  847. if self.keepalive_task is not None:
  848. self.keepalive_task.cancel()
  849. # If self.connection_lost_waiter isn't pending, that's a bug, because:
  850. # - it's set only here in connection_lost() which is called only once;
  851. # - it must never be canceled.
  852. self.connection_lost_waiter.set_result(None)
  853. # Adapted from asyncio.streams.FlowControlMixin
  854. if self.paused: # pragma: no cover
  855. self.paused = False
  856. for waiter in self.drain_waiters:
  857. if not waiter.done():
  858. if exc is None:
  859. waiter.set_result(None)
  860. else:
  861. waiter.set_exception(exc)
  862. # Flow control callbacks
  863. def pause_writing(self) -> None: # pragma: no cover
  864. # Adapted from asyncio.streams.FlowControlMixin
  865. assert not self.paused
  866. self.paused = True
  867. def resume_writing(self) -> None: # pragma: no cover
  868. # Adapted from asyncio.streams.FlowControlMixin
  869. assert self.paused
  870. self.paused = False
  871. for waiter in self.drain_waiters:
  872. if not waiter.done():
  873. waiter.set_result(None)
  874. async def drain(self) -> None: # pragma: no cover
  875. # We don't check if the connection is closed because we call drain()
  876. # immediately after write() and write() would fail in that case.
  877. # Adapted from asyncio.streams.StreamWriter
  878. # Yield to the event loop so that connection_lost() may be called.
  879. if self.transport.is_closing():
  880. await asyncio.sleep(0)
  881. # Adapted from asyncio.streams.FlowControlMixin
  882. if self.paused:
  883. waiter = self.loop.create_future()
  884. self.drain_waiters.append(waiter)
  885. try:
  886. await waiter
  887. finally:
  888. self.drain_waiters.remove(waiter)
  889. # Streaming protocol callbacks
  890. def data_received(self, data: bytes) -> None:
  891. # Feed incoming data to the protocol.
  892. self.protocol.receive_data(data)
  893. # This isn't expected to raise an exception.
  894. events = self.protocol.events_received()
  895. # Write outgoing data to the transport.
  896. try:
  897. self.send_data()
  898. except Exception as exc:
  899. if self.debug:
  900. self.logger.debug("! error while sending data", exc_info=True)
  901. self.set_recv_exc(exc)
  902. # If needed, set the close deadline based on the close timeout.
  903. if self.protocol.close_expected():
  904. if self.close_deadline is None:
  905. if self.close_timeout is not None:
  906. self.close_deadline = self.loop.time() + self.close_timeout
  907. # If self.send_data raised an exception, then events are lost.
  908. # Given that automatic responses write small amounts of data,
  909. # this should be uncommon, so we don't handle the edge case.
  910. for event in events:
  911. # This isn't expected to raise an exception.
  912. self.process_event(event)
  913. def eof_received(self) -> None:
  914. # Feed the end of the data stream to the protocol.
  915. self.protocol.receive_eof()
  916. # This isn't expected to raise an exception.
  917. events = self.protocol.events_received()
  918. # There is no error handling because send_data() can only write
  919. # the end of the data stream and it handles errors by itself.
  920. self.send_data()
  921. # This code path is triggered when receiving an HTTP response
  922. # without a Content-Length header. This is the only case where
  923. # reading until EOF generates an event; all other events have
  924. # a known length. Ignore for coverage measurement because tests
  925. # are in test_client.py rather than test_connection.py.
  926. for event in events: # pragma: no cover
  927. # This isn't expected to raise an exception.
  928. self.process_event(event)
  929. # The WebSocket protocol has its own closing handshake: endpoints close
  930. # the TCP or TLS connection after sending and receiving a close frame.
  931. # As a consequence, they never need to write after receiving EOF, so
  932. # there's no reason to keep the transport open by returning True.
  933. # Besides, that doesn't work on TLS connections.
  934. # broadcast() is defined in the connection module even though it's primarily
  935. # used by servers and documented in the server module because it works with
  936. # client connections too and because it's easier to test together with the
  937. # Connection class.
  938. def broadcast(
  939. connections: Iterable[Connection],
  940. message: DataLike,
  941. raise_exceptions: bool = False,
  942. *,
  943. text: bool | None = None,
  944. ) -> None:
  945. """
  946. Broadcast a message to several WebSocket connections.
  947. A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like
  948. object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent
  949. as a Binary_ frame.
  950. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  951. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  952. You may override this behavior with the ``text`` argument:
  953. * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object
  954. (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a
  955. Text_ frame. This improves performance when the message is already
  956. UTF-8 encoded, for example if the message contains JSON and you're
  957. using a JSON library that produces a bytestring.
  958. * Set ``text=False`` to send a string (:class:`str`) in a Binary_
  959. frame. This may be useful for servers that expect binary frames
  960. instead of text frames.
  961. :func:`broadcast` pushes the message synchronously to all connections even
  962. if their write buffers are overflowing. There's no backpressure.
  963. If you broadcast messages faster than a connection can handle them, messages
  964. will pile up in its write buffer until the connection times out. Keep
  965. ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage
  966. from slow connections.
  967. Unlike :meth:`~websockets.asyncio.connection.Connection.send`,
  968. :func:`broadcast` doesn't support sending fragmented messages. Indeed,
  969. fragmentation is useful for sending large messages without buffering them in
  970. memory, while :func:`broadcast` buffers one copy per connection as fast as
  971. possible.
  972. :func:`broadcast` skips connections that aren't open in order to avoid
  973. errors on connections where the closing handshake is in progress.
  974. :func:`broadcast` ignores failures to write the message on some connections.
  975. It continues writing to other connections. On Python 3.11 and above, you may
  976. set ``raise_exceptions`` to :obj:`True` to record failures and raise all
  977. exceptions in a :pep:`654` :exc:`ExceptionGroup`.
  978. While :func:`broadcast` makes more sense for servers, it works identically
  979. with clients, if you have a use case for opening connections to many servers
  980. and broadcasting a message to them.
  981. Args:
  982. websockets: WebSocket connections to which the message will be sent.
  983. message: Message to send.
  984. raise_exceptions: Whether to raise an exception in case of failures.
  985. text: Force sending in Text_ or Binary_ frames.
  986. Raises:
  987. TypeError: If ``message`` doesn't have a supported type.
  988. """
  989. if isinstance(message, str):
  990. send_method = "send_binary" if text is False else "send_text"
  991. message = message.encode()
  992. elif isinstance(message, BytesLike):
  993. send_method = "send_text" if text is True else "send_binary"
  994. else:
  995. raise TypeError("data must be str or bytes")
  996. if raise_exceptions:
  997. if sys.version_info[:2] < (3, 11): # pragma: no cover
  998. raise ValueError("raise_exceptions requires at least Python 3.11")
  999. exceptions: list[Exception] = []
  1000. for connection in connections:
  1001. exception: Exception
  1002. if connection.protocol.state is not OPEN:
  1003. continue
  1004. if connection.send_in_progress is not None:
  1005. if raise_exceptions:
  1006. exception = ConcurrencyError("sending a fragmented message")
  1007. exceptions.append(exception)
  1008. else:
  1009. connection.logger.warning(
  1010. "skipped broadcast: sending a fragmented message",
  1011. )
  1012. continue
  1013. try:
  1014. # Call connection.protocol.send_text or send_binary.
  1015. # Either way, message is already converted to bytes.
  1016. getattr(connection.protocol, send_method)(message)
  1017. connection.send_data()
  1018. except Exception as write_exception:
  1019. if raise_exceptions:
  1020. exception = RuntimeError("failed to write message")
  1021. exception.__cause__ = write_exception
  1022. exceptions.append(exception)
  1023. else:
  1024. connection.logger.warning(
  1025. "skipped broadcast: failed to write message: %s",
  1026. traceback.format_exception_only(write_exception)[0].strip(),
  1027. )
  1028. if raise_exceptions and exceptions:
  1029. raise ExceptionGroup("skipped broadcast", exceptions)
  1030. # Pretend that broadcast is actually defined in the server module.
  1031. broadcast.__module__ = "websockets.asyncio.server"