Discord/classes/cache/holo_cache_redis.py

92 lines
2.9 KiB
Python
Raw Normal View History

2025-02-09 23:37:44 +01:00
import logging
from logging import Logger
from typing import Dict, Any, List
2025-02-09 23:00:18 +01:00
from redis import Redis
from classes.cache import HoloCache
2025-02-09 23:37:44 +01:00
from modules.cache_utils import string_to_json, json_to_string
logger: Logger = logging.getLogger(__name__)
2025-02-09 23:00:18 +01:00
class HoloCacheRedis(HoloCache):
client: Redis
2025-02-09 23:37:44 +01:00
def __init__(self, client: Redis):
self.client = client
logger.info("Initialized Redis for caching")
2025-02-09 23:00:18 +01:00
@classmethod
def from_config(cls, engine_config: Dict[str, Any]) -> Any:
2025-02-09 23:37:44 +01:00
if "uri" not in engine_config:
raise KeyError(
"Cache configuration is invalid. Please check if all keys are set (engine: memcached)"
)
uri_split: List[str] = engine_config["uri"].split(":")
return cls(Redis(host=uri_split[0], port=int(uri_split[1])))
2025-02-09 23:00:18 +01:00
def get_json(self, key: str) -> Any | None:
2025-02-09 23:37:44 +01:00
try:
result: Any | None = self.client.get(key)
logger.debug(
"Got json cache key '%s'%s",
key,
"" if result is not None else " (not found)",
)
except Exception as exc:
logger.error("Could not get json cache key '%s' due to: %s", key, exc)
return None
return None if result is None else string_to_json(result)
2025-02-09 23:00:18 +01:00
def get_string(self, key: str) -> str | None:
2025-02-09 23:37:44 +01:00
try:
result: str | None = self.client.get(key)
logger.debug(
"Got string cache key '%s'%s",
key,
"" if result is not None else " (not found)",
)
return result
except Exception as exc:
logger.error("Could not get string cache key '%s' due to: %s", key, exc)
return None
2025-02-09 23:00:18 +01:00
2025-02-09 23:37:44 +01:00
# TODO Implement binary deserialization
2025-02-09 23:00:18 +01:00
def get_object(self, key: str) -> Any | None:
raise NotImplementedError()
def set_json(self, key: str, value: Any) -> None:
2025-02-09 23:37:44 +01:00
try:
self.client.set(key, json_to_string(value))
logger.debug("Set json cache key '%s'", key)
except Exception as exc:
logger.error("Could not set json cache key '%s' due to: %s", key, exc)
return None
2025-02-09 23:00:18 +01:00
def set_string(self, key: str, value: str) -> None:
2025-02-09 23:37:44 +01:00
try:
self.client.set(key, value)
logger.debug("Set string cache key '%s'", key)
except Exception as exc:
logger.error("Could not set string cache key '%s' due to: %s", key, exc)
return None
2025-02-09 23:00:18 +01:00
2025-02-09 23:37:44 +01:00
# TODO Implement binary serialization
2025-02-09 23:00:18 +01:00
def set_object(self, key: str, value: Any) -> None:
raise NotImplementedError()
def delete(self, key: str) -> None:
2025-02-09 23:37:44 +01:00
try:
self.client.delete(key)
logger.debug("Deleted cache key '%s'", key)
except Exception as exc:
logger.error("Could not delete cache key '%s' due to: %s", key, exc)