Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

perf: Cache stores

Clémence Lesné5118b6d6fe8a
diff --git a/helpers/config_models/database.py b/helpers/config_models/database.py
index c93a4e6..355fc1f 100644
--- a/helpers/config_models/database.py
+++ b/helpers/config_models/database.py
@@ -18,9 +18,10 @@ class CosmosDbModel(BaseModel, frozen=True):
@cache
def instance(self) -> IStore:
+ from helpers.config import CONFIG
from persistence.cosmos_db import CosmosDbStore
- return CosmosDbStore(self)
+ return CosmosDbStore(CONFIG.cache.instance(), self)
class SqliteModel(BaseModel, frozen=True):
@@ -38,9 +39,10 @@ class SqliteModel(BaseModel, frozen=True):
@cache
def instance(self) -> IStore:
+ from helpers.config import CONFIG
from persistence.sqlite import SqliteStore
- return SqliteStore(self)
+ return SqliteStore(CONFIG.cache.instance(), self)
class DatabaseModel(BaseModel):
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index e1ff7f6..16dddfa 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -2,12 +2,13 @@ from azure.cosmos import ConsistencyLevel
from azure.cosmos.aio import CosmosClient, ContainerProxy
from azure.cosmos.exceptions import CosmosHttpResponseError
from contextlib import asynccontextmanager
-from helpers.http import azure_transport
from helpers.config import CONFIG
from helpers.config_models.database import CosmosDbModel
+from helpers.http import azure_transport
from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessStatus
+from persistence.icache import ICache
from persistence.istore import IStore
from pydantic import ValidationError
from typing import AsyncGenerator, Optional
@@ -19,7 +20,8 @@ class CosmosDbStore(IStore):
_client: Optional[CosmosClient] = None
_config: CosmosDbModel
- def __init__(self, config: CosmosDbModel):
+ def __init__(self, cache: ICache, config: CosmosDbModel):
+ super().__init__(cache)
logger.info(f"Using Cosmos DB {config.database}/{config.container}")
self._config = config
@@ -78,6 +80,17 @@ class CosmosDbStore(IStore):
async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
logger.debug(f"Loading call {call_id}")
+
+ # Try cache
+ cache_key = self._cache_key_call_id(call_id)
+ cached = await self._cache.aget(cache_key)
+ if cached:
+ try:
+ return CallStateModel.model_validate_json(cached)
+ except ValidationError as e:
+ logger.debug(f"Parsing error: {e.errors()}")
+
+ # Try live
call = None
try:
async with self._use_client() as db:
@@ -94,22 +107,48 @@ class CosmosDbStore(IStore):
pass
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB, {e}")
+
+ # Update cache
+ if call:
+ await self._cache.aset(cache_key, call.model_dump_json())
+
return call
async def call_aset(self, call: CallStateModel) -> bool:
+ logger.debug(f"Saving call {call.call_id}")
+
+ # Update live
data = call.model_dump(mode="json", exclude_none=True)
data["id"] = str(call.call_id) # CosmosDB requires an id field
logger.debug(f"Saving call {call.call_id}: {data}")
+ res = False
try:
async with self._use_client() as db:
await db.upsert_item(body=data)
- return True
+ res = True
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB: {e}")
- return False
+
+ # Update cache
+ if res:
+ cache_key = self._cache_key_call_id(call.call_id)
+ await self._cache.aset(cache_key, call.model_dump_json())
+
+ return res
async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
logger.debug(f"Loading last call for {phone_number}")
+
+ # Try cache
+ cache_key = self._cache_key_phone_number(phone_number)
+ cached = await self._cache.aget(cache_key)
+ if cached:
+ try:
+ return CallStateModel.model_validate_json(cached)
+ except ValidationError as e:
+ logger.debug(f"Parsing error: {e.errors()}")
+
+ # Try live
call = None
try:
async with self._use_client() as db:
@@ -132,6 +171,11 @@ class CosmosDbStore(IStore):
pass
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB: {e}")
+
+ # Update cache
+ if call:
+ await self._cache.aset(cache_key, call.model_dump_json())
+
return call
async def call_asearch_all(
@@ -140,6 +184,7 @@ class CosmosDbStore(IStore):
phone_number: Optional[str] = None,
) -> tuple[Optional[list[CallStateModel]], int]:
logger.debug(f"Searching calls, for {phone_number} and count {count}")
+ # TODO: Cache results
calls, total = await asyncio.gather(
self._call_asearch_all_calls_worker(count, phone_number),
self._call_asearch_all_total_worker(phone_number),
diff --git a/persistence/icache.py b/persistence/icache.py
index 12acd11..97872f2 100644
--- a/persistence/icache.py
+++ b/persistence/icache.py
@@ -16,3 +16,7 @@ class ICache(ABC):
@abstractmethod
async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:
pass
+
+ @abstractmethod
+ async def adel(self, key: str) -> bool:
+ pass
diff --git a/persistence/istore.py b/persistence/istore.py
index a0ffda6..090f70b 100644
--- a/persistence/istore.py
+++ b/persistence/istore.py
@@ -1,11 +1,16 @@
from abc import ABC, abstractmethod
from models.call import CallStateModel
from models.readiness import ReadinessStatus
+from persistence.icache import ICache
from typing import Optional
from uuid import UUID
class IStore(ABC):
+ _cache: ICache
+
+ def __init__(self, cache: ICache):
+ self._cache = cache
@abstractmethod
async def areadiness(self) -> ReadinessStatus:
@@ -30,3 +35,9 @@ class IStore(ABC):
phone_number: Optional[str] = None,
) -> tuple[Optional[list[CallStateModel]], int]:
pass
+
+ def _cache_key_call_id(self, call_id: UUID) -> str:
+ return f"{self.__class__.__name__}-call_id-{call_id}"
+
+ def _cache_key_phone_number(self, phone_number: str) -> str:
+ return f"{self.__class__.__name__}-phone_number-{phone_number}"
diff --git a/persistence/memory.py b/persistence/memory.py
index ab1e7ff..8a37af2 100644
--- a/persistence/memory.py
+++ b/persistence/memory.py
@@ -56,6 +56,15 @@ class MemoryCache(ICache):
self._cache.move_to_end(sha_key, last=False)
return True
+ async def adel(self, key: str) -> bool:
+ """
+ Delete a value from the cache.
+ """
+ sha_key = self._key_to_hash(key)
+ if sha_key in self._cache:
+ self._cache.pop(sha_key)
+ return True
+
@staticmethod
def _key_to_hash(key: str) -> str:
"""
diff --git a/persistence/redis.py b/persistence/redis.py
index c5005f7..cd6f3d3 100644
--- a/persistence/redis.py
+++ b/persistence/redis.py
@@ -100,6 +100,20 @@ class RedisCache(ICache):
return False
return True
+ async def adel(self, key: str) -> bool:
+ """
+ Delete a value from the cache.
+
+ Catch errors for a maximum of 3 times, then raise the error.
+ """
+ sha_key = self._key_to_hash(key)
+ try:
+ await self._client.delete(sha_key)
+ except RedisError as e:
+ logger.error(f"Error deleting value, {e}")
+ return False
+ return True
+
@staticmethod
def _key_to_hash(key: str) -> bytes:
"""
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index f0ea2fd..de7c6b6 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -6,6 +6,7 @@ from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessStatus
from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
+from persistence.icache import ICache
from persistence.istore import IStore
from pydantic import ValidationError
from typing import AsyncGenerator, Optional
@@ -23,7 +24,8 @@ class SqliteStore(IStore):
_config: SqliteModel
_first_run_done: bool = False
- def __init__(self, config: SqliteModel):
+ def __init__(self, cache: ICache, config: SqliteModel):
+ super().__init__(cache)
logger.info(f"Using SQLite database at {config.path} with table {config.table}")
self._config = config
@@ -53,6 +55,17 @@ class SqliteStore(IStore):
async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
logger.debug(f"Loading call {call_id}")
+
+ # Try cache
+ cache_key = self._cache_key_call_id(call_id)
+ call = await self._cache.aget(cache_key)
+ if call:
+ try:
+ return CallStateModel.model_validate_json(call)
+ except ValidationError as e:
+ logger.debug(f"Parsing error: {e.errors()}")
+
+ # Try live
call = None
async with self._use_db() as db:
cursor = await db.execute(
@@ -65,10 +78,17 @@ class SqliteStore(IStore):
call = CallStateModel.model_validate_json(row[0])
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
+
+ # Update cache
+ if call:
+ await self._cache.aset(cache_key, call.model_dump_json())
+
return call
async def call_aset(self, call: CallStateModel) -> bool:
# TODO: Catch exceptions and return False if something goes wrong
+
+ # Update live
data = call.model_dump_json(exclude_none=True)
logger.debug(f"Saving call {call.call_id}: {data}")
async with self._use_db() as db:
@@ -80,10 +100,26 @@ class SqliteStore(IStore):
),
)
await db.commit()
+
+ # Update cache
+ cache_key = self._cache_key_call_id(call.call_id)
+ await self._cache.aset(cache_key, data)
+
return True
async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
logger.debug(f"Loading last call for {phone_number}")
+
+ # Try cache
+ cache_key = self._cache_key_phone_number(phone_number)
+ call = await self._cache.aget(cache_key)
+ if call:
+ try:
+ return CallStateModel.model_validate_json(call)
+ except ValidationError as e:
+ logger.debug(f"Parsing error: {e.errors()}")
+
+ # Try live
call = None
async with self._use_db() as db:
cursor = await db.execute(
@@ -99,6 +135,11 @@ class SqliteStore(IStore):
call = CallStateModel.model_validate_json(row[0])
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
+
+ # Update cache
+ if call:
+ await self._cache.aset(cache_key, call.model_dump_json())
+
return call
async def call_asearch_all(
@@ -107,6 +148,7 @@ class SqliteStore(IStore):
phone_number: Optional[str] = None,
) -> tuple[Optional[list[CallStateModel]], int]:
logger.debug(f"Searching calls, for {phone_number} and count {count}")
+ # TODO: Cache results
calls, total = await asyncio.gather(
self._call_asearch_all_calls_worker(count, phone_number),
self._call_asearch_all_total_worker(phone_number),