| 1 |
.. _closing: |
| 2 |
|
| 3 |
Connection closure |
| 4 |
================== |
| 5 |
|
| 6 |
Connection closure is a difficult part of the connection lifecycle |
| 7 |
with choices needing to be made by Hypercorn about how to respond and |
| 8 |
what to send to the ASGI application. |
| 9 |
|
| 10 |
Before a connection is fully closed, it is often 'half-closed' by one |
| 11 |
side sending an EOF (empty bytestring b""). If sent by the client |
| 12 |
Hypercorn will not expect any further messages, but will allow |
| 13 |
messages to be sent to the client. This follows the HTTPWG guidance in |
| 14 |
`rfc.section.9.6.p.12 |
| 15 |
<https://github.com/httpwg/http-core/pull/431/files>`_. |
| 16 |
|
| 17 |
Client disconnection |
| 18 |
-------------------- |
| 19 |
|
| 20 |
If the client disconnects unexpectedly, i.e. whilst the server is |
| 21 |
still expecting to read or send data, the read/send socket action will |
| 22 |
raise an exception. This exception is caught and a Closed event is |
| 23 |
sent to the protocol. The protocol should then send each stream a |
| 24 |
StreamClosed event and delete the stream. |
| 25 |
|
| 26 |
Server disconnection |
| 27 |
-------------------- |
| 28 |
|
| 29 |
In the normal course of actions a stream should send a EndBody or |
| 30 |
EndData followed by a StreamClosed event to indicate that the stream |
| 31 |
has finished and the connection can be closed. However if the |
| 32 |
application errors the stream may only be able to send a StreamClosed |
| 33 |
event. Therefore the protocol only sends a StreamClosed event back to |
| 34 |
the stream on receipt of the StreamClosed from the stream. |
| 35 |
|
| 36 |
The protocol only sends a Closed event to the server if the connection |
| 37 |
must be closed, e.g. HTTP/1 without keep alive or an error. |
| 38 |
|
| 39 |
ASGI messages |
| 40 |
------------- |
| 41 |
|
| 42 |
I've chosen to allow ASGI applications to continue to send messages to |
| 43 |
the server after the connection has closed and after the server has |
| 44 |
sent a disconnect message. Specifically Hypercorn will not error and |
| 45 |
instead no-op on receipt. This ensures that there isn't a race |
| 46 |
condition after the server has sent the disconnect message. |
| 47 |
|
| 48 |
Hypercorn guarantees to send the disconnect message, and send it only |
| 49 |
once, to each application instance. This message will be sent on |
| 50 |
closure of the connection (either on client or server closure). |