34 lines
973 B
Python
34 lines
973 B
Python
from typing import Any, Protocol
|
|||
|
|
|
||
|
|
|
||
|
|
class CacheClient(Protocol):
|
||
|
|
async def get(self, key: str) -> Any: ...
|
||
|
|
|
||
|
|
async def set(self, key: str, value: str, ex: int | None = None) -> Any: ...
|
||
|
|
|
||
|
|
|
||
|
|
class CacheReadResult:
|
||
|
|
def __init__(self, value: Any, degraded: bool = False) -> None:
|
||
|
|
self.value = value
|
||
|
|
self.degraded = degraded
|
||
|
|
|
||
|
|
|
||
|
|
class MemoryCacheAdapter:
|
||
|
|
"""Cache is an optimization; failures must not block MySQL recall."""
|
||
|
|
|
||
|
|
def __init__(self, client: CacheClient) -> None:
|
||
|
|
self.client = client
|
||
|
|
|
||
|
|
async def get(self, key: str) -> CacheReadResult:
|
||
|
|
try:
|
||
|
|
return CacheReadResult(await self.client.get(key))
|
||
|
|
except Exception:
|
||
|
|
return CacheReadResult(None, degraded=True)
|
||
|
|
|
||
|
|
async def set(self, key: str, value: str, ttl_seconds: int = 300) -> bool:
|
||
|
|
try:
|
||
|
|
await self.client.set(key, value, ex=ttl_seconds)
|
||
|
|
return True
|
||
|
|
except Exception:
|
||
|
|
return False
|