Close the socket when connection setup fails or is cancelled

MA
12d ago
+42-18

Summary

When connection setup fails after the socket is opened, the network backends can leave the socket open:

  • start_tls closed the stream only on Exception, so a cancelled handshake (asyncio.CancelledError, trio.Cancelled, or gevent.Timeout with the sync backend) left the TCP socket open. TrioStream.start_tls also built trio.SSLStream before the try, so an error from wrap_bio, for example on a malformed sni_hostname, leaked the socket as well.
  • connect_tcp and connect_unix_socket didn't close the socket when setsockopt raised for a socket_options entry. The error surfaces as ConnectError, and with retries configured every attempt leaks another socket.
  • SyncBackend.connect_unix_socket didn't close the socket when connect() failed, for example when the socket path doesn't exist.

Each of these now closes the socket and re-raises, catching BaseException like the existing cleanup in http11.py and connection_pool.py. In the anyio and trio backends the setsockopt cleanup runs outside fail_after, so a deadline that expires right after connecting can't turn the ConnectError into a ConnectTimeout.

No tests were added: like the existing start_tls failure handling, the new cleanup branches are marked # pragma: no cover.

Checklist

  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.