Skip to content

Commit

Permalink
Simplify branching in the connector (#9629)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Nov 2, 2024
1 parent 4108ca5 commit c95c025
Showing 1 changed file with 23 additions and 31 deletions.
54 changes: 23 additions & 31 deletions aiohttp/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,21 +342,15 @@ def _cleanup(self) -> None:
connections = {}
deadline = now - timeout
for key, conns in self._conns.items():
alive = []
alive: List[Tuple[ResponseHandler, float]] = []
for proto, use_time in conns:
if proto.is_connected():
if use_time - deadline < 0:
transport = proto.transport
proto.close()
if key.is_ssl and not self._cleanup_closed_disabled:
self._cleanup_closed_transports.append(transport)
else:
alive.append((proto, use_time))
else:
transport = proto.transport
proto.close()
if key.is_ssl and not self._cleanup_closed_disabled:
self._cleanup_closed_transports.append(transport)
if proto.is_connected() and use_time - deadline >= 0:
alive.append((proto, use_time))
continue
transport = proto.transport
proto.close()
if not self._cleanup_closed_disabled and key.is_ssl:
self._cleanup_closed_transports.append(transport)

if alive:
connections[key] = alive
Expand Down Expand Up @@ -599,6 +593,7 @@ async def _wait_for_available_connection(
await trace.send_connection_queued_end()

def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
"""Get next reusable connection for the key or None."""
try:
conns = self._conns[key]
except KeyError:
Expand All @@ -607,23 +602,20 @@ def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
t1 = self._loop.time()
while conns:
proto, t0 = conns.pop()
if proto.is_connected():
if t1 - t0 > self._keepalive_timeout:
transport = proto.transport
proto.close()
# only for SSL transports
if key.is_ssl and not self._cleanup_closed_disabled:
self._cleanup_closed_transports.append(transport)
else:
if not conns:
# The very last connection was reclaimed: drop the key
del self._conns[key]
return proto
else:
transport = proto.transport
proto.close()
if key.is_ssl and not self._cleanup_closed_disabled:
self._cleanup_closed_transports.append(transport)
# We will we reuse the connection if its connected and
# the keepalive timeout has not been exceeded
if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:
if not conns:
# The very last connection was reclaimed: drop the key
del self._conns[key]
return proto

# Connection cannot be reused, close it
transport = proto.transport
proto.close()
# only for SSL transports
if not self._cleanup_closed_disabled and key.is_ssl:
self._cleanup_closed_transports.append(transport)

# No more connections: drop the key
del self._conns[key]
Expand Down

0 comments on commit c95c025

Please sign in to comment.