Bound PostgreSQL response waits and test paused database
This commit is contained in:
@@ -1,13 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from psycopg import AsyncConnection, OperationalError, waiting
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
|
||||
|
||||
DB_IO_TIMEOUT_SECONDS = float(
|
||||
os.getenv("DB_IO_TIMEOUT_SECONDS", "3")
|
||||
)
|
||||
|
||||
if DB_IO_TIMEOUT_SECONDS <= 0:
|
||||
raise ValueError("DB_IO_TIMEOUT_SECONDS must be positive")
|
||||
|
||||
|
||||
class DeadlineConnection(AsyncConnection):
|
||||
async def wait(self, gen, interval=0.1):
|
||||
try:
|
||||
async with asyncio.timeout(DB_IO_TIMEOUT_SECONDS):
|
||||
return await waiting.wait_async(
|
||||
gen,
|
||||
self.pgconn.socket,
|
||||
interval=interval,
|
||||
)
|
||||
|
||||
except TimeoutError:
|
||||
await self.close()
|
||||
raise OperationalError(
|
||||
"PostgreSQL response deadline exceeded"
|
||||
) from None
|
||||
|
||||
except asyncio.CancelledError:
|
||||
await self.close()
|
||||
raise
|
||||
|
||||
|
||||
pool = AsyncConnectionPool(
|
||||
conninfo="",
|
||||
connection_class=DeadlineConnection,
|
||||
kwargs={
|
||||
"host": os.getenv("PGHOST", "postgres"),
|
||||
"port": int(os.getenv("PGPORT", "5432")),
|
||||
@@ -41,4 +73,4 @@ async def close_db() -> None:
|
||||
|
||||
async def check_db() -> None:
|
||||
async with pool.connection() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
await conn.execute("SELECT 1")
|
||||
|
||||
Reference in New Issue
Block a user