From 58607ce91debe1ccc1010a666fa18cde9b2b8543 Mon Sep 17 00:00:00 2001 From: Nikita Ilyasov Date: Tue, 23 Jul 2019 17:12:19 +0300 Subject: [PATCH 1/2] fixes leaking connections https://bugs.python.org/issue37658 https://github.com/MagicStack/asyncpg/issues/467 --- asyncpg/connect_utils.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/asyncpg/connect_utils.py b/asyncpg/connect_utils.py index 3b5b725e..f90f81b7 100644 --- a/asyncpg/connect_utils.py +++ b/asyncpg/connect_utils.py @@ -508,9 +508,15 @@ async def _connect_addr(*, addr, loop, timeout, params, config, else: connector = loop.create_connection(proto_factory, *addr) + connector = asyncio.ensure_future(connector) + before = time.monotonic() - tr, pr = await asyncio.wait_for( - connector, timeout=timeout, loop=loop) + try: + tr, pr = await asyncio.wait_for( + connector, timeout=timeout, loop=loop) + except asyncio.CancelledError: + connector.add_done_callback(_close_leaked_connection) + raise timeout -= time.monotonic() - before try: @@ -646,3 +652,12 @@ def _create_future(loop): return asyncio.Future(loop=loop) else: return create_future() + + +def _close_leaked_connection(fut): + try: + tr, pr = fut.result() + if tr: + tr.close() + except asyncio.CancelledError: + pass # hide the exception From 07130d8112dc33c8a6f9226577bb488ff53bb7ec Mon Sep 17 00:00:00 2001 From: Nikita Ilyasov Date: Tue, 23 Jul 2019 17:54:38 +0300 Subject: [PATCH 2/2] adds missing space --- asyncpg/connect_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asyncpg/connect_utils.py b/asyncpg/connect_utils.py index f90f81b7..7c549935 100644 --- a/asyncpg/connect_utils.py +++ b/asyncpg/connect_utils.py @@ -660,4 +660,4 @@ def _close_leaked_connection(fut): if tr: tr.close() except asyncio.CancelledError: - pass # hide the exception + pass # hide the exception