"""Logic for retrieving top sound recordings.""" from typing import Any, Mapping from ddtrace import tracer from oto import response as oto_response from analytics.constants import cache from analytics.queries.format import format_row from analytics.queries.top_sound_recordings import TopSoundRecordings from analytics.schemas import top_sound_recordings as top_sound_recordings_schema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis from analytics.validation.schema import schema_dump TOP_SOUND_RECORDINGS_METRICS = [ "streams_1_day", "streams_7_days", "streams_28_days", "streams_all_time", ] @cache_in_redis(ttl=cache.ONE_DAY) @tracer.wrap(name="get_top_sound_recordings") def get_top_sound_recordings( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Fetch top sound recordings. Args: query_params: Dict with distributors, country_ids, order_by, limit, offset. permissions: Dict with permission_* keys. Returns: oto_response.Response with top sound recordings payload. """ order_by = query_params["order_by"] if order_by not in TOP_SOUND_RECORDINGS_METRICS: raise Exception("Invalid order_by field") query_input = { **permissions, "distributors": query_params["distributors"], "country_ids": query_params.get("country_ids", []), "store_ids": store_availability.get_store_ids(), "order_by": order_by, "all_time": order_by == "streams_all_time", "limit": query_params["limit"], "offset": query_params["offset"], "transfer_product_ownership_enabled": query_params.get( "transfer_product_ownership_enabled", False ), # STREAMS_BY_TRACK_*_ROLLUP is widened by the transfer-product-ownership # dbt PR; rollup_grain dedups former-owner rows that would otherwise # inflate SUM()s post-transfer. "rollup_grain": True, } items = [format_row(row) for row in TopSoundRecordings(query_input).execute()] if not items: return oto_response.Response({"items": []}) schema = top_sound_recordings_schema.TopSoundRecordingsSchema() return oto_response.Response(schema_dump(schema, {"items": items}))