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.1.9~10 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f4c8697995af7b588e3c9b56c7506209295ef3fb;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 354cbd77c..a67e29adf 100644 --- a/psycopg_pool/psycopg_pool/pool.py +++ b/psycopg_pool/psycopg_pool/pool.py @@ -138,14 +138,14 @@ class ConnectionPool(BasePool[Connection[Any]]): 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) -> Connection[Any]: """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 a03b33d2f..03dd61e1c 100644 --- a/psycopg_pool/psycopg_pool/pool_async.py +++ b/psycopg_pool/psycopg_pool/pool_async.py @@ -116,14 +116,14 @@ class AsyncConnectionPool(BasePool[AsyncConnection[Any]]): self, timeout: Optional[float] = None ) -> AsyncIterator[AsyncConnection[Any]]: 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) -> AsyncConnection[Any]: logger.info("connection requested from %r", self.name)