|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from typing import Any, Callable |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | +import redis |
| 7 | + |
| 8 | +from pems_data.serialization import arrow_bytes_to_df, df_to_arrow_bytes |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +def redis_connection(host: str = None, port: int = None, **kwargs) -> redis.Redis | None: |
| 14 | + """Try to create a new connection to a redis backend. Return None if the connection fails. |
| 15 | +
|
| 16 | + Uses the `REDIS_HOSTNAME` and `REDIS_PORT` environment variables as fallback. |
| 17 | +
|
| 18 | + Args: |
| 19 | + host (str): The redis hostname |
| 20 | + port (int): The port to connect on |
| 21 | + """ |
| 22 | + |
| 23 | + host = host or os.environ.get("REDIS_HOSTNAME", "redis") |
| 24 | + port = int(port or os.environ.get("REDIS_PORT", "6379")) |
| 25 | + |
| 26 | + logger.debug(f"connecting to redis @ {host}:{port}") |
| 27 | + |
| 28 | + kwargs["host"] = host |
| 29 | + kwargs["port"] = port |
| 30 | + |
| 31 | + try: |
| 32 | + return redis.Redis(**kwargs) |
| 33 | + except redis.ConnectionError as ce: |
| 34 | + logger.error(f"connection failed for redis @ {host}:{port}", exc_info=ce) |
| 35 | + return None |
| 36 | + |
| 37 | + |
| 38 | +class Cache: |
| 39 | + """Basic caching interface for `pems_data`.""" |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def build_key(cls, *args) -> str: |
| 43 | + """Build a cache key from the given parts.""" |
| 44 | + return ":".join([str(a).lower() for a in args]) |
| 45 | + |
| 46 | + def __init__(self, host: str = None, port: int = None): |
| 47 | + """Create a new instance of the Cache interface. |
| 48 | +
|
| 49 | + Args: |
| 50 | + host (str): (Optional) The hostname of the cache backend. |
| 51 | + port (int): (Optional) The port to connect on the cache backend. |
| 52 | + """ |
| 53 | + |
| 54 | + self.host = host |
| 55 | + self.port = port |
| 56 | + self.c = None |
| 57 | + |
| 58 | + def _connect(self): |
| 59 | + """Establish a connection to the cache backend if necessary.""" |
| 60 | + if not isinstance(self.c, redis.Redis): |
| 61 | + self.c = redis_connection(self.host, self.port) |
| 62 | + |
| 63 | + def is_available(self) -> bool: |
| 64 | + """Return a bool indicating if the cache backend is available or not.""" |
| 65 | + self._connect() |
| 66 | + available = self.c and self.c.ping() is True |
| 67 | + logger.debug(f"cache is available: {available}") |
| 68 | + return available |
| 69 | + |
| 70 | + def get(self, key: str, mutate_func: Callable[[Any], Any] = None) -> Any: |
| 71 | + """Get a raw value from the cache, or None if the key doesn't exist. |
| 72 | +
|
| 73 | + Args: |
| 74 | + key (str): The item's cache key. |
| 75 | + mutate_func (callable): If provided, call this on the cached value and return its result. |
| 76 | + """ |
| 77 | + if self.is_available(): |
| 78 | + logger.debug(f"read from cache: {key}") |
| 79 | + value = self.c.get(key) |
| 80 | + if value and mutate_func: |
| 81 | + logger.debug(f"mutating cached value: {key}") |
| 82 | + return mutate_func(value) |
| 83 | + return value |
| 84 | + logger.warning(f"cache unavailable to get: {key}") |
| 85 | + return None |
| 86 | + |
| 87 | + def get_df(self, key: str) -> pd.DataFrame: |
| 88 | + """Get a `pandas.DataFrame` from the cache, or None if the key doesn't exist.""" |
| 89 | + return self.get(key, mutate_func=arrow_bytes_to_df) |
| 90 | + |
| 91 | + def set(self, key: str, value: Any, ttl: int = None, mutate_func: Callable[[Any], Any] = None) -> None: |
| 92 | + """Set a value in the cache. |
| 93 | +
|
| 94 | + Args: |
| 95 | + key (str): The item's cache key. |
| 96 | + value (Any): The item's value to store in the cache. |
| 97 | + ttl (int): Seconds until expiration. |
| 98 | + mutate_func (callable): If provided, call this on the value and insert the result in the cache. |
| 99 | + """ |
| 100 | + if self.is_available(): |
| 101 | + if mutate_func: |
| 102 | + logger.debug(f"mutating value for cache: {key}") |
| 103 | + value = mutate_func(value) |
| 104 | + logger.debug(f"store in cache: {key}") |
| 105 | + self.c.set(key, value, ex=ttl) |
| 106 | + else: |
| 107 | + logger.warning(f"cache unavailable to set: {key}") |
| 108 | + |
| 109 | + def set_df(self, key: str, value: pd.DataFrame, ttl: int = None) -> None: |
| 110 | + """Set a `pandas.DataFrame` in the cache, with an optional TTL (seconds until expiration).""" |
| 111 | + self.set(key, value, mutate_func=df_to_arrow_bytes, ttl=ttl) |
0 commit comments