This commit is contained in:
stijndcl 2022-07-27 21:10:43 +02:00
parent ea4181eac0
commit db499f3742
20 changed files with 350 additions and 101 deletions

View file

@ -1,14 +1,18 @@
from abc import ABC, abstractmethod
from typing import Generic, TypeVar
from overrides import overrides
from sqlalchemy.ext.asyncio import AsyncSession
from database.crud import ufora_courses
from database.crud import ufora_courses, wordle
from database.mongo_types import MongoDatabase
__all__ = ["CacheManager"]
__all__ = ["CacheManager", "UforaCourseCache"]
T = TypeVar("T")
class DatabaseCache(ABC):
class DatabaseCache(ABC, Generic[T]):
"""Base class for a simple cache-like structure
The goal of this class is to store data for Discord auto-completion results
@ -31,10 +35,10 @@ class DatabaseCache(ABC):
self.data.clear()
@abstractmethod
async def refresh(self, database_session: AsyncSession):
async def refresh(self, database_session: T):
"""Refresh the data stored in this cache"""
async def invalidate(self, database_session: AsyncSession):
async def invalidate(self, database_session: T):
"""Invalidate the data stored in this cache"""
await self.refresh(database_session)
@ -45,7 +49,7 @@ class DatabaseCache(ABC):
return [self.data[index] for index, value in enumerate(self.data_transformed) if query in value]
class UforaCourseCache(DatabaseCache):
class UforaCourseCache(DatabaseCache[AsyncSession]):
"""Cache to store the names of Ufora courses"""
# Also store the aliases to add additional support
@ -90,14 +94,26 @@ class UforaCourseCache(DatabaseCache):
return sorted(list(results))
class WordleCache(DatabaseCache[MongoDatabase]):
"""Cache to store the current daily Wordle word"""
async def refresh(self, database_session: MongoDatabase):
word = await wordle.get_daily_word(database_session)
if word is not None:
self.data = [word]
class CacheManager:
"""Class that keeps track of all caches"""
ufora_courses: UforaCourseCache
wordle_word: WordleCache
def __init__(self):
self.ufora_courses = UforaCourseCache()
self.wordle_word = WordleCache()
async def initialize_caches(self, database_session: AsyncSession):
async def initialize_caches(self, postgres_session: AsyncSession, mongo_db: MongoDatabase):
"""Initialize the contents of all caches"""
await self.ufora_courses.refresh(database_session)
await self.ufora_courses.refresh(postgres_session)
await self.wordle_word.refresh(mongo_db)