connection.py 48 KB

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