|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from typing import Any, Union |
| 3 | + |
| 4 | +from fastapi_ronin.defaults import CACHE_DEFAULT_NAMESPACE, NOT_SET |
| 5 | +from fastapi_ronin.types import TTLType |
| 6 | + |
| 7 | +from .cache_client_interface import CacheClientInterface |
| 8 | + |
| 9 | + |
| 10 | +class BaseCacheClient(CacheClientInterface, ABC): |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + namespace: str = CACHE_DEFAULT_NAMESPACE, |
| 14 | + default_ttl: Union[int, float, None] = None, |
| 15 | + ): |
| 16 | + self.namespace = namespace |
| 17 | + self.default_ttl = self._validate_ttl(default_ttl) |
| 18 | + |
| 19 | + async def get(self, key: str) -> Any: |
| 20 | + return await self._get(self._make_key(key)) |
| 21 | + |
| 22 | + async def set(self, key: str, value: Any, ttl: TTLType = NOT_SET) -> None: |
| 23 | + await self._set(self._make_key(key), value, self._get_ttl(ttl)) |
| 24 | + |
| 25 | + async def delete(self, key: str) -> None: |
| 26 | + await self._delete(self._make_key(key)) |
| 27 | + |
| 28 | + async def clear(self) -> None: |
| 29 | + await self._clear() |
| 30 | + |
| 31 | + async def exists(self, *keys: str) -> int: |
| 32 | + if not keys: |
| 33 | + return 0 |
| 34 | + return await self._exists(*self._make_keys(*keys)) |
| 35 | + |
| 36 | + def _make_key(self, key: str) -> str: |
| 37 | + return f'{self.namespace}:{key}' |
| 38 | + |
| 39 | + def _make_keys(self, *keys: str) -> tuple[str, ...]: |
| 40 | + return tuple(self._make_key(key) for key in keys) |
| 41 | + |
| 42 | + def _get_ttl(self, ttl: TTLType) -> Union[int, float, None]: |
| 43 | + _ttl: Union[int, float, None] = None |
| 44 | + if ttl is NOT_SET: |
| 45 | + _ttl = self.default_ttl |
| 46 | + elif ttl is None or isinstance(ttl, (int, float)): |
| 47 | + _ttl = ttl |
| 48 | + else: |
| 49 | + raise ValueError(f'Invalid TTL: {ttl}') |
| 50 | + return self._validate_ttl(_ttl) |
| 51 | + |
| 52 | + def _validate_ttl(self, ttl: Union[int, float, None]) -> Union[int, float, None]: |
| 53 | + if ttl is not None and ttl <= 0: |
| 54 | + raise ValueError(f'TTL must be positive, got: {ttl} seconds') |
| 55 | + return ttl |
| 56 | + |
| 57 | + @abstractmethod |
| 58 | + async def _get(self, key: str) -> Any: |
| 59 | + pass |
| 60 | + |
| 61 | + @abstractmethod |
| 62 | + async def _set(self, key: str, value: Any, ttl: Union[int, float, None]) -> None: |
| 63 | + pass |
| 64 | + |
| 65 | + @abstractmethod |
| 66 | + async def _delete(self, key: str) -> None: |
| 67 | + pass |
| 68 | + |
| 69 | + @abstractmethod |
| 70 | + async def _clear(self) -> None: |
| 71 | + pass |
| 72 | + |
| 73 | + @abstractmethod |
| 74 | + async def _exists(self, *keys: str) -> int: |
| 75 | + pass |
| 76 | + |
| 77 | + @abstractmethod |
| 78 | + async def ping(self) -> bool: |
| 79 | + pass |
| 80 | + |
| 81 | + @abstractmethod |
| 82 | + async def close(self) -> None: |
| 83 | + pass |
0 commit comments