Skip to content

Commit 49a15fc

Browse files
committed
Avoid leaking connections if _can_use_connection fails
1 parent 5b14653 commit 49a15fc

File tree

1 file changed

+28
-23
lines changed

1 file changed

+28
-23
lines changed

asyncpg/connect_utils.py

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,30 +1071,35 @@ async def _connect(*, loop, connection_class, record_class, **kwargs):
10711071
candidates = []
10721072
chosen_connection = None
10731073
last_error = None
1074-
for addr in addrs:
1075-
try:
1076-
conn = await _connect_addr(
1077-
addr=addr,
1078-
loop=loop,
1079-
params=params,
1080-
config=config,
1081-
connection_class=connection_class,
1082-
record_class=record_class,
1074+
try:
1075+
for addr in addrs:
1076+
try:
1077+
conn = await _connect_addr(
1078+
addr=addr,
1079+
loop=loop,
1080+
params=params,
1081+
config=config,
1082+
connection_class=connection_class,
1083+
record_class=record_class,
1084+
)
1085+
candidates.append(conn)
1086+
if await _can_use_connection(conn, target_attr):
1087+
chosen_connection = conn
1088+
break
1089+
except OSError as ex:
1090+
last_error = ex
1091+
else:
1092+
if target_attr == SessionAttribute.prefer_standby and candidates:
1093+
chosen_connection = random.choice(candidates)
1094+
finally:
1095+
1096+
async def _close_candidates(conns, chosen):
1097+
await asyncio.gather(
1098+
*(c.close() for c in conns if c is not chosen),
1099+
return_exceptions=True
10831100
)
1084-
candidates.append(conn)
1085-
if await _can_use_connection(conn, target_attr):
1086-
chosen_connection = conn
1087-
break
1088-
except OSError as ex:
1089-
last_error = ex
1090-
else:
1091-
if target_attr == SessionAttribute.prefer_standby and candidates:
1092-
chosen_connection = random.choice(candidates)
1093-
1094-
await asyncio.gather(
1095-
*(c.close() for c in candidates if c is not chosen_connection),
1096-
return_exceptions=True
1097-
)
1101+
if candidates:
1102+
asyncio.create_task(_close_candidates(candidates, chosen_connection))
10981103

10991104
if chosen_connection:
11001105
return chosen_connection

0 commit comments

Comments
 (0)