Skip to content

Commit

Permalink
Ensure database reconnection (#96)
Browse files Browse the repository at this point in the history
* Enable pool_pre_ping on database engine.

* Shorten DB timeouts.

* Add exception handling to DB snapshot task.

* Sync with Gameboard.
  • Loading branch information
sei-jvessella authored Feb 14, 2024
1 parent d4313f0 commit 54b39d6
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 deletions.
3 changes: 1 addition & 2 deletions gamebrain/clients/gameboardmodels.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,8 @@ class TeamChallengeScore(BaseModel):
class GameScoreTeam(BaseModel):
team: SimpleEntity
players: list[PlayerWithSponsor]
rank: int
overallScore: Score
totalTimeMs: int
cumulativeTimeMs: int
challenges: list[TeamChallengeScore]


Expand Down
9 changes: 8 additions & 1 deletion gamebrain/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# DM23-0100

import asyncio
import datetime
import json
import logging
import os.path
Expand Down Expand Up @@ -231,7 +232,13 @@ def _init_jwks(cls):
async def _db_sync_task(cls):
while True:
snapshot = await GameStateManager.snapshot_data()
await db.store_cache_snapshot(snapshot)
try:
await db.store_cache_snapshot(snapshot)
except Exception as e:
logging.exception(e)
else:
time = datetime.datetime.now(tz=datetime.timezone.utc)
logging.debug(f"Saved cache snapshot at {time}.")
await asyncio.sleep(10)

@classmethod
Expand Down
23 changes: 18 additions & 5 deletions gamebrain/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,24 @@ def _orm_obj_to_dict(cls, obj: orm_base) -> Dict:
return result

@classmethod
async def init_db(cls, connection_string: str = "", drop_first=False, echo=False):
async def init_db(
cls,
connection_string: str = "",
drop_first=False,
echo=False
):
if cls.engine and not drop_first:
return
cls.engine = create_async_engine(
connection_string, echo=echo, future=True)
connection_string,
echo=echo,
future=True,
pool_pre_ping=True,
pool_timeout=10,
connect_args={
"timeout": 10,
},
)
# I don't know if expire_on_commit is necessary here, but the SQLAlchemy docs used it.
cls.session_factory = sessionmaker(
cls.engine, expire_on_commit=False, class_=AsyncSession
Expand Down Expand Up @@ -332,9 +345,9 @@ async def deactivate_game_session(session_id: int):
# active_game = await get_team_game_session(session_id)
try:
session = (await DBManager.get_rows(
DBManager.GameSession,
DBManager.GameSession.id == session_id,
)
DBManager.GameSession,
DBManager.GameSession.id == session_id,
)
).pop()
except IndexError:
return
Expand Down

0 comments on commit 54b39d6

Please sign in to comment.