connection.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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. Raises:
  368. ConnectionClosed: When the connection is closed.
  369. TypeError: If ``message`` doesn't have a supported type.
  370. """
  371. # While sending a fragmented message, prevent sending other messages
  372. # until all fragments are sent.
  373. while self.send_in_progress is not None:
  374. await asyncio.shield(self.send_in_progress)
  375. # Unfragmented message -- this case must be handled first because
  376. # strings and bytes-like objects are iterable.
  377. if isinstance(message, str):
  378. async with self.send_context():
  379. if text is False:
  380. self.protocol.send_binary(message.encode())
  381. else:
  382. self.protocol.send_text(message.encode())
  383. elif isinstance(message, BytesLike):
  384. async with self.send_context():
  385. if text is True:
  386. self.protocol.send_text(message)
  387. else:
  388. self.protocol.send_binary(message)
  389. # Catch a common mistake -- passing a dict to send().
  390. elif isinstance(message, Mapping):
  391. raise TypeError("data is a dict-like object")
  392. # Fragmented message -- regular iterator.
  393. elif isinstance(message, Iterable):
  394. chunks = iter(message)
  395. try:
  396. chunk = next(chunks)
  397. except StopIteration:
  398. return
  399. assert self.send_in_progress is None
  400. self.send_in_progress = self.loop.create_future()
  401. try:
  402. # First fragment.
  403. if isinstance(chunk, str):
  404. async with self.send_context():
  405. if text is False:
  406. self.protocol.send_binary(chunk.encode(), fin=False)
  407. else:
  408. self.protocol.send_text(chunk.encode(), fin=False)
  409. encode = True
  410. elif isinstance(chunk, BytesLike):
  411. async with self.send_context():
  412. if text is True:
  413. self.protocol.send_text(chunk, fin=False)
  414. else:
  415. self.protocol.send_binary(chunk, fin=False)
  416. encode = False
  417. else:
  418. raise TypeError("iterable must contain bytes or str")
  419. # Other fragments
  420. for chunk in chunks:
  421. if isinstance(chunk, str) and encode:
  422. async with self.send_context():
  423. self.protocol.send_continuation(chunk.encode(), fin=False)
  424. elif isinstance(chunk, BytesLike) and not encode:
  425. async with self.send_context():
  426. self.protocol.send_continuation(chunk, fin=False)
  427. else:
  428. raise TypeError("iterable must contain uniform types")
  429. # Final fragment.
  430. async with self.send_context():
  431. self.protocol.send_continuation(b"", fin=True)
  432. except Exception:
  433. # We're half-way through a fragmented message and we can't
  434. # complete it. This makes the connection unusable.
  435. async with self.send_context():
  436. self.protocol.fail(
  437. CloseCode.INTERNAL_ERROR,
  438. "error in fragmented message",
  439. )
  440. raise
  441. finally:
  442. self.send_in_progress.set_result(None)
  443. self.send_in_progress = None
  444. # Fragmented message -- async iterator.
  445. elif isinstance(message, AsyncIterable):
  446. achunks = aiter(message)
  447. try:
  448. chunk = await anext(achunks)
  449. except StopAsyncIteration:
  450. return
  451. assert self.send_in_progress is None
  452. self.send_in_progress = self.loop.create_future()
  453. try:
  454. # First fragment.
  455. if isinstance(chunk, str):
  456. if text is False:
  457. async with self.send_context():
  458. self.protocol.send_binary(chunk.encode(), fin=False)
  459. else:
  460. async with self.send_context():
  461. self.protocol.send_text(chunk.encode(), fin=False)
  462. encode = True
  463. elif isinstance(chunk, BytesLike):
  464. if text is True:
  465. async with self.send_context():
  466. self.protocol.send_text(chunk, fin=False)
  467. else:
  468. async with self.send_context():
  469. self.protocol.send_binary(chunk, fin=False)
  470. encode = False
  471. else:
  472. raise TypeError("async iterable must contain bytes or str")
  473. # Other fragments
  474. async for chunk in achunks:
  475. if isinstance(chunk, str) and encode:
  476. async with self.send_context():
  477. self.protocol.send_continuation(chunk.encode(), fin=False)
  478. elif isinstance(chunk, BytesLike) and not encode:
  479. async with self.send_context():
  480. self.protocol.send_continuation(chunk, fin=False)
  481. else:
  482. raise TypeError("async iterable must contain uniform types")
  483. # Final fragment.
  484. async with self.send_context():
  485. self.protocol.send_continuation(b"", fin=True)
  486. except Exception:
  487. # We're half-way through a fragmented message and we can't
  488. # complete it. This makes the connection unusable.
  489. async with self.send_context():
  490. self.protocol.fail(
  491. CloseCode.INTERNAL_ERROR,
  492. "error in fragmented message",
  493. )
  494. raise
  495. finally:
  496. self.send_in_progress.set_result(None)
  497. self.send_in_progress = None
  498. else:
  499. raise TypeError("data must be str, bytes, iterable, or async iterable")
  500. async def close(
  501. self,
  502. code: CloseCode | int = CloseCode.NORMAL_CLOSURE,
  503. reason: str = "",
  504. ) -> None:
  505. """
  506. Perform the closing handshake.
  507. :meth:`close` waits for the other end to complete the handshake and
  508. for the TCP connection to terminate.
  509. :meth:`close` is idempotent: it doesn't do anything once the
  510. connection is closed.
  511. Args:
  512. code: WebSocket close code.
  513. reason: WebSocket close reason.
  514. """
  515. try:
  516. # The context manager takes care of waiting for the TCP connection
  517. # to terminate after calling a method that sends a close frame.
  518. async with self.send_context():
  519. if self.send_in_progress is not None:
  520. self.protocol.fail(
  521. CloseCode.INTERNAL_ERROR,
  522. "close during fragmented message",
  523. )
  524. else:
  525. self.protocol.send_close(code, reason)
  526. except ConnectionClosed:
  527. # Ignore ConnectionClosed exceptions raised from send_context().
  528. # They mean that the connection is closed, which was the goal.
  529. pass
  530. async def wait_closed(self) -> None:
  531. """
  532. Wait until the connection is closed.
  533. :meth:`wait_closed` waits for the closing handshake to complete and for
  534. the TCP connection to terminate.
  535. """
  536. await asyncio.shield(self.connection_lost_waiter)
  537. async def ping(self, data: DataLike | None = None) -> Awaitable[float]:
  538. """
  539. Send a Ping_.
  540. .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
  541. A ping may serve as a keepalive or as a check that the remote endpoint
  542. received all messages up to this point
  543. Args:
  544. data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
  545. If ``data`` is :obj:`None`, the payload is four random bytes.
  546. Returns:
  547. A future that will be completed when the corresponding pong is
  548. received. You can ignore it if you don't intend to wait. The result
  549. of the future is the latency of the connection in seconds.
  550. ::
  551. pong_received = await ws.ping()
  552. # only if you want to wait for the corresponding pong
  553. latency = await pong_received
  554. Raises:
  555. ConnectionClosed: When the connection is closed.
  556. ConcurrencyError: If another ping was sent with the same data and
  557. the corresponding pong wasn't received yet.
  558. """
  559. if isinstance(data, BytesLike):
  560. data = bytes(data)
  561. elif isinstance(data, str):
  562. data = data.encode()
  563. elif data is not None:
  564. raise TypeError("data must be str or bytes-like")
  565. async with self.send_context():
  566. # Protect against duplicates if a payload is explicitly set.
  567. if data in self.pending_pings:
  568. raise ConcurrencyError("already waiting for a pong with the same data")
  569. # Generate a unique random payload otherwise.
  570. while data is None or data in self.pending_pings:
  571. data = struct.pack("!I", random.getrandbits(32))
  572. pong_received = self.loop.create_future()
  573. ping_timestamp = self.loop.time()
  574. # The event loop's default clock is time.monotonic(). Its resolution
  575. # is a bit low on Windows (~16ms). This is improved in Python 3.13.
  576. self.pending_pings[data] = (pong_received, ping_timestamp)
  577. self.protocol.send_ping(data)
  578. return pong_received
  579. async def pong(self, data: DataLike = b"") -> None:
  580. """
  581. Send a Pong_.
  582. .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
  583. An unsolicited pong may serve as a unidirectional heartbeat.
  584. Args:
  585. data: Payload of the pong. A :class:`str` will be encoded to UTF-8.
  586. Raises:
  587. ConnectionClosed: When the connection is closed.
  588. """
  589. if isinstance(data, BytesLike):
  590. data = bytes(data)
  591. elif isinstance(data, str):
  592. data = data.encode()
  593. else:
  594. raise TypeError("data must be str or bytes-like")
  595. async with self.send_context():
  596. self.protocol.send_pong(data)
  597. # Private methods
  598. def process_event(self, event: Event) -> None:
  599. """
  600. Process one incoming event.
  601. This method is overridden in subclasses to handle the handshake.
  602. """
  603. assert isinstance(event, Frame)
  604. if event.opcode in DATA_OPCODES:
  605. self.recv_messages.put(event)
  606. if event.opcode is Opcode.PONG:
  607. self.acknowledge_pings(bytes(event.data))
  608. def acknowledge_pings(self, data: bytes) -> None:
  609. """
  610. Acknowledge pings when receiving a pong.
  611. """
  612. # Ignore unsolicited pong.
  613. if data not in self.pending_pings:
  614. return
  615. pong_timestamp = self.loop.time()
  616. # Sending a pong for only the most recent ping is legal.
  617. # Acknowledge all previous pings too in that case.
  618. ping_id = None
  619. ping_ids = []
  620. for ping_id, (pong_received, ping_timestamp) in self.pending_pings.items():
  621. ping_ids.append(ping_id)
  622. latency = pong_timestamp - ping_timestamp
  623. if not pong_received.done():
  624. pong_received.set_result(latency)
  625. if ping_id == data:
  626. self.latency = latency
  627. break
  628. else:
  629. raise AssertionError("solicited pong not found in pings")
  630. # Remove acknowledged pings from self.pending_pings.
  631. for ping_id in ping_ids:
  632. del self.pending_pings[ping_id]
  633. def terminate_pending_pings(self) -> None:
  634. """
  635. Raise ConnectionClosed in pending pings when the connection is closed.
  636. """
  637. assert self.protocol.state is CLOSED
  638. exc = self.protocol.close_exc
  639. for pong_received, _ping_timestamp in self.pending_pings.values():
  640. if not pong_received.done():
  641. pong_received.set_exception(exc)
  642. # If the exception is never retrieved, it will be logged when ping
  643. # is garbage-collected. This is confusing for users.
  644. # Given that ping is done (with an exception), canceling it does
  645. # nothing, but it prevents logging the exception.
  646. pong_received.cancel()
  647. self.pending_pings.clear()
  648. async def keepalive(self) -> None:
  649. """
  650. Send a Ping frame and wait for a Pong frame at regular intervals.
  651. """
  652. assert self.ping_interval is not None
  653. latency = 0.0
  654. try:
  655. while True:
  656. # If self.ping_timeout > latency > self.ping_interval,
  657. # pings will be sent immediately after receiving pongs.
  658. # The period will be longer than self.ping_interval.
  659. await asyncio.sleep(self.ping_interval - latency)
  660. # This cannot raise ConnectionClosed when the connection is
  661. # closing because ping(), via send_context(), waits for the
  662. # connection to be closed before raising ConnectionClosed.
  663. # However, connection_lost() cancels keepalive_task before
  664. # it gets a chance to resume excuting.
  665. pong_received = await self.ping()
  666. if self.debug:
  667. self.logger.debug("% sent keepalive ping")
  668. if self.ping_timeout is not None:
  669. try:
  670. async with asyncio_timeout(self.ping_timeout):
  671. # connection_lost cancels keepalive immediately
  672. # after setting a ConnectionClosed exception on
  673. # pong_received. A CancelledError is raised here,
  674. # not a ConnectionClosed exception.
  675. latency = await pong_received
  676. if self.debug:
  677. self.logger.debug("% received keepalive pong")
  678. except asyncio.TimeoutError:
  679. if self.debug:
  680. self.logger.debug("- timed out waiting for keepalive pong")
  681. async with self.send_context():
  682. self.protocol.fail(
  683. CloseCode.INTERNAL_ERROR,
  684. "keepalive ping timeout",
  685. )
  686. raise AssertionError(
  687. "send_context() should wait for connection_lost(), "
  688. "which cancels keepalive()"
  689. )
  690. except Exception:
  691. self.logger.error("keepalive ping failed", exc_info=True)
  692. def start_keepalive(self) -> None:
  693. """
  694. Run :meth:`keepalive` in a task, unless keepalive is disabled.
  695. """
  696. if self.ping_interval is not None:
  697. self.keepalive_task = self.loop.create_task(self.keepalive())
  698. @contextlib.asynccontextmanager
  699. async def send_context(
  700. self,
  701. *,
  702. expected_state: State = OPEN, # CONNECTING during the opening handshake
  703. ) -> AsyncIterator[None]:
  704. """
  705. Create a context for writing to the connection from user code.
  706. On entry, :meth:`send_context` checks that the connection is open; on
  707. exit, it writes outgoing data to the socket::
  708. async with self.send_context():
  709. self.protocol.send_text(message.encode())
  710. When the connection isn't open on entry, when the connection is expected
  711. to close on exit, or when an unexpected error happens, terminating the
  712. connection, :meth:`send_context` waits until the connection is closed
  713. then raises :exc:`~websockets.exceptions.ConnectionClosed`.
  714. """
  715. # Should we wait until the connection is closed?
  716. wait_for_close = False
  717. # Should we close the transport and raise ConnectionClosed?
  718. raise_close_exc = False
  719. # What exception should we chain ConnectionClosed to?
  720. original_exc: BaseException | None = None
  721. if self.protocol.state is expected_state:
  722. # Let the caller interact with the protocol.
  723. try:
  724. yield
  725. except (ProtocolError, ConcurrencyError):
  726. # The protocol state wasn't changed. Exit immediately.
  727. raise
  728. except Exception as exc:
  729. self.logger.error("unexpected internal error", exc_info=True)
  730. # This branch should never run. It's a safety net in case of
  731. # bugs. Since we don't know what happened, we will close the
  732. # connection and raise the exception to the caller.
  733. wait_for_close = False
  734. raise_close_exc = True
  735. original_exc = exc
  736. else:
  737. # Check if the connection is expected to close soon.
  738. if self.protocol.close_expected():
  739. wait_for_close = True
  740. # Set the close deadline based on the close timeout.
  741. # Since we tested earlier that protocol.state is OPEN
  742. # (or CONNECTING), self.close_deadline is still None.
  743. assert self.close_deadline is None
  744. if self.close_timeout is not None:
  745. self.close_deadline = self.loop.time() + self.close_timeout
  746. # Write outgoing data to the socket with flow control.
  747. try:
  748. self.send_data()
  749. await self.drain()
  750. except Exception as exc:
  751. if self.debug:
  752. self.logger.debug(
  753. "! error while sending data",
  754. exc_info=True,
  755. )
  756. # While the only expected exception here is OSError,
  757. # other exceptions would be treated identically.
  758. wait_for_close = False
  759. raise_close_exc = True
  760. original_exc = exc
  761. else: # self.protocol.state is not expected_state
  762. # Minor layering violation: we assume that the connection
  763. # will be closing soon if it isn't in the expected state.
  764. wait_for_close = True
  765. # Calculate close_deadline if it wasn't set yet.
  766. if self.close_deadline is None:
  767. if self.close_timeout is not None:
  768. self.close_deadline = self.loop.time() + self.close_timeout
  769. raise_close_exc = True
  770. # If the connection is expected to close soon and the close timeout
  771. # elapses, close the socket to terminate the connection.
  772. if wait_for_close:
  773. try:
  774. async with asyncio_timeout_at(self.close_deadline):
  775. await asyncio.shield(self.connection_lost_waiter)
  776. except TimeoutError:
  777. # There's no risk of overwriting another error because
  778. # original_exc is never set when wait_for_close is True.
  779. assert original_exc is None
  780. original_exc = TimeoutError("timed out while closing connection")
  781. # Set recv_exc before closing the transport in order to get
  782. # proper exception reporting.
  783. raise_close_exc = True
  784. self.set_recv_exc(original_exc)
  785. # If an error occurred, close the transport to terminate the connection and
  786. # raise an exception.
  787. if raise_close_exc:
  788. self.transport.abort()
  789. # Wait for the protocol state to be CLOSED before accessing close_exc.
  790. await asyncio.shield(self.connection_lost_waiter)
  791. raise self.protocol.close_exc from original_exc
  792. def send_data(self) -> None:
  793. """
  794. Send outgoing data.
  795. """
  796. for data in self.protocol.data_to_send():
  797. if data:
  798. self.transport.write(data)
  799. else:
  800. # Half-close the TCP connection when possible i.e. no TLS.
  801. if self.transport.can_write_eof():
  802. if self.debug:
  803. self.logger.debug("x half-closing TCP connection")
  804. # write_eof() doesn't document which exceptions it raises.
  805. # OSError is plausible. uvloop can raise RuntimeError here.
  806. try:
  807. self.transport.write_eof()
  808. except Exception: # pragma: no cover
  809. pass
  810. # Else, close the TCP connection.
  811. else: # pragma: no cover
  812. if self.debug:
  813. self.logger.debug("x closing TCP connection")
  814. self.transport.close()
  815. def set_recv_exc(self, exc: BaseException | None) -> None:
  816. """
  817. Set recv_exc, if not set yet.
  818. This method must be called only from connection callbacks.
  819. """
  820. if self.recv_exc is None:
  821. self.recv_exc = exc
  822. # asyncio.Protocol methods
  823. # Connection callbacks
  824. def connection_made(self, transport: asyncio.BaseTransport) -> None:
  825. transport = cast(asyncio.Transport, transport)
  826. self.recv_messages = Assembler(
  827. self.max_queue_high,
  828. self.max_queue_low,
  829. pause=transport.pause_reading,
  830. resume=transport.resume_reading,
  831. )
  832. transport.set_write_buffer_limits(
  833. self.write_limit_high,
  834. self.write_limit_low,
  835. )
  836. self.transport = transport
  837. def connection_lost(self, exc: Exception | None) -> None:
  838. # Calling protocol.receive_eof() is safe because it's idempotent.
  839. # This guarantees that the protocol state becomes CLOSED.
  840. self.protocol.receive_eof()
  841. assert self.protocol.state is CLOSED
  842. self.set_recv_exc(exc)
  843. # Abort recv() and pending pings with a ConnectionClosed exception.
  844. self.recv_messages.close()
  845. self.terminate_pending_pings()
  846. if self.keepalive_task is not None:
  847. self.keepalive_task.cancel()
  848. # If self.connection_lost_waiter isn't pending, that's a bug, because:
  849. # - it's set only here in connection_lost() which is called only once;
  850. # - it must never be canceled.
  851. self.connection_lost_waiter.set_result(None)
  852. # Adapted from asyncio.streams.FlowControlMixin
  853. if self.paused: # pragma: no cover
  854. self.paused = False
  855. for waiter in self.drain_waiters:
  856. if not waiter.done():
  857. if exc is None:
  858. waiter.set_result(None)
  859. else:
  860. waiter.set_exception(exc)
  861. # Flow control callbacks
  862. def pause_writing(self) -> None: # pragma: no cover
  863. # Adapted from asyncio.streams.FlowControlMixin
  864. assert not self.paused
  865. self.paused = True
  866. def resume_writing(self) -> None: # pragma: no cover
  867. # Adapted from asyncio.streams.FlowControlMixin
  868. assert self.paused
  869. self.paused = False
  870. for waiter in self.drain_waiters:
  871. if not waiter.done():
  872. waiter.set_result(None)
  873. async def drain(self) -> None: # pragma: no cover
  874. # We don't check if the connection is closed because we call drain()
  875. # immediately after write() and write() would fail in that case.
  876. # Adapted from asyncio.streams.StreamWriter
  877. # Yield to the event loop so that connection_lost() may be called.
  878. if self.transport.is_closing():
  879. await asyncio.sleep(0)
  880. # Adapted from asyncio.streams.FlowControlMixin
  881. if self.paused:
  882. waiter = self.loop.create_future()
  883. self.drain_waiters.append(waiter)
  884. try:
  885. await waiter
  886. finally:
  887. self.drain_waiters.remove(waiter)
  888. # Streaming protocol callbacks
  889. def data_received(self, data: bytes) -> None:
  890. # Feed incoming data to the protocol.
  891. self.protocol.receive_data(data)
  892. # This isn't expected to raise an exception.
  893. events = self.protocol.events_received()
  894. # Write outgoing data to the transport.
  895. try:
  896. self.send_data()
  897. except Exception as exc:
  898. if self.debug:
  899. self.logger.debug("! error while sending data", exc_info=True)
  900. self.set_recv_exc(exc)
  901. # If needed, set the close deadline based on the close timeout.
  902. if self.protocol.close_expected():
  903. if self.close_deadline is None:
  904. if self.close_timeout is not None:
  905. self.close_deadline = self.loop.time() + self.close_timeout
  906. # If self.send_data raised an exception, then events are lost.
  907. # Given that automatic responses write small amounts of data,
  908. # this should be uncommon, so we don't handle the edge case.
  909. for event in events:
  910. # This isn't expected to raise an exception.
  911. self.process_event(event)
  912. def eof_received(self) -> None:
  913. # Feed the end of the data stream to the protocol.
  914. self.protocol.receive_eof()
  915. # This isn't expected to raise an exception.
  916. events = self.protocol.events_received()
  917. # There is no error handling because send_data() can only write
  918. # the end of the data stream and it handles errors by itself.
  919. self.send_data()
  920. # This code path is triggered when receiving an HTTP response
  921. # without a Content-Length header. This is the only case where
  922. # reading until EOF generates an event; all other events have
  923. # a known length. Ignore for coverage measurement because tests
  924. # are in test_client.py rather than test_connection.py.
  925. for event in events: # pragma: no cover
  926. # This isn't expected to raise an exception.
  927. self.process_event(event)
  928. # The WebSocket protocol has its own closing handshake: endpoints close
  929. # the TCP or TLS connection after sending and receiving a close frame.
  930. # As a consequence, they never need to write after receiving EOF, so
  931. # there's no reason to keep the transport open by returning True.
  932. # Besides, that doesn't work on TLS connections.
  933. # broadcast() is defined in the connection module even though it's primarily
  934. # used by servers and documented in the server module because it works with
  935. # client connections too and because it's easier to test together with the
  936. # Connection class.
  937. def broadcast(
  938. connections: Iterable[Connection],
  939. message: DataLike,
  940. raise_exceptions: bool = False,
  941. ) -> None:
  942. """
  943. Broadcast a message to several WebSocket connections.
  944. A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like
  945. object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent
  946. as a Binary_ frame.
  947. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  948. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  949. :func:`broadcast` pushes the message synchronously to all connections even
  950. if their write buffers are overflowing. There's no backpressure.
  951. If you broadcast messages faster than a connection can handle them, messages
  952. will pile up in its write buffer until the connection times out. Keep
  953. ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage
  954. from slow connections.
  955. Unlike :meth:`~websockets.asyncio.connection.Connection.send`,
  956. :func:`broadcast` doesn't support sending fragmented messages. Indeed,
  957. fragmentation is useful for sending large messages without buffering them in
  958. memory, while :func:`broadcast` buffers one copy per connection as fast as
  959. possible.
  960. :func:`broadcast` skips connections that aren't open in order to avoid
  961. errors on connections where the closing handshake is in progress.
  962. :func:`broadcast` ignores failures to write the message on some connections.
  963. It continues writing to other connections. On Python 3.11 and above, you may
  964. set ``raise_exceptions`` to :obj:`True` to record failures and raise all
  965. exceptions in a :pep:`654` :exc:`ExceptionGroup`.
  966. While :func:`broadcast` makes more sense for servers, it works identically
  967. with clients, if you have a use case for opening connections to many servers
  968. and broadcasting a message to them.
  969. Args:
  970. websockets: WebSocket connections to which the message will be sent.
  971. message: Message to send.
  972. raise_exceptions: Whether to raise an exception in case of failures.
  973. Raises:
  974. TypeError: If ``message`` doesn't have a supported type.
  975. """
  976. if isinstance(message, str):
  977. send_method = "send_text"
  978. message = message.encode()
  979. elif isinstance(message, BytesLike):
  980. send_method = "send_binary"
  981. else:
  982. raise TypeError("data must be str or bytes")
  983. if raise_exceptions:
  984. if sys.version_info[:2] < (3, 11): # pragma: no cover
  985. raise ValueError("raise_exceptions requires at least Python 3.11")
  986. exceptions: list[Exception] = []
  987. for connection in connections:
  988. exception: Exception
  989. if connection.protocol.state is not OPEN:
  990. continue
  991. if connection.send_in_progress is not None:
  992. if raise_exceptions:
  993. exception = ConcurrencyError("sending a fragmented message")
  994. exceptions.append(exception)
  995. else:
  996. connection.logger.warning(
  997. "skipped broadcast: sending a fragmented message",
  998. )
  999. continue
  1000. try:
  1001. # Call connection.protocol.send_text or send_binary.
  1002. # Either way, message is already converted to bytes.
  1003. getattr(connection.protocol, send_method)(message)
  1004. connection.send_data()
  1005. except Exception as write_exception:
  1006. if raise_exceptions:
  1007. exception = RuntimeError("failed to write message")
  1008. exception.__cause__ = write_exception
  1009. exceptions.append(exception)
  1010. else:
  1011. connection.logger.warning(
  1012. "skipped broadcast: failed to write message: %s",
  1013. traceback.format_exception_only(write_exception)[0].strip(),
  1014. )
  1015. if raise_exceptions and exceptions:
  1016. raise ExceptionGroup("skipped broadcast", exceptions)
  1017. # Pretend that broadcast is actually defined in the server module.
  1018. broadcast.__module__ = "websockets.asyncio.server"