Source code for sidequest_bot.config_cache

 1"""TTL cache of guild configs so hot paths (every message) don't hit the API."""
 2
 3import asyncio
 4import time
 5from typing import TYPE_CHECKING
 6
 7if TYPE_CHECKING:
 8    from sidequest_bot.api_client import SideQuestAPI
 9    from sidequest_common.schemas import GuildConfigSchema, GuildConfigUpdate
10
11DEFAULT_TTL_SECONDS = 60.0
12
13
[docs] 14class GuildConfigCache: 15 """Per-guild config cache. 16 17 Reads are served from memory for ``ttl`` seconds. Writes through :meth:`update` go to the API and replace the 18 cached copy immediately, so changes made from slash commands apply without waiting for expiry. 19 """ 20 21 def __init__(self, api: SideQuestAPI, *, ttl: float = DEFAULT_TTL_SECONDS) -> None: 22 self._api = api 23 self._ttl = ttl 24 self._entries: dict[int, tuple[float, GuildConfigSchema]] = {} 25 self._locks: dict[int, asyncio.Lock] = {} 26
[docs] 27 async def get(self, guild_id: int) -> GuildConfigSchema: 28 """Cached config, fetched from the API when missing or stale (one fetch per guild at a time).""" 29 if (entry := self._fresh(guild_id)) is not None: 30 return entry 31 lock = self._locks.setdefault(guild_id, asyncio.Lock()) 32 async with lock: 33 if (entry := self._fresh(guild_id)) is not None: 34 return entry 35 config = await self._api.get_guild_config(guild_id) 36 self._entries[guild_id] = (time.monotonic(), config) 37 return config
38
[docs] 39 async def update(self, guild_id: int, changes: GuildConfigUpdate) -> GuildConfigSchema: 40 """Persist ``changes`` and cache the result.""" 41 config = await self._api.update_guild_config(guild_id, changes) 42 self._entries[guild_id] = (time.monotonic(), config) 43 return config
44
[docs] 45 def invalidate(self, guild_id: int) -> None: 46 """Drop the cached config so the next read refetches.""" 47 self._entries.pop(guild_id, None)
48 49 def _fresh(self, guild_id: int) -> GuildConfigSchema | None: 50 entry = self._entries.get(guild_id) 51 if entry is None or time.monotonic() - entry[0] > self._ttl: 52 return None 53 return entry[1]