Debian Codegraph @

docs/topics/design.rst

raw
1 :orphan:
2
3 Design (legacy)
4 ===============
5
6 .. currentmodule:: websockets.legacy
7
8 This document describes the design of the legacy implementation of websockets.
9 It assumes familiarity with the specification of the WebSocket protocol in
10 :rfc:`6455`.
11
12 It's primarily intended at maintainers. It may also be useful for users who
13 wish to understand what happens under the hood.
14
15 .. warning::
16
17 Internals described in this document may change at any time.
18
19 Backwards compatibility is only guaranteed for :doc:`public APIs
20 <../reference/index>`.
21
22 Lifecycle
23 ---------
24
25 State
26 .....
27
28 WebSocket connections go through a trivial state machine:
29
30 - ``CONNECTING``: initial state,
31 - ``OPEN``: when the opening handshake is complete,
32 - ``CLOSING``: when the closing handshake is started,
33 - ``CLOSED``: when the TCP connection is closed.
34
35 Transitions happen in the following places:
36
37 - ``CONNECTING -> OPEN``: in
38 :meth:`~protocol.WebSocketCommonProtocol.connection_open` which runs when the
39 :ref:`opening handshake <opening-handshake>` completes and the WebSocket
40 connection is established — not to be confused with
41 :meth:`~asyncio.BaseProtocol.connection_made` which runs when the TCP
42 connection is established;
43 - ``OPEN -> CLOSING``: in :meth:`~protocol.WebSocketCommonProtocol.write_frame`
44 immediately before sending a close frame; since receiving a close frame
45 triggers sending a close frame, this does the right thing regardless of which
46 side started the :ref:`closing handshake <closing-handshake>`; also in
47 :meth:`~protocol.WebSocketCommonProtocol.fail_connection` which duplicates a
48 few lines of code from ``write_close_frame()`` and ``write_frame()``;
49 - ``* -> CLOSED``: in :meth:`~protocol.WebSocketCommonProtocol.connection_lost`
50 which is always called exactly once when the TCP connection is closed.
51
52 Coroutines
53 ..........
54
55 The following diagram shows which coroutines are running at each stage of the
56 connection lifecycle on the client side.
57
58 .. image:: lifecycle.svg
59 :target: _images/lifecycle.svg
60
61 The lifecycle is identical on the server side, except inversion of control makes
62 the equivalent of :meth:`~client.connect` implicit.
63
64 Coroutines shown in green are called by the application. Multiple coroutines
65 may interact with the WebSocket connection concurrently.
66
67 Coroutines shown in gray manage the connection. When the opening handshake
68 succeeds, :meth:`~protocol.WebSocketCommonProtocol.connection_open` starts two
69 tasks:
70
71 - :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` runs
72 :meth:`~protocol.WebSocketCommonProtocol.transfer_data` which handles incoming
73 data and lets :meth:`~protocol.WebSocketCommonProtocol.recv` consume it. It
74 may be canceled to terminate the connection. It never exits with an exception
75 other than :exc:`~asyncio.CancelledError`. See :ref:`data transfer
76 <data-transfer>` below.
77
78 - :attr:`~protocol.WebSocketCommonProtocol.keepalive_ping_task` runs
79 :meth:`~protocol.WebSocketCommonProtocol.keepalive_ping` which sends Ping
80 frames at regular intervals and ensures that corresponding Pong frames are
81 received. It is canceled when the connection terminates. It never exits with
82 an exception other than :exc:`~asyncio.CancelledError`.
83
84 - :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` runs
85 :meth:`~protocol.WebSocketCommonProtocol.close_connection` which waits for the
86 data transfer to terminate, then takes care of closing the TCP connection. It
87 must not be canceled. It never exits with an exception. See :ref:`connection
88 termination <connection-termination>` below.
89
90 Besides, :meth:`~protocol.WebSocketCommonProtocol.fail_connection` starts the
91 same :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` when the
92 opening handshake fails, in order to close the TCP connection.
93
94 Splitting the responsibilities between two tasks makes it easier to guarantee
95 that websockets can terminate connections:
96
97 - within a fixed timeout,
98 - without leaking pending tasks,
99 - without leaking open TCP connections,
100
101 regardless of whether the connection terminates normally or abnormally.
102
103 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` completes when no
104 more data will be received on the connection. Under normal circumstances, it
105 exits after exchanging close frames.
106
107 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` completes when
108 the TCP connection is closed.
109
110
111 .. _opening-handshake:
112
113 Opening handshake
114 -----------------
115
116 websockets performs the opening handshake when establishing a WebSocket
117 connection. On the client side, :meth:`~client.connect` executes it before
118 returning the protocol to the caller. On the server side, it's executed before
119 passing the protocol to the ``ws_handler`` coroutine handling the connection.
120
121 While the opening handshake is asymmetrical — the client sends an HTTP Upgrade
122 request and the server replies with an HTTP Switching Protocols response —
123 websockets aims at keeping the implementation of both sides consistent with
124 one another.
125
126 On the client side, :meth:`~client.WebSocketClientProtocol.handshake`:
127
128 - builds an HTTP request based on the ``uri`` and parameters passed to
129 :meth:`~client.connect`;
130 - writes the HTTP request to the network;
131 - reads an HTTP response from the network;
132 - checks the HTTP response, validates ``extensions`` and ``subprotocol``, and
133 configures the protocol accordingly;
134 - moves to the ``OPEN`` state.
135
136 On the server side, :meth:`~server.WebSocketServerProtocol.handshake`:
137
138 - reads an HTTP request from the network;
139 - calls :meth:`~server.WebSocketServerProtocol.process_request` which may abort
140 the WebSocket handshake and return an HTTP response instead; this hook only
141 makes sense on the server side;
142 - checks the HTTP request, negotiates ``extensions`` and ``subprotocol``, and
143 configures the protocol accordingly;
144 - builds an HTTP response based on the above and parameters passed to
145 :meth:`~server.serve`;
146 - writes the HTTP response to the network;
147 - moves to the ``OPEN`` state;
148 - returns the ``path`` part of the ``uri``.
149
150 The most significant asymmetry between the two sides of the opening handshake
151 lies in the negotiation of extensions and, to a lesser extent, of the
152 subprotocol. The server knows everything about both sides and decides what the
153 parameters should be for the connection. The client merely applies them.
154
155 If anything goes wrong during the opening handshake, websockets :ref:`fails
156 the connection <connection-failure>`.
157
158
159 .. _data-transfer:
160
161 Data transfer
162 -------------
163
164 Symmetry
165 ........
166
167 Once the opening handshake has completed, the WebSocket protocol enters the
168 data transfer phase. This part is almost symmetrical. There are only two
169 differences between a server and a client:
170
171 - `client-to-server masking`_: the client masks outgoing frames; the server
172 unmasks incoming frames;
173 - `closing the TCP connection`_: the server closes the connection immediately;
174 the client waits for the server to do it.
175
176 .. _client-to-server masking: https://datatracker.ietf.org/doc/html/rfc6455.html#section-5.3
177 .. _closing the TCP connection: https://datatracker.ietf.org/doc/html/rfc6455.html#section-5.5.1
178
179 These differences are so minor that all the logic for `data framing`_, for
180 `sending and receiving data`_ and for `closing the connection`_ is implemented
181 in the same class, :class:`~protocol.WebSocketCommonProtocol`.
182
183 .. _data framing: https://datatracker.ietf.org/doc/html/rfc6455.html#section-5
184 .. _sending and receiving data: https://datatracker.ietf.org/doc/html/rfc6455.html#section-6
185 .. _closing the connection: https://datatracker.ietf.org/doc/html/rfc6455.html#section-7
186
187 The :attr:`~protocol.WebSocketCommonProtocol.is_client` attribute tells which
188 side a protocol instance is managing. This attribute is defined on the
189 :attr:`~server.WebSocketServerProtocol` and
190 :attr:`~client.WebSocketClientProtocol` classes.
191
192 Data flow
193 .........
194
195 The following diagram shows how data flows between an application built on top
196 of websockets and a remote endpoint. It applies regardless of which side is
197 the server or the client.
198
199 .. image:: protocol.svg
200 :target: _images/protocol.svg
201
202 Public methods are shown in green, private methods in yellow, and buffers in
203 orange. Methods related to connection termination are omitted; connection
204 termination is discussed in another section below.
205
206 Receiving data
207 ..............
208
209 The left side of the diagram shows how websockets receives data.
210
211 Incoming data is written to a :class:`~asyncio.StreamReader` in order to
212 implement flow control and provide backpressure on the TCP connection.
213
214 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task`, which is started
215 when the WebSocket connection is established, processes this data.
216
217 When it receives data frames, it reassembles fragments and puts the resulting
218 messages in the :attr:`~protocol.WebSocketCommonProtocol.messages` queue.
219
220 When it encounters a control frame:
221
222 - if it's a close frame, it starts the closing handshake;
223 - if it's a ping frame, it answers with a pong frame;
224 - if it's a pong frame, it acknowledges the corresponding ping (unless it's an
225 unsolicited pong).
226
227 Running this process in a task guarantees that control frames are processed
228 promptly. Without such a task, websockets would depend on the application to
229 drive the connection by having exactly one coroutine awaiting
230 :meth:`~protocol.WebSocketCommonProtocol.recv` at any time. While this happens
231 naturally in many use cases, it cannot be relied upon.
232
233 Then :meth:`~protocol.WebSocketCommonProtocol.recv` fetches the next message
234 from the :attr:`~protocol.WebSocketCommonProtocol.messages` queue, with some
235 complexity added for handling backpressure and termination correctly.
236
237 Sending data
238 ............
239
240 The right side of the diagram shows how websockets sends data.
241
242 :meth:`~protocol.WebSocketCommonProtocol.send` writes one or several data frames
243 containing the message. While sending a fragmented message, concurrent calls to
244 :meth:`~protocol.WebSocketCommonProtocol.send` are put on hold until all
245 fragments are sent. This makes concurrent calls safe.
246
247 :meth:`~protocol.WebSocketCommonProtocol.ping` writes a ping frame and yields a
248 :class:`~asyncio.Future` which will be completed when a matching pong frame is
249 received.
250
251 :meth:`~protocol.WebSocketCommonProtocol.pong` writes a pong frame.
252
253 :meth:`~protocol.WebSocketCommonProtocol.close` writes a close frame and waits
254 for the TCP connection to terminate.
255
256 Outgoing data is written to a :class:`~asyncio.StreamWriter` in order to
257 implement flow control and provide backpressure from the TCP connection.
258
259 .. _closing-handshake:
260
261 Closing handshake
262 .................
263
264 When the other side of the connection initiates the closing handshake,
265 :meth:`~protocol.WebSocketCommonProtocol.read_message` receives a close frame
266 while in the ``OPEN`` state. It moves to the ``CLOSING`` state, sends a close
267 frame, and returns :obj:`None`, causing
268 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` to terminate.
269
270 When this side of the connection initiates the closing handshake with
271 :meth:`~protocol.WebSocketCommonProtocol.close`, it moves to the ``CLOSING``
272 state and sends a close frame. When the other side sends a close frame,
273 :meth:`~protocol.WebSocketCommonProtocol.read_message` receives it in the
274 ``CLOSING`` state and returns :obj:`None`, also causing
275 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` to terminate.
276
277 If the other side doesn't send a close frame within the connection's close
278 timeout, websockets :ref:`fails the connection <connection-failure>`.
279
280 The closing handshake can take up to ``2 * close_timeout``: one
281 ``close_timeout`` to write a close frame and one ``close_timeout`` to receive
282 a close frame.
283
284 Then websockets terminates the TCP connection.
285
286
287 .. _connection-termination:
288
289 Connection termination
290 ----------------------
291
292 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task`, which is
293 started when the WebSocket connection is established, is responsible for
294 eventually closing the TCP connection.
295
296 First :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` waits for
297 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` to terminate, which
298 may happen as a result of:
299
300 - a successful closing handshake: as explained above, this exits the infinite
301 loop in :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task`;
302 - a timeout while waiting for the closing handshake to complete: this cancels
303 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task`;
304 - a protocol error, including connection errors: depending on the exception,
305 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` :ref:`fails the
306 connection <connection-failure>` with a suitable code and exits.
307
308 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` is separate from
309 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` to make it easier
310 to implement the timeout on the closing handshake. Canceling
311 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` creates no risk of
312 canceling :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` and
313 failing to close the TCP connection, thus leaking resources.
314
315 Then :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` cancels
316 :meth:`~protocol.WebSocketCommonProtocol.keepalive_ping`. This task has no
317 protocol compliance responsibilities. Terminating it to avoid leaking it is the
318 only concern.
319
320 Terminating the TCP connection can take up to ``2 * close_timeout`` on the
321 server side and ``3 * close_timeout`` on the client side. Clients start by
322 waiting for the server to close the connection, hence the extra
323 ``close_timeout``. Then both sides go through the following steps until the
324 TCP connection is lost: half-closing the connection (only for non-TLS
325 connections), closing the connection, aborting the connection. At this point
326 the connection drops regardless of what happens on the network.
327
328
329 .. _connection-failure:
330
331 Connection failure
332 ------------------
333
334 If the opening handshake doesn't complete successfully, websockets fails the
335 connection by closing the TCP connection.
336
337 Once the opening handshake has completed, websockets fails the connection by
338 canceling :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` and
339 sending a close frame if appropriate.
340
341 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` exits, unblocking
342 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task`, which closes
343 the TCP connection.
344
345
346 .. _server-shutdown:
347
348 Server shutdown
349 ---------------
350
351 :class:`~server.WebSocketServer` closes asynchronously like
352 :class:`asyncio.Server`. The shutdown happen in two steps:
353
354 1. Stop listening and accepting new connections;
355 2. Close established connections with close code 1001 (going away) or, if
356 the opening handshake is still in progress, with HTTP status code 503
357 (Service Unavailable).
358
359 The first call to :class:`~server.WebSocketServer.close` starts a task that
360 performs this sequence. Further calls are ignored. This is the easiest way to
361 make :class:`~server.WebSocketServer.close` and
362 :class:`~server.WebSocketServer.wait_closed` idempotent.
363
364
365 .. _cancellation:
366
367 Cancellation
368 ------------
369
370 User code
371 .........
372
373 websockets provides a WebSocket application server. It manages connections and
374 passes them to user-provided connection handlers. This is an *inversion of
375 control* scenario: library code calls user code.
376
377 If a connection drops, the corresponding handler should terminate. If the
378 server shuts down, all connection handlers must terminate. Canceling
379 connection handlers would terminate them.
380
381 However, using cancellation for this purpose would require all connection
382 handlers to handle it properly. For example, if a connection handler starts
383 some tasks, it should catch :exc:`~asyncio.CancelledError`, terminate or
384 cancel these tasks, and then re-raise the exception.
385
386 Cancellation is tricky in :mod:`asyncio` applications, especially when it
387 interacts with finalization logic. In the example above, what if a handler
388 gets interrupted with :exc:`~asyncio.CancelledError` while it's finalizing
389 the tasks it started, after detecting that the connection dropped?
390
391 websockets considers that cancellation may only be triggered by the caller of
392 a coroutine when it doesn't care about the results of that coroutine anymore.
393 (Source: `Guido van Rossum <https://groups.google.com/forum/#!msg
394 /python-tulip/LZQe38CR3bg/7qZ1p_q5yycJ>`_). Since connection handlers run
395 arbitrary user code, websockets has no way of deciding whether that code is
396 still doing something worth caring about.
397
398 For these reasons, websockets never cancels connection handlers. Instead it
399 expects them to detect when the connection is closed, execute finalization
400 logic if needed, and exit.
401
402 Conversely, cancellation isn't a concern for WebSocket clients because they
403 don't involve inversion of control.
404
405 Library
406 .......
407
408 Most :doc:`public APIs <../reference/index>` of websockets are coroutines.
409 They may be canceled, for example if the user starts a task that calls these
410 coroutines and cancels the task later. websockets must handle this situation.
411
412 Cancellation during the opening handshake is handled like any other exception:
413 the TCP connection is closed and the exception is re-raised. This can only
414 happen on the client side. On the server side, the opening handshake is
415 managed by websockets and nothing results in a cancellation.
416
417 Once the WebSocket connection is established, internal tasks
418 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` and
419 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` mustn't get
420 accidentally canceled if a coroutine that awaits them is canceled. In other
421 words, they must be shielded from cancellation.
422
423 :meth:`~protocol.WebSocketCommonProtocol.recv` waits for the next message in the
424 queue or for :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` to
425 terminate, whichever comes first. It relies on :func:`~asyncio.wait` for waiting
426 on two futures in parallel. As a consequence, even though it's waiting on a
427 :class:`~asyncio.Future` signaling the next message and on
428 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task`, it doesn't
429 propagate cancellation to them.
430
431 :meth:`~protocol.WebSocketCommonProtocol.ensure_open` is called by
432 :meth:`~protocol.WebSocketCommonProtocol.send`,
433 :meth:`~protocol.WebSocketCommonProtocol.ping`, and
434 :meth:`~protocol.WebSocketCommonProtocol.pong`. When the connection state is
435 ``CLOSING``, it waits for
436 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` but shields it to
437 prevent cancellation.
438
439 :meth:`~protocol.WebSocketCommonProtocol.close` waits for the data transfer task
440 to terminate with :func:`~asyncio.timeout`. If it's canceled or if the timeout
441 elapses, :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` is
442 canceled, which is correct at this point.
443 :meth:`~protocol.WebSocketCommonProtocol.close` then waits for
444 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` but shields it
445 to prevent cancellation.
446
447 :meth:`~protocol.WebSocketCommonProtocol.close` and
448 :meth:`~protocol.WebSocketCommonProtocol.fail_connection` are the only places
449 where :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` may be
450 canceled.
451
452 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task` starts by
453 waiting for :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task`. It
454 catches :exc:`~asyncio.CancelledError` to prevent a cancellation of
455 :attr:`~protocol.WebSocketCommonProtocol.transfer_data_task` from propagating to
456 :attr:`~protocol.WebSocketCommonProtocol.close_connection_task`.
457
458 .. _backpressure:
459
460 Backpressure
461 ------------
462
463 .. note::
464
465 This section discusses backpressure from the perspective of a server but
466 the concept applies to clients symmetrically.
467
468 With a naive implementation, if a server receives inputs faster than it can
469 process them, or if it generates outputs faster than it can send them, data
470 accumulates in buffers, eventually causing the server to run out of memory and
471 crash.
472
473 The solution to this problem is backpressure. Any part of the server that
474 receives inputs faster than it can process them and send the outputs
475 must propagate that information back to the previous part in the chain.
476
477 websockets is designed to make it easy to get backpressure right.
478
479 For incoming data, websockets builds upon :class:`~asyncio.StreamReader` which
480 propagates backpressure to its own buffer and to the TCP stream. Frames are
481 parsed from the input stream and added to a bounded queue. If the queue fills
482 up, parsing halts until the application reads a frame.
483
484 For outgoing data, websockets builds upon :class:`~asyncio.StreamWriter` which
485 implements flow control. If the output buffers grow too large, it waits until
486 they're drained. That's why all APIs that write frames are asynchronous.
487
488 Of course, it's still possible for an application to create its own unbounded
489 buffers and break the backpressure. Be careful with queues.
490
491 Concurrency
492 -----------
493
494 Awaiting any combination of :meth:`~protocol.WebSocketCommonProtocol.recv`,
495 :meth:`~protocol.WebSocketCommonProtocol.send`,
496 :meth:`~protocol.WebSocketCommonProtocol.close`
497 :meth:`~protocol.WebSocketCommonProtocol.ping`, or
498 :meth:`~protocol.WebSocketCommonProtocol.pong` concurrently is safe, including
499 multiple calls to the same method, with one exception and one limitation.
500
501 * **Only one coroutine can receive messages at a time.** This constraint avoids
502 non-deterministic behavior (and simplifies the implementation). If a coroutine
503 is awaiting :meth:`~protocol.WebSocketCommonProtocol.recv`, awaiting it again
504 in another coroutine raises :exc:`RuntimeError`.
505
506 * **Sending a fragmented message forces serialization.** Indeed, the WebSocket
507 protocol doesn't support multiplexing messages. If a coroutine is awaiting
508 :meth:`~protocol.WebSocketCommonProtocol.send` to send a fragmented message,
509 awaiting it again in another coroutine waits until the first call completes.
510 This will be transparent in many cases. It may be a concern if the fragmented
511 message is generated slowly by an asynchronous iterator.
512
513 Receiving frames is independent from sending frames. This isolates
514 :meth:`~protocol.WebSocketCommonProtocol.recv`, which receives frames, from the
515 other methods, which send frames.
516
517 While the connection is open, each frame is sent with a single write. Combined
518 with the concurrency model of :mod:`asyncio`, this enforces serialization. The
519 only other requirement is to prevent interleaving other data frames in the
520 middle of a fragmented message.
521
522 After the connection is closed, sending a frame raises
523 :exc:`~websockets.exceptions.ConnectionClosed`, which is safe.