Description
On a multi-user system, starting the server may randomly fail with "Address already in use".
The reason is that init_httpserver selects the port via _find_http_port however, that port may no longer be available when _bind_http_server is called - especially due to the delay by being run in the event loop.
This is a classic race condition.
Reproduce
Start two instances in the background at the same time (via a script) and there is a significant chance to reproduce.
Expected behavior
The fallback port should be selected in a robust, race-condition free way.
Context
Unfortunately the obvious idea of selecting the fallback inside _bind_http_server_tcp and by also checking for listen() failing seems not possible because the code uses the selected port before _bind_http_server_tcp is called.
It might be possible for _find_http_port to store the socket and using add_sockets instead of listen as the most drop-in fix, however I have not tested if that can work.
I expect would also mean adding extra code to close the sockets manually at shutdown.
Description
On a multi-user system, starting the server may randomly fail with "Address already in use".
The reason is that init_httpserver selects the port via _find_http_port however, that port may no longer be available when _bind_http_server is called - especially due to the delay by being run in the event loop.
This is a classic race condition.
Reproduce
Start two instances in the background at the same time (via a script) and there is a significant chance to reproduce.
Expected behavior
The fallback port should be selected in a robust, race-condition free way.
Context
Unfortunately the obvious idea of selecting the fallback inside _bind_http_server_tcp and by also checking for listen() failing seems not possible because the code uses the selected port before _bind_http_server_tcp is called.
It might be possible for _find_http_port to store the socket and using add_sockets instead of listen as the most drop-in fix, however I have not tested if that can work.
I expect would also mean adding extra code to close the sockets manually at shutdown.