Skip to content

Commit

Permalink
🐛(api) fix not thread-safe database session singleton
Browse files Browse the repository at this point in the history
The singleton pattern is not thread-safe leading to database session
inconsistency during server heavy load (expired sessions, etc.)

See raised errors in SQLAlchemy docuementation:
https://docs.sqlalchemy.org/en/20/errors.html#error-bhk3
  • Loading branch information
jmaupetit committed Jul 19, 2024
1 parent fbdacff commit a07c905
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 19 deletions.
1 change: 1 addition & 0 deletions src/api/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ and this project adheres to
### Fixed

- Add relevant data examples for Swagger
- Improve database session management

## [0.10.0] - 2024-07-01

Expand Down
21 changes: 2 additions & 19 deletions src/api/qualicharge/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,6 @@ def get_engine(self, url: PostgresDsn, echo: bool = False) -> SAEngine:
return self._engine


class Session(metaclass=Singleton):
"""Database session singleton."""

_session: Optional[SMSession] = None

def get_session(self, engine: SAEngine) -> SMSession:
"""Get active session or create a new one."""
if self._session is None:
logger.debug("Create new session")
self._session = SMSession(bind=engine)
logger.debug("Getting database session %s", self._session)
return self._session


class SAQueryCounter:
"""Context manager to count SQLALchemy queries.
Expand Down Expand Up @@ -88,12 +74,9 @@ def get_engine() -> SAEngine:

def get_session() -> Generator[SMSession, None, None]:
"""Get database session."""
session = Session().get_session(get_engine())
logger.debug("Getting session %s", session)
try:
with SMSession(bind=get_engine()) as session:
logger.debug("Getting session %s", session)
yield session
finally:
session.close()


def is_alive() -> bool:
Expand Down

0 comments on commit a07c905

Please sign in to comment.