Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
perf: Store Redis cache keys are hashs
Clémence Lesné457459f34100
diff --git a/persistence/icache.py b/persistence/icache.pyindex 07d3118..0904ded 100644--- a/persistence/icache.py+++ b/persistence/icache.py@@ -4,9 +4,11 @@ from typing import Optional, Unionclass ICache(ABC):@abstractmethod- async def aget(self, key: str) -> Optional[bytes]:+ async def aget(self, key: Union[str, bytes]) -> Optional[bytes]:pass@abstractmethod- async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:+ async def aset(+ self, key: Union[str, bytes], value: Union[str, bytes, None]+ ) -> bool:passdiff --git a/persistence/memory.py b/persistence/memory.pyindex 32d679c..1849f3c 100644--- a/persistence/memory.py+++ b/persistence/memory.py@@ -15,15 +15,18 @@ class MemoryCache(ICache):_logger.info(f"Using memory cache with {config.max_size} size limit")self._config = config- async def aget(self, key: str) -> Optional[bytes]:+ async def aget(self, key: Union[str, bytes]) -> Optional[bytes]:"""Get a value from the cache.If the key does not exist, return `None`."""- return self._cache.get(key, None)+ str_key = self._key_to_str(key)+ return self._cache.get(str_key, None)- async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:+ async def aset(+ self, key: Union[str, bytes], value: Union[str, bytes, None]+ ) -> bool:"""Set a value in the cache.@@ -31,5 +34,10 @@ class MemoryCache(ICache):"""if len(self._cache) >= self._config.max_size:self._cache = {}- self._cache[key] = value.encode() if isinstance(value, str) else value+ str_key = self._key_to_str(key)+ self._cache[str_key] = value.encode() if isinstance(value, str) else valuereturn True++ @staticmethod+ def _key_to_str(key: Union[str, bytes]) -> str:+ return key.decode() if isinstance(key, bytes) else str(key)diff --git a/persistence/redis.py b/persistence/redis.pyindex 884aa77..4264f5f 100644--- a/persistence/redis.py+++ b/persistence/redis.py@@ -1,4 +1,5 @@from contextlib import asynccontextmanager+from functools import wrapsfrom helpers.config_models.cache import RedisModelfrom helpers.logging import build_loggerfrom persistence.icache import ICache@@ -6,7 +7,8 @@ from redis.asyncio import Redisfrom redis.asyncio.retry import Retryfrom redis.backoff import ExponentialBackofffrom redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError-from typing import AsyncGenerator, Optional, Union+from typing import AsyncGenerator, Awaitable, Callable, Optional, Union+import hashlib_logger = build_logger(__name__)@@ -20,7 +22,27 @@ class RedisCache(ICache):_logger.info(f"Using Redis cache {config.host}:{config.port}")self._config = config- async def aget(self, key: str) -> Optional[bytes]:+ @staticmethod+ def _key_as_sha(func: Callable[..., Awaitable]):+ """+ Decorator to convert the key to a SHA-256 hash.+ """++ @wraps(func)+ async def wrapper(self, key: Union[str, bytes], *args, **kwargs):+ bytes_key = key.encode() if isinstance(key, str) else key+ sha_key = hashlib.sha256(bytes_key, usedforsecurity=False).digest()+ return await func(+ self,+ *args,+ key=sha_key,+ **kwargs,+ )++ return wrapper++ @_key_as_sha+ async def aget(self, key: Union[str, bytes]) -> Optional[bytes]:"""Get a value from the cache.@@ -33,7 +55,10 @@ class RedisCache(ICache):res = await db.get(key)return res- async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:+ @_key_as_sha+ async def aset(+ self, key: Union[str, bytes], value: Union[str, bytes, None]+ ) -> bool:"""Set a value in the cache.