from typing import List from api import cache from external_api.streams_analytics.providers.AmazonStreamsProvider import AmazonStreamsProvider from external_api.streams_analytics.providers.AppleStreamsProvider import AppleStreamsProvider from external_api.streams_analytics.providers.SpotifyStreamsProvider import SpotifyStreamsProvider from external_api.streams_analytics.providers.TrackStreamsProvider import TrackStreamsProvider from external_api.base.analytics_models import TrackStreamsQuery, TrackStreamsResult from external_api.base.clients.client_factory import ApiClientFactory from config import DEFAULT_STREAMS_CACHE_TIMEOUT_SEC from utils.async_helpers import await_all class TrackStreamsFetcher: providers: List[TrackStreamsProvider] = [] def __init__(self, providers: List[TrackStreamsProvider]) -> None: self.providers = providers async def fetch(self, query: TrackStreamsQuery) -> List[TrackStreamsResult]: cache_key = self.make_cache_key(query) cached_result = cache.get(cache_key) if cached_result is not None: return cached_result result = await self.fetch_fresh_streams(query) cache.set(cache_key, result, timeout=DEFAULT_STREAMS_CACHE_TIMEOUT_SEC) return result def make_cache_key(self, query): return "streams-cache:" + query.__repr__() async def fetch_fresh_streams(self, query: TrackStreamsQuery): tasks = list(map(lambda p: p.fetch(query), self.providers)) result = await await_all(tasks) return result def default_track_streams_fetcher() -> TrackStreamsFetcher: apollo_api_client = ApiClientFactory.apollo_api_client() delphi_api_client = ApiClientFactory.delphi_client() providers: List[TrackStreamsProvider] = [ SpotifyStreamsProvider(apollo_api_client), AppleStreamsProvider(apollo_api_client), AmazonStreamsProvider(delphi_api_client), ] return TrackStreamsFetcher(providers)