From 6637f6e9ebefd20ebfddfa59edfae704302dca46 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Fri, 27 Mar 2026 00:36:35 -0500 Subject: [PATCH] fix: disable autoconnect and set pool timeout on PooledPostgresqlDatabase (#80) - Set timeout=5 so pool exhaustion surfaces as an error instead of hanging forever - Set autoconnect=False to require explicit connection acquisition - Add HTTP middleware in main.py to open/close connections per request Closes #80 Co-Authored-By: Claude Sonnet 4.6 --- app/db_engine.py | 4 ++-- app/main.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/app/db_engine.py b/app/db_engine.py index 0e6790c..3b6645e 100644 --- a/app/db_engine.py +++ b/app/db_engine.py @@ -30,8 +30,8 @@ if DATABASE_TYPE.lower() == "postgresql": port=int(os.environ.get("POSTGRES_PORT", "5432")), max_connections=20, stale_timeout=300, # 5 minutes - timeout=0, - autoconnect=True, + timeout=5, + autoconnect=False, autorollback=True, # Automatically rollback failed transactions ) else: diff --git a/app/main.py b/app/main.py index 58a5ffe..dd23244 100644 --- a/app/main.py +++ b/app/main.py @@ -8,6 +8,8 @@ from fastapi import Depends, FastAPI, Request from fastapi.openapi.docs import get_swagger_ui_html from fastapi.openapi.utils import get_openapi +from .db_engine import db + # from fastapi.openapi.docs import get_swagger_ui_html # from fastapi.openapi.utils import get_openapi @@ -68,6 +70,17 @@ app = FastAPI( ) +@app.middleware("http") +async def db_connection_middleware(request: Request, call_next): + db.connect(reuse_if_open=True) + try: + response = await call_next(request) + finally: + if not db.is_closed(): + db.close() + return response + + logger.info(f"Starting up now...")