From: Daniele Varrazzo Date: Fri, 6 Oct 2023 12:36:43 +0000 (+0200) Subject: fix(pool): trade off usage timing precision for robustness X-Git-Tag: pool-3.2.0~23 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=c0845ab901763659c42bc8b7c6bd134297ac70c5;p=thirdparty%2Fpsycopg.git fix(pool): trade off usage timing precision for robustness It is unlikely that the statements we shuffled around will fail; however, let's do the right thing and make sure that, if they do, the getconn/putconn pair remains matched. --- diff --git a/psycopg_pool/psycopg_pool/pool.py b/psycopg_pool/psycopg_pool/pool.py index a7bc5b0de..aeafec87e 100644 --- a/psycopg_pool/psycopg_pool/pool.py +++ b/psycopg_pool/psycopg_pool/pool.py @@ -192,14 +192,14 @@ class ConnectionPool(Generic[CT], BasePool): in working state, replace it with a new one. """ conn = self.getconn(timeout=timeout) - t0 = monotonic() try: + t0 = monotonic() with conn: yield conn finally: + self.putconn(conn) t1 = monotonic() self._stats[self._USAGE_MS] += int(1000.0 * (t1 - t0)) - self.putconn(conn) def getconn(self, timeout: Optional[float] = None) -> CT: """Obtain a connection from the pool. diff --git a/psycopg_pool/psycopg_pool/pool_async.py b/psycopg_pool/psycopg_pool/pool_async.py index 76a2cf489..6f1b5f514 100644 --- a/psycopg_pool/psycopg_pool/pool_async.py +++ b/psycopg_pool/psycopg_pool/pool_async.py @@ -170,14 +170,14 @@ class AsyncConnectionPool(Generic[ACT], BasePool): @asynccontextmanager async def connection(self, timeout: Optional[float] = None) -> AsyncIterator[ACT]: conn = await self.getconn(timeout=timeout) - t0 = monotonic() try: + t0 = monotonic() async with conn: yield conn finally: + await self.putconn(conn) t1 = monotonic() self._stats[self._USAGE_MS] += int(1000.0 * (t1 - t0)) - await self.putconn(conn) async def getconn(self, timeout: Optional[float] = None) -> ACT: logger.info("connection requested from %r", self.name)