Debian Codegraph @

src/websockets/sync/connection.py

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