diff --git a/app/api/dependencies.py b/app/api/dependencies.py index 6cc5981..bb6b308 100644 --- a/app/api/dependencies.py +++ b/app/api/dependencies.py @@ -255,7 +255,12 @@ async def get_user_by_api_key( # Update last used timestamp for the API key api_key_record.last_used_at = datetime.utcnow() - await db.commit() + try: + await db.commit() + except Exception: + # If commit fails, rollback and continue + await db.rollback() + # Don't fail the request just because timestamp update failed # Cache the user data for future requests await cache_user_async(api_key, user) diff --git a/app/core/database.py b/app/core/database.py index 31a466f..3eb5d1e 100644 --- a/app/core/database.py +++ b/app/core/database.py @@ -76,8 +76,15 @@ async def get_async_db(): async with AsyncSessionLocal() as session: try: yield session - finally: - await session.close() + except Exception: + # Rollback on any exception, but handle potential session state issues + try: + await session.rollback() + except Exception: + # If rollback fails (e.g., session already closed), ignore it + # The context manager will handle session cleanup + pass + raise @asynccontextmanager @@ -87,10 +94,14 @@ async def get_db_session(): try: yield session except Exception: - await session.rollback() + # Rollback on any exception, but handle potential session state issues + try: + await session.rollback() + except Exception: + # If rollback fails (e.g., session already closed), ignore it + # The context manager will handle session cleanup + pass raise - finally: - await session.close() def get_connection_info():