Skip to content

Avoid leaking connections if _can_use_connection fails #1269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 28 additions & 23 deletions asyncpg/connect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1071,30 +1071,35 @@ async def _connect(*, loop, connection_class, record_class, **kwargs):
candidates = []
chosen_connection = None
last_error = None
for addr in addrs:
try:
conn = await _connect_addr(
addr=addr,
loop=loop,
params=params,
config=config,
connection_class=connection_class,
record_class=record_class,
try:
for addr in addrs:
try:
conn = await _connect_addr(
addr=addr,
loop=loop,
params=params,
config=config,
connection_class=connection_class,
record_class=record_class,
)
candidates.append(conn)
if await _can_use_connection(conn, target_attr):
chosen_connection = conn
break
except OSError as ex:
last_error = ex
else:
if target_attr == SessionAttribute.prefer_standby and candidates:
chosen_connection = random.choice(candidates)
finally:

async def _close_candidates(conns, chosen):
await asyncio.gather(
*(c.close() for c in conns if c is not chosen),
return_exceptions=True
)
candidates.append(conn)
if await _can_use_connection(conn, target_attr):
chosen_connection = conn
break
except OSError as ex:
last_error = ex
else:
if target_attr == SessionAttribute.prefer_standby and candidates:
chosen_connection = random.choice(candidates)

await asyncio.gather(
*(c.close() for c in candidates if c is not chosen_connection),
return_exceptions=True
)
if candidates:
asyncio.create_task(_close_candidates(candidates, chosen_connection))

if chosen_connection:
return chosen_connection
Expand Down