"""Helper function for fetching gateway callers.""" from dataclasses import dataclass from datadog_api_client import ApiClient, Configuration from datadog_api_client.v2.apis import LogsApi from datadog_api_client.v2.models import ( LogsAggregateRequest, LogsAggregateSort, LogsAggregateSortType, LogsAggregationFunction, LogsCompute, LogsComputeType, LogsGroupBy, LogsQueryFilter, LogsSortOrder, ) @dataclass(frozen=True) class AggregateLogsConfig: """Configuration values for Datadog log aggregation request.""" query: str facet: str group_by_limit: int logs_from: str logs_to: str def aggregate_logs( configuration: Configuration, aggregate_config: AggregateLogsConfig, ) -> dict[str, dict]: """Aggregate logs. Args: configuration: Datadog API client configuration. aggregate_config: Aggregation query and grouping configuration. Returns: dict[str, dict]: Mapping of grouped log facet values to aggregated compute results. """ request_base = LogsAggregateRequest( compute=[ LogsCompute( aggregation=LogsAggregationFunction.COUNT, type=LogsComputeType.TOTAL, ) ], filter=LogsQueryFilter( query=aggregate_config.query, _from=aggregate_config.logs_from, to=aggregate_config.logs_to, indexes=["*"], ), group_by=[ LogsGroupBy( facet=aggregate_config.facet, limit=aggregate_config.group_by_limit, sort=LogsAggregateSort( type=LogsAggregateSortType.MEASURE, aggregation=LogsAggregationFunction.COUNT, order=LogsSortOrder.DESCENDING, ), ) ], ) aggregates_by_facet: dict[str, dict] = {} with ApiClient(configuration) as api_client: logs_api = LogsApi(api_client) response = logs_api.aggregate_logs(body=request_base) buckets = ( response.data.buckets if response.data and response.data.buckets else [] ) for bucket in buckets: facets = bucket.by or {} facet_key = facets.get(aggregate_config.facet) if not isinstance(facet_key, str) or not facet_key.strip(): continue aggregates_by_facet[facet_key] = bucket.computes or {} return aggregates_by_facet