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

reliability: Add a readiness health check

Clémence Lesné5ce83610b43d
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 1d64401..c782f3d 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -191,6 +191,12 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {
memory: '2Gi'
}
probes: [
+ {
+ type: 'Startup'
+ tcpSocket: {
+ port: 8080
+ }
+ }
{
type: 'Liveness'
httpGet: {
@@ -198,6 +204,13 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {
port: 8080
}
}
+ {
+ type: 'Readiness'
+ httpGet: {
+ path: '/health/readiness'
+ port: 8080
+ }
+ }
]
}
]
diff --git a/main.py b/main.py
index a3afec2..62b81e0 100644
--- a/main.py
+++ b/main.py
@@ -21,6 +21,7 @@ from azure.core.credentials import AzureKeyCredential
from azure.core.messaging import CloudEvent
from azure.eventgrid import EventGridEvent, SystemEventNames
from fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks, Response
+from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from jinja2 import Environment, FileSystemLoader, select_autoescape
@@ -44,6 +45,7 @@ from helpers.call_events import (
on_transfer_error,
)
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
+from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatus
# Jinja configuration
@@ -67,8 +69,11 @@ _call_client = CallAutomationClient(
),
)
-# Persistence
+# Persistences
+_cache = CONFIG.cache.instance()
_db = CONFIG.database.instance()
+_search = CONFIG.ai_search.instance()
+_sms = CONFIG.sms.instance()
# FastAPI
_logger.info(f'Using root path "{CONFIG.api.root_path}"')
@@ -106,6 +111,38 @@ async def health_liveness_get() -> None:
pass
+ "/health/readiness",
+ description="Readiness healthckeck, returns the status of all components, and fails if one of them is not ready. If all components are ready, returns 200, otherwise 503.",
+)
+async def health_readiness_get() -> JSONResponse:
+ # Check all components in parallel
+ cache_check, db_check, search_check, sms_check = await asyncio.gather(
+ _cache.areadiness(), _db.areadiness(), _search.areadiness(), _sms.areadiness()
+ )
+ readiness = ReadinessModel(
+ status=ReadinessStatus.OK,
+ checks=[
+ ReadinessCheckModel(id="cache", status=cache_check),
+ ReadinessCheckModel(id="index", status=db_check),
+ ReadinessCheckModel(id="startup", status=ReadinessStatus.OK),
+ ReadinessCheckModel(id="store", status=search_check),
+ ReadinessCheckModel(id="stream", status=sms_check),
+ ],
+ )
+ # If one of the checks fails, the whole readiness fails
+ status_code = status.HTTP_200_OK
+ for check in readiness.checks:
+ if check.status != ReadinessStatus.OK:
+ readiness.status = ReadinessStatus.FAIL
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ break
+ return JSONResponse(
+ content=jsonable_encoder(readiness),
+ status_code=status_code,
+ )
+
+
# Serve static files
api.mount("/static", StaticFiles(directory="public_website/static"))
diff --git a/models/readiness.py b/models/readiness.py
new file mode 100644
index 0000000..282c53a
--- /dev/null
+++ b/models/readiness.py
@@ -0,0 +1,21 @@
+from enum import Enum
+from pydantic import BaseModel
+from typing import List
+
+
+class ReadinessStatus(str, Enum):
+ FAIL = "fail"
+ OK = "ok"
+
+
+class ReadinessCheckModel(BaseModel):
+ id: str
+ status: ReadinessStatus
+
+ class Config:
+ use_enum_values = True
+
+
+class ReadinessModel(BaseModel):
+ checks: List[ReadinessCheckModel]
+ status: str
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index 142137c..68bda73 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -10,6 +10,7 @@ from contextlib import asynccontextmanager
from helpers.config_models.ai_search import AiSearchModel
from helpers.logging import build_logger
from models.call import CallModel
+from models.readiness import ReadinessStatus
from models.training import TrainingModel
from persistence.icache import ICache
from persistence.isearch import ISearch
@@ -38,6 +39,20 @@ class AiSearchSearch(ISearch):
self._config = config
super().__init__(cache)
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the AI Search service.
+ """
+ try:
+ async with self._use_db() as db:
+ await db.get_document_count()
+ return ReadinessStatus.OK
+ except HttpResponseError as e:
+ _logger.error(f"Error requesting AI Search, {e}")
+ except ServiceRequestError as e:
+ _logger.error(f"Error connecting to AI Search, {e}")
+ return ReadinessStatus.FAIL
+
@retry(
reraise=True,
retry=retry_if_exception_type(ServiceResponseError),
diff --git a/persistence/communication_services.py b/persistence/communication_services.py
index 8f853e7..1cd584f 100644
--- a/persistence/communication_services.py
+++ b/persistence/communication_services.py
@@ -5,6 +5,7 @@ from contextlib import asynccontextmanager
from helpers.config_models.communication_service import CommunicationServiceModel
from helpers.logging import build_logger
from helpers.pydantic_types.phone_numbers import PhoneNumber
+from models.readiness import ReadinessStatus
from persistence.isms import ISms
from typing import AsyncGenerator
@@ -19,6 +20,13 @@ class CommunicationServicesSms(ISms):
_logger.info(f"Using Communication Services from number {config.phone_number}")
self._config = config
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the Communication Services SMS service.
+ """
+ # TODO: How to check the readiness of the SMS service? We could send a SMS for each test, but that would be damm expensive.
+ return ReadinessStatus.OK
+
async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
_logger.info(f"Sending SMS to {phone_number}")
success = False
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index 654e662..884b82f 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -7,10 +7,11 @@ from helpers.config import CONFIG
from helpers.config_models.database import CosmosDbModel
from helpers.logging import build_logger
from models.call import CallModel
+from models.readiness import ReadinessStatus
from persistence.istore import IStore
from pydantic import ValidationError
from typing import AsyncGenerator, Optional
-from uuid import UUID
+from uuid import UUID, uuid4
from tenacity import (
retry,
stop_after_attempt,
@@ -29,6 +30,55 @@ class CosmosDbStore(IStore):
_logger.info(f"Using Cosmos DB {config.database}/{config.container}")
self._config = config
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the Cosmos DB service.
+
+ This will validate the ACID properties of the database: Create, Read, Update, Delete.
+ """
+ test_id = str(uuid4())
+ test_partition = "+33612345678"
+ test_dict = {
+ "id": test_id, # unique id
+ "phone_number": test_partition, # partition key
+ "test": "test",
+ }
+ try:
+ async with self._use_db() as db:
+ # Test the item does not exist
+ try:
+ await db.read_item(item=test_id, partition_key=test_partition)
+ return ReadinessStatus.FAIL
+ except CosmosHttpResponseError as e:
+ if e.status_code != 404:
+ _logger.error(f"Error requesting CosmosDB, {e}")
+ return ReadinessStatus.FAIL
+ # Create a new item
+ await db.upsert_item(body=test_dict)
+ # Test the item is the same
+ read_item = await db.read_item(
+ item=test_id, partition_key=test_partition
+ )
+ assert {
+ k: v for k, v in read_item.items() if k in test_dict
+ } == test_dict # Check only the relevant fields, Cosmos DB adds metadata
+ # Delete the item
+ await db.delete_item(item=test_id, partition_key=test_partition)
+ # Test the item does not exist
+ try:
+ await db.read_item(item=test_id, partition_key=test_partition)
+ return ReadinessStatus.FAIL
+ except CosmosHttpResponseError as e:
+ if e.status_code != 404:
+ _logger.error(f"Error requesting CosmosDB, {e}")
+ return ReadinessStatus.FAIL
+ return ReadinessStatus.OK
+ except AssertionError:
+ _logger.error("Readiness test failed", exc_info=True)
+ except CosmosHttpResponseError as e:
+ _logger.error(f"Error requesting CosmosDB, {e}")
+ return ReadinessStatus.FAIL
+
@retry(
reraise=True,
retry=retry_if_exception_type(ServiceResponseError),
diff --git a/persistence/icache.py b/persistence/icache.py
index 07d3118..12acd11 100644
--- a/persistence/icache.py
+++ b/persistence/icache.py
@@ -1,8 +1,14 @@
from abc import ABC, abstractmethod
+from models.readiness import ReadinessStatus
from typing import Optional, Union
class ICache(ABC):
+
+ @abstractmethod
+ async def areadiness(self) -> ReadinessStatus:
+ pass
+
@abstractmethod
async def aget(self, key: str) -> Optional[bytes]:
pass
diff --git a/persistence/isearch.py b/persistence/isearch.py
index 451a220..61d9fb0 100644
--- a/persistence/isearch.py
+++ b/persistence/isearch.py
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
from models.call import CallModel
+from models.readiness import ReadinessStatus
from models.training import TrainingModel
from persistence.icache import ICache
from typing import Optional
@@ -11,6 +12,10 @@ class ISearch(ABC):
def __init__(self, cache: ICache):
self._cache = cache
+ @abstractmethod
+ async def areadiness(self) -> ReadinessStatus:
+ pass
+
@abstractmethod
async def training_asearch_all(
self, text: str, call: CallModel
diff --git a/persistence/isms.py b/persistence/isms.py
index c9d26ca..1cb1310 100644
--- a/persistence/isms.py
+++ b/persistence/isms.py
@@ -1,8 +1,14 @@
from abc import ABC, abstractmethod
from helpers.pydantic_types.phone_numbers import PhoneNumber
+from models.readiness import ReadinessStatus
class ISms(ABC):
+
+ @abstractmethod
+ async def areadiness(self) -> ReadinessStatus:
+ pass
+
@abstractmethod
async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
pass
diff --git a/persistence/istore.py b/persistence/istore.py
index 08a337e..e969394 100644
--- a/persistence/istore.py
+++ b/persistence/istore.py
@@ -1,10 +1,16 @@
from abc import ABC, abstractmethod
from models.call import CallModel
+from models.readiness import ReadinessStatus
from typing import Optional
from uuid import UUID
class IStore(ABC):
+
+ @abstractmethod
+ async def areadiness(self) -> ReadinessStatus:
+ pass
+
@abstractmethod
async def call_aget(self, call_id: UUID) -> Optional[CallModel]:
pass
diff --git a/persistence/memory.py b/persistence/memory.py
index 5845296..8859a3f 100644
--- a/persistence/memory.py
+++ b/persistence/memory.py
@@ -1,6 +1,7 @@
from collections import OrderedDict
from helpers.config_models.cache import MemoryModel
from helpers.logging import build_logger
+from models.readiness import ReadinessStatus
from persistence.icache import ICache
from typing import Optional, Union
import hashlib
@@ -25,6 +26,12 @@ class MemoryCache(ICache):
_logger.info(f"Using memory cache with {config.max_size} size limit")
self._config = config
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the memory cache.
+ """
+ return ReadinessStatus.OK # Always ready, it's memory :)
+
async def aget(self, key: str) -> Optional[bytes]:
"""
Get a value from the cache.
diff --git a/persistence/redis.py b/persistence/redis.py
index a5a2455..969280e 100644
--- a/persistence/redis.py
+++ b/persistence/redis.py
@@ -1,6 +1,7 @@
from contextlib import asynccontextmanager
from helpers.config_models.cache import RedisModel
from helpers.logging import build_logger
+from models.readiness import ReadinessStatus
from opentelemetry.instrumentation.redis import RedisInstrumentor
from persistence.icache import ICache
from redis.asyncio import Redis
@@ -8,6 +9,7 @@ from redis.asyncio.retry import Retry
from redis.backoff import ExponentialBackoff
from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError, RedisError
from typing import AsyncGenerator, Optional, Union
+from uuid import uuid4
import hashlib
@@ -25,6 +27,33 @@ class RedisCache(ICache):
_logger.info(f"Using Redis cache {config.host}:{config.port}")
self._config = config
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the Redis cache.
+
+ This will validate the ACID properties of the database: Create, Read, Update, Delete.
+ """
+ test_name = str(uuid4())
+ test_value = "test"
+ try:
+ async with self._use_db() as db:
+ # Test the item does not exist
+ assert await db.get(test_name) is None
+ # Create a new item
+ await db.set(test_name, test_value)
+ # Test the item is the same
+ assert (await db.get(test_name)).decode() == test_value
+ # Delete the item
+ await db.delete(test_name)
+ # Test the item does not exist
+ assert await db.get(test_name) is None
+ return ReadinessStatus.OK
+ except AssertionError as e:
+ _logger.error(f"Readiness test failed, {e}")
+ except RedisError as e:
+ _logger.error(f"Error requesting Redis, {e}")
+ return ReadinessStatus.FAIL
+
async def aget(self, key: str) -> Optional[bytes]:
"""
Get a value from the cache.
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index e8b24ca..0171a4a 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -5,6 +5,7 @@ from helpers.config import CONFIG
from helpers.config_models.database import SqliteModel
from helpers.logging import build_logger
from models.call import CallModel
+from models.readiness import ReadinessStatus
from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
from persistence.istore import IStore
from pydantic import ValidationError
@@ -29,6 +30,20 @@ class SqliteStore(IStore):
)
self._config = config
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the SQLite database.
+
+ This checks if the database is reachable and can be queried.
+ """
+ try:
+ async with self._use_db() as db:
+ await db.execute("SELECT 1")
+ return ReadinessStatus.OK
+ except Exception as e:
+ _logger.error(f"Error requesting SQLite, {e}")
+ return ReadinessStatus.FAIL
+
async def call_aget(self, call_id: UUID) -> Optional[CallModel]:
_logger.debug(f"Loading call {call_id}")
call = None
diff --git a/persistence/twilio.py b/persistence/twilio.py
index 20e31f8..100932f 100644
--- a/persistence/twilio.py
+++ b/persistence/twilio.py
@@ -1,6 +1,7 @@
from helpers.config_models.sms import TwilioModel
from helpers.logging import build_logger
from helpers.pydantic_types.phone_numbers import PhoneNumber
+from models.readiness import ReadinessStatus
from persistence.isms import ISms
from twilio.base.exceptions import TwilioRestException
from twilio.http.async_http_client import AsyncTwilioHttpClient
@@ -23,6 +24,22 @@ class TwilioSms(ISms):
username=config.account_sid,
)
+ async def areadiness(self) -> ReadinessStatus:
+ """
+ Check the readiness of the Twilio SMS service.
+
+ This only check if the Twilio API is reachable and the account has remaining balance.
+ """
+ account_sid = self._config.account_sid
+ try:
+ account = await self._client.api.accounts(account_sid).fetch_async()
+ balance = await account.balance.fetch_async()
+ assert balance.balance and float(balance.balance) > 0
+ return ReadinessStatus.OK
+ except AssertionError:
+ _logger.error("Readiness test failed", exc_info=True)
+ return ReadinessStatus.FAIL
+
async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
_logger.info(f"Sending SMS to {phone_number}")
success = False