Skip to content

Commit e3ad12d

Browse files
committed
Make sure idle never-acquired pool connections are closed due to inactivity
The `max_inactive_connection_lifetime` setting currently fails to apply to the connection which were never acquired because `_setup_inactive_callback()` is only called in `release()`. Fixes: #389
1 parent ab0bc71 commit e3ad12d

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

asyncpg/pool.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ async def connect(self):
124124

125125
self._con = await self._pool._get_new_connection()
126126
self._generation = self._pool._generation
127+
self._maybe_cancel_inactive_callback()
128+
self._setup_inactive_callback()
127129

128130
async def acquire(self) -> PoolConnectionProxy:
129131
if self._con is None or self._con.is_closed():

tests/test_pool.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,24 @@ async def worker(pool):
668668

669669
self.assertGreaterEqual(N, 50)
670670

671+
async def test_pool_max_inactive_time_05(self):
672+
# Test that idle never-acquired connections abide by
673+
# the max inactive lifetime.
674+
async with self.create_pool(
675+
database='postgres', min_size=2, max_size=2,
676+
max_inactive_connection_lifetime=0.2) as pool:
677+
678+
self.assertIsNotNone(pool._holders[0]._con)
679+
self.assertIsNotNone(pool._holders[1]._con)
680+
681+
await pool.execute('SELECT pg_sleep(0.3)')
682+
await asyncio.sleep(0.3, loop=self.loop)
683+
684+
self.assertIs(pool._holders[0]._con, None)
685+
# The connection in the second holder was never used,
686+
# but should be closed nonetheless.
687+
self.assertIs(pool._holders[1]._con, None)
688+
671689
async def test_pool_handles_inactive_connection_errors(self):
672690
pool = await self.create_pool(database='postgres',
673691
min_size=1, max_size=1)

0 commit comments

Comments
 (0)