"""Interface to the ows-track microservice.""" from typing import List import backoff from cachetools.func import ttl_cache from owsrequest import request from collaborator import config from collaborator.constants import error, service_name from collaborator.utils import owsrequest from collaborator.utils.error import OwsError from collaborator.utils.helpers import get_from_response from collaborator.utils.ttl_cache_list import ttl_cache_list @ttl_cache() @backoff.on_exception( wait_gen=backoff.expo, exception=OwsError, max_tries=config.MAX_NETWORK_REQUEST_RETRIES, logger=config.LOGGER_NAME, ) def get_track(tuid: str) -> dict: """Get information about a track. tuid (str): The track tuid. Returns: oto.response.Response """ track_url = f"/track/{tuid}" res = request.get(service_name.OWS_TRACK, track_url) return owsrequest.unwrap_data_or_error(res, error.ERROR_CODE_OWS_TRACK) @ttl_cache_list @backoff.on_exception( wait_gen=backoff.expo, exception=OwsError, max_tries=config.MAX_NETWORK_REQUEST_RETRIES, logger=config.LOGGER_NAME, ) def get_tracks(tuids: List[str]) -> dict: """Get information about tracks. tuid (str): The track tuid. Returns: oto.response.Response """ track_url = "/tracks" res = request.get( service_name.OWS_TRACK, track_url, params={"tuids": ",".join(tuids)} ) return owsrequest.unwrap_data_or_error(res, error.ERROR_CODE_OWS_TRACK) def get_tracks_batched(tuids: List[str], batch_size=100): """Get information about tracks in batches. Args: tuids (List[str]): List of tuids to get information for. batch_size (int, optional): Size of batches. Defaults to 100. Returns: List[dict]: List of track information objects. """ tuids_batches = [ tuids[i : i + batch_size] for i in range(0, len(tuids), batch_size) ] responses = [get_tracks(tuids_batch) for tuids_batch in tuids_batches] responses_items = [get_from_response(response, "items") for response in responses] tracks = [track for response_items in responses_items for track in response_items] return tracks def get_tracks_by_product_id(product_id: int) -> list: """Get information about tracks by product IDs. Args: product_id (int): Product ID. Returns: oto.response.Response """ path = f"/product/{product_id}/tracks" res = request.get( service_name.OWS_TRACK, path, ) tracks_data = res.json() tracks = tracks_data.get("items", []) return tracks