Implement connection tracking and graceful shutdown (sync server) #1615
+114
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi again, I implemented the connection tracking and graceful server shutdown procedure that I explained in issue #1488.
Server shutdown behavior
In the current version, the sync server does not have a way of tracking active connections. After launching the handler into a separate thread, the Server instance forgets about that connection. When we want to interrupt the server process with an interrupt, this can cause the process to continue running due to remaining active connections.
I updated
src/websockets/sync/server.py
to add logic for better handling graceful shutdowns. I also added optional argumentscode
andreason
that are passed to the clients withServerConnection.close(code, reason)
which allows additional information to be provided to the clients.Considerations
One of the things I considered when choosing how to update active connections is the existing API. I am not sure if there are users who instantiate Server() differently in their codebases, as opposed to the recommended
server = serve(socket, handle, ...)
approach. Therefore, I think there could be complaints about changing the signature ofconn_handler()
. So, I kept it unchanged. I did add an optional argument to the constructor ofServer
(as a keyword-only arg, so I think it won't be a problem either).I added some tests in
tests/sync/test_server.py
, and tried to match the style of existing tests there.Please let me know if anyone has suggestions on this.
Update: fixed a typo "sync server does have" -> "sync server does not have"