from anydi import singleton from cachelib import BaseCache as Cache from fansifter_common.adapters.ows_account import OwsAccountClient from fansifter_common.utils.cache import cached, make_cache_key from dmp.adapters.features import Features from dmp.rosters.constants import GLOBAL_FAN_DATA_LISTS_FEATURE_ID from dmp.rosters.repositories import ArtistRosterMainRepRepository DEFAULT_CACHE_TIMEOUT = 60 * 10 # 10 minutes @singleton class GlobalFanDataAccessService: def __init__( self, ows_account_client: OwsAccountClient, artist_roster_main_rep_repository: ArtistRosterMainRepRepository, features: Features, cache: Cache, ) -> None: self.ows_account_client = ows_account_client self.artist_roster_main_rep_repository = artist_roster_main_rep_repository self.features = features self.cache = cache @cached("global-fandata-list-enabled-for-vendor", timeout=DEFAULT_CACHE_TIMEOUT) def is_enabled_for_vendor(self, vendor_id: int) -> bool: features = self.ows_account_client.get_vendor_features(vendor_id) for feature in features: if feature.feature_id == GLOBAL_FAN_DATA_LISTS_FEATURE_ID: return True return False def _get_enabled_status_bulk(self, vendor_ids: list[int]) -> dict[int, bool]: if not vendor_ids: return {} cache_keys = [ make_cache_key("global-fandata-list-enabled-for-vendor", vendor_id) for vendor_id in vendor_ids ] cached_values = list(self.cache.get_many(*cache_keys)) result: dict[int, bool] = {} keys_to_set: dict[str, bool] = {} for vendor_id, cache_key, cached_val in zip( vendor_ids, cache_keys, cached_values, strict=False ): if cached_val is not None: result[vendor_id] = cached_val else: features = self.ows_account_client.get_vendor_features(vendor_id) enabled = any( f.feature_id == GLOBAL_FAN_DATA_LISTS_FEATURE_ID for f in features ) result[vendor_id] = enabled keys_to_set[cache_key] = enabled if keys_to_set: self.cache.set_many(keys_to_set, DEFAULT_CACHE_TIMEOUT) return result def is_enabled_for_any_vendor(self, vendor_ids: list[int]) -> bool: return any(self._get_enabled_status_bulk(vendor_ids).values()) def get_enabled_for_any_vendor(self, vendor_ids: list[int]) -> list[int]: status = self._get_enabled_status_bulk(vendor_ids) return [vendor_id for vendor_id, enabled in status.items() if enabled] @cached("global-fandata-list-allowed-for-any-vendor", timeout=DEFAULT_CACHE_TIMEOUT) def has_access_for_artist_and_any_vendor( self, global_participant_id: str, vendor_ids: list[int], subaccount_ids: list[int], ) -> bool: return self.artist_roster_main_rep_repository.exists_by_artist_and_any_account( global_participant_id=global_participant_id, vendor_ids=vendor_ids, subaccount_ids=subaccount_ids, )