|
| 1 | +import datetime |
| 2 | +import functools |
| 3 | +from http import HTTPStatus |
| 4 | +from typing import Any, NotRequired, TypedDict |
| 5 | + |
| 6 | +from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter |
| 7 | +from azure.monitor.opentelemetry.exporter._connection_string_parser import ConnectionStringParser |
| 8 | +from azure.monitor.opentelemetry.exporter._generated.exporter.models import MonitorBase, TelemetryItem |
| 9 | + |
| 10 | +from app.authentication.models import User |
| 11 | +from app.common.logger import logger |
| 12 | +from app.config import config |
| 13 | + |
| 14 | + |
| 15 | +@functools.lru_cache(maxsize=1) |
| 16 | +def get_trace_exporter() -> AzureMonitorTraceExporter: |
| 17 | + kwargs: dict[str, Any] = { |
| 18 | + "connection_string": config.APPINSIGHTS_CONSTRING, |
| 19 | + "logger_name": "API", |
| 20 | + } |
| 21 | + if config.has_azure_service_principal: |
| 22 | + from azure.identity import ClientSecretCredential |
| 23 | + |
| 24 | + kwargs["credential"] = ClientSecretCredential( |
| 25 | + tenant_id=config.AZURE_TENANT_ID, |
| 26 | + client_id=config.OAUTH_CLIENT_ID, |
| 27 | + client_secret=config.OAUTH_CLIENT_SECRET.get_secret_value(), |
| 28 | + ) |
| 29 | + return AzureMonitorTraceExporter(**kwargs) |
| 30 | + |
| 31 | + |
| 32 | +class EventData(TypedDict): |
| 33 | + ver: int |
| 34 | + properties: dict[str, Any] |
| 35 | + name: str |
| 36 | + url: NotRequired[str] |
| 37 | + measurements: NotRequired[dict[str, float]] |
| 38 | + |
| 39 | + |
| 40 | +class MetricsData(TypedDict): |
| 41 | + ver: int |
| 42 | + metrics: list[dict[str, Any]] |
| 43 | + properties: dict[str, Any] |
| 44 | + |
| 45 | + |
| 46 | +class ExceptionData(TypedDict): |
| 47 | + ver: int |
| 48 | + exceptions: list[dict[str, Any]] |
| 49 | + properties: dict[str, Any] |
| 50 | + |
| 51 | + |
| 52 | +class EventBase(TypedDict): |
| 53 | + baseType: str |
| 54 | + baseData: EventData | MetricsData | ExceptionData |
| 55 | + |
| 56 | + |
| 57 | +class Event(TypedDict): |
| 58 | + name: str |
| 59 | + tags: dict[str, str] |
| 60 | + time: datetime.datetime |
| 61 | + data: EventBase |
| 62 | + |
| 63 | + |
| 64 | +class TelemetryErrorDetails(TypedDict): |
| 65 | + index: int |
| 66 | + statusCode: int |
| 67 | + message: str |
| 68 | + |
| 69 | + |
| 70 | +class TelemetryResult(TypedDict): |
| 71 | + items_received: int |
| 72 | + items_accepted: int |
| 73 | + errors: list[TelemetryErrorDetails] |
| 74 | + |
| 75 | + |
| 76 | +def track_events_use_case(user: User, events: list[Event]) -> TelemetryResult | None: |
| 77 | + if connection_string := config.APPINSIGHTS_CONSTRING: |
| 78 | + instrumentation_key = ConnectionStringParser(connection_string=connection_string).instrumentation_key |
| 79 | + else: |
| 80 | + logger.warning("Environment variable 'APPINSIGHTS_CONSTRING' is unset; Unable to send to Azure Monitor") |
| 81 | + return TelemetryResult( |
| 82 | + items_accepted=0, |
| 83 | + items_received=len(events), |
| 84 | + errors=[ |
| 85 | + TelemetryErrorDetails( |
| 86 | + index=idx, |
| 87 | + statusCode=HTTPStatus.SERVICE_UNAVAILABLE, |
| 88 | + message="No Applications Insight connection string provided", |
| 89 | + ) |
| 90 | + for idx in range(len(events)) |
| 91 | + ], |
| 92 | + ) |
| 93 | + telemetry_items = [ |
| 94 | + TelemetryItem( |
| 95 | + name=event["name"], |
| 96 | + instrumentation_key=instrumentation_key, |
| 97 | + tags=event["tags"], |
| 98 | + time=event["time"], |
| 99 | + data=MonitorBase(event["data"]), |
| 100 | + ) |
| 101 | + for event in events |
| 102 | + ] |
| 103 | + trace_exporter = get_trace_exporter() |
| 104 | + try: |
| 105 | + result = trace_exporter.client.track(telemetry_items) |
| 106 | + return TelemetryResult( |
| 107 | + items_received=result.items_received or len(events), |
| 108 | + items_accepted=result.items_accepted or 0, |
| 109 | + errors=[ |
| 110 | + TelemetryErrorDetails( |
| 111 | + index=error.index or 0, |
| 112 | + statusCode=error.status_code or 0, |
| 113 | + message=error.message or "", |
| 114 | + ) |
| 115 | + for error in (result.errors or []) |
| 116 | + ], |
| 117 | + ) |
| 118 | + except Exception as e: |
| 119 | + logger.error(f"Failed to track events: {e}") |
| 120 | + return None |
| 121 | + |
| 122 | + |
| 123 | +__all__ = ["track_events_use_case", "Event", "TelemetryResult"] |
0 commit comments