import logging from logging import Logger from typing import Dict, Any, List from redis import Redis from classes.cache import HoloCache from modules.cache_utils import string_to_json, json_to_string logger: Logger = logging.getLogger(__name__) class HoloCacheRedis(HoloCache): client: Redis def __init__(self, client: Redis): self.client = client logger.info("Initialized Redis for caching") @classmethod def from_config(cls, engine_config: Dict[str, Any]) -> Any: 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]))) def get_json(self, key: str) -> Any | None: 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) def get_string(self, key: str) -> str | None: 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 # TODO Implement binary deserialization def get_object(self, key: str) -> Any | None: raise NotImplementedError() def set_json(self, key: str, value: Any) -> None: 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 def set_string(self, key: str, value: str) -> None: 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 # TODO Implement binary serialization def set_object(self, key: str, value: Any) -> None: raise NotImplementedError() def delete(self, key: str) -> None: 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)