Debian Codegraph @

src/websockets/asyncio/connection.py

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