""" FastAPI router for query endpoints. Query endpoints are used to retrieve data from Snowflake and return it to the client. """ from datetime import date, timedelta from cachetools import TTLCache from fastapi import APIRouter from fastapi.responses import JSONResponse from ... import logger from ...logic import queries from ...responses import json_200_data from ...typings import LabelID logger = logger.new_logger(__name__) ROUTE: str = "/audits/query" # Cache for top_label_artists_by_yt_revenue, with a TTL of 24 hours (because the # data is not expected to change frequently) top_label_artists_by_yt_revenue_cache = TTLCache(maxsize=256, ttl=3600 * 24) def create_router(*args, **kwargs): """Create FastAPI router.""" app = APIRouter() @app.get("/top_label_artists_by_yt_revenue", response_class=JSONResponse) async def top_label_artists_by_youtube_revenue_last_12_months( label: LabelID, limit: int | None = 10 ): """Get top artists by net revenue from YouTube for a given label, taking into account the last 12 months. Args: label: The label ID (e.g. 1234). limit: The maximum number of artists to return. Defaults to 10. If None, all artists will be returned. Returns: A list of the top 10 artists by net revenue from YouTube for the given label, or less than this if there are fewer artists for the label. The list is sorted by net revenue, descending. """ cached_response = top_label_artists_by_yt_revenue_cache.get(label) if cached_response is not None: logger.debug( "Getting from cache top label artists by net revenue from YouTube for " "label {}...", label, ) return json_200_data(cached_response) logger.debug( "Getting from DB top label artists by net revenue from YouTube for " "label {}...", label, ) rows = await queries.get_top_label_artists_by_revenue( label, stores=[ 453, # YouTube ], start_date=date.today() - timedelta(days=365), limit=limit, ) # Make sure the rows are sorted by net revenue, descending sorted_rows = sorted(rows, key=lambda row: row["net_revenue"], reverse=True) # For security reasons, we only return the artist ID and name, excluding # any other data such as 'net_revenue'. This could be returned in the future # if necessary. results = [{"id": row["id"], "name": row["name"]} for row in sorted_rows] top_label_artists_by_yt_revenue_cache[label] = results return json_200_data(results) return app