Skip to content

Commit

Permalink
Cache calls to get_team_game_session.
Browse files Browse the repository at this point in the history
  • Loading branch information
sei-jvessella committed Apr 23, 2024
1 parent d4149ec commit 862ed1a
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions gamebrain/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

# DM23-0100

from asyncio import Lock
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
Expand Down Expand Up @@ -194,6 +195,30 @@ async def delete_where(cls, orm_class: orm_base, *args):
await session.commit()


class TeamSessionCache:
_cache: dict[str, dict] = {}
_cache_lock: Lock = Lock()

@classmethod
async def remove(cls, team_ids: [str]):
async with cls._cache_lock:
for team_id in team_ids:
try:
del cls._cache[team_id]
except KeyError:
...

@classmethod
async def set(cls, team_id: str, game_session: dict):
async with cls._cache_lock:
cls._cache[team_id] = game_session

@classmethod
async def get(cls, team_id: str) -> dict | None:
async with cls._cache_lock:
return cls._cache.get(team_id)


async def store_event(team_id: str, message: str):
received_time = datetime.now(timezone.utc)
event = [
Expand Down Expand Up @@ -291,6 +316,7 @@ async def store_game_session(
)
merged_session_data = await DBManager.merge_rows([session_data])

await TeamSessionCache.remove(team_ids)
for team_id in team_ids:
await store_team(
team_id,
Expand All @@ -301,18 +327,24 @@ async def store_game_session(
await store_players(players)


async def get_team_game_session(team_id: str):
async def get_team_game_session(team_id: str) -> dict:
game_session = await TeamSessionCache.get(team_id)
if game_session:
return game_session

team = await get_team(team_id)
if not team:
return None
try:
return (
game_session = (
await DBManager.get_rows(
DBManager.GameSession,
DBManager.GameSession.id == team["game_session_id"],
DBManager.GameSession.active == True,
)
).pop()
await TeamSessionCache.set(team_id, game_session)
return game_session
except IndexError:
return None

Expand Down

0 comments on commit 862ed1a

Please sign in to comment.