import logging from logging import Logger from typing import Dict, Any from bson import ObjectId from pymemcache import Client from ujson import dumps, loads from . import HoloCache logger: Logger = logging.getLogger(__name__) class HoloCacheMemcached(HoloCache): client: Client def __init__(self, client: Client): self.client = client @classmethod def from_config(cls, engine_config: Dict[str, Any]) -> "HoloCacheMemcached": if "uri" not in engine_config: raise KeyError( "Cache configuration is invalid. Please check if all keys are set (engine: memcached)" ) return cls(Client(engine_config["uri"], default_noreply=True)) def get_json(self, key: str) -> Any | None: try: result: Any | None = self.client.get(key, None) 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 self._string_to_json(result) def get_string(self, key: str) -> str | None: try: result: str | None = self.client.get(key, None) 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 def get_object(self, key: str) -> Any | None: # TODO Implement binary deserialization raise NotImplementedError() def set_json(self, key: str, value: Any) -> None: try: self.client.set(key, self._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 def set_object(self, key: str, value: Any) -> None: # TODO Implement binary serialization 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) @staticmethod def _json_to_string(json_object: Any) -> str: if isinstance(json_object, dict) and "_id" in json_object: json_object["_id"] = str(json_object["_id"]) return dumps( json_object, ensure_ascii=False, indent=0, escape_forward_slashes=False ) @staticmethod def _string_to_json(json_string: str) -> Any: json_object: Any = loads(json_string) if isinstance(json_object, dict) and "_id" in json_object: json_object["_id"] = ObjectId(json_object["_id"]) return json_object