|
|
import os |
|
|
import socket |
|
|
import json |
|
|
import logging |
|
|
import httpx |
|
|
from tenacity import retry, stop_after_attempt, wait_exponential |
|
|
|
|
|
from src.schemas.search_request import SearchRequest |
|
|
from src.config import config |
|
|
|
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
SPACE_ID = config.app.id |
|
|
API_ENDPOINT = config.tracking_db.api_endpoint |
|
|
ANON_KEY = config.tracking_db.anon_key |
|
|
JWT_TOKEN = config.tracking_db.jwt_token |
|
|
|
|
|
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=5)) |
|
|
async def send_tracking_event_to_db(search_data: SearchRequest): |
|
|
|
|
|
headers = { |
|
|
"apikey": ANON_KEY.get_secret_value(), |
|
|
"Authorization": f"Bearer {JWT_TOKEN.get_secret_value()}", |
|
|
"Content-Type": "application/json", |
|
|
"Prefer": "return=minimal" |
|
|
} |
|
|
|
|
|
data = search_data.model_dump() |
|
|
session_id = data.pop('session_id') |
|
|
|
|
|
payload = { |
|
|
"space_id": SPACE_ID, |
|
|
"session_id": session_id, |
|
|
"environment": "dev" if os.getenv("DEV_MODE", "").lower() == "true" else "prod", |
|
|
"server_host": socket.gethostname(), |
|
|
"data": data |
|
|
} |
|
|
|
|
|
try: |
|
|
async with httpx.AsyncClient(timeout=10.0) as client: |
|
|
response = await client.post(API_ENDPOINT, headers=headers, json=payload) |
|
|
response.raise_for_status() |
|
|
logger.info("Successfully sent tracking event to DB!") |
|
|
except httpx.TimeoutException: |
|
|
logger.warning("Tracking request timed out - continuing anyway") |
|
|
except httpx.HTTPStatusError as e: |
|
|
logger.error(f"HTTP {e.response.status_code} error tracking event") |
|
|
except Exception as e: |
|
|
logger.error(f"Unexpected error in tracking: {e} with payload: {json.dumps(payload)}") |