Debian Codegraph @

src/websockets/trio/connection.py

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