@@ -364,21 +364,15 @@ def _cleanup(self) -> None:
364
364
connections = {}
365
365
deadline = now - timeout
366
366
for key , conns in self ._conns .items ():
367
- alive = []
367
+ alive : List [ Tuple [ ResponseHandler , float ]] = []
368
368
for proto , use_time in conns :
369
- if proto .is_connected ():
370
- if use_time - deadline < 0 :
371
- transport = proto .transport
372
- proto .close ()
373
- if key .is_ssl and not self ._cleanup_closed_disabled :
374
- self ._cleanup_closed_transports .append (transport )
375
- else :
376
- alive .append ((proto , use_time ))
377
- else :
378
- transport = proto .transport
379
- proto .close ()
380
- if key .is_ssl and not self ._cleanup_closed_disabled :
381
- self ._cleanup_closed_transports .append (transport )
369
+ if proto .is_connected () and use_time - deadline >= 0 :
370
+ alive .append ((proto , use_time ))
371
+ continue
372
+ transport = proto .transport
373
+ proto .close ()
374
+ if not self ._cleanup_closed_disabled and key .is_ssl :
375
+ self ._cleanup_closed_transports .append (transport )
382
376
383
377
if alive :
384
378
connections [key ] = alive
@@ -584,6 +578,7 @@ async def connect(
584
578
return Connection (self , key , proto , self ._loop )
585
579
586
580
def _get (self , key : "ConnectionKey" ) -> Optional [ResponseHandler ]:
581
+ """Get next reusable connection for the key or None."""
587
582
try :
588
583
conns = self ._conns [key ]
589
584
except KeyError :
@@ -592,23 +587,20 @@ def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
592
587
t1 = self ._loop .time ()
593
588
while conns :
594
589
proto , t0 = conns .pop ()
595
- if proto .is_connected ():
596
- if t1 - t0 > self ._keepalive_timeout :
597
- transport = proto .transport
598
- proto .close ()
599
- # only for SSL transports
600
- if key .is_ssl and not self ._cleanup_closed_disabled :
601
- self ._cleanup_closed_transports .append (transport )
602
- else :
603
- if not conns :
604
- # The very last connection was reclaimed: drop the key
605
- del self ._conns [key ]
606
- return proto
607
- else :
608
- transport = proto .transport
609
- proto .close ()
610
- if key .is_ssl and not self ._cleanup_closed_disabled :
611
- self ._cleanup_closed_transports .append (transport )
590
+ # We will we reuse the connection if its connected and
591
+ # the keepalive timeout has not been exceeded
592
+ if proto .is_connected () and t1 - t0 <= self ._keepalive_timeout :
593
+ if not conns :
594
+ # The very last connection was reclaimed: drop the key
595
+ del self ._conns [key ]
596
+ return proto
597
+
598
+ # Connection cannot be reused, close it
599
+ transport = proto .transport
600
+ proto .close ()
601
+ # only for SSL transports
602
+ if not self ._cleanup_closed_disabled and key .is_ssl :
603
+ self ._cleanup_closed_transports .append (transport )
612
604
613
605
# No more connections: drop the key
614
606
del self ._conns [key ]
0 commit comments