]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
fix(pool): trade off usage timing precision for robustness
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 6 Oct 2023 12:36:43 +0000 (14:36 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 6 Oct 2023 18:35:29 +0000 (20:35 +0200)
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.

psycopg_pool/psycopg_pool/pool.py
psycopg_pool/psycopg_pool/pool_async.py

index a7bc5b0de5d8911220b789221dae7b192fe2f2bd..aeafec87eb925a3fa05f7bc6c28459f8fd66f85d 100644 (file)
@@ -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.
index 76a2cf489e5ddf4644cf34bd3cd19c46fcd2bb85..6f1b5f5145f0586d49f55040503dbc5ecda2d10b 100644 (file)
@@ -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)