from __future__ import annotations from collections.abc import Sequence from typing import cast from anydi import singleton from cachelib import BaseCache as Cache from fansifter_common.identifiers.types import ( CRMProfileIdentifier, FansifterProfileIdentifier, ProfileIdentifier, ) from preference_center.config import Settings from preference_center.profile.models import Profile, Subscription @singleton class ProfileCache: def __init__(self, cache: Cache, settings: Settings) -> None: self.cache = cache self.settings = settings def get_profile(self, identifier: ProfileIdentifier) -> Profile | None: return cast( Profile | None, self.cache.get(self._profile_key(identifier)), ) def set_profile( self, identifier: ProfileIdentifier, profile: Profile, ) -> None: self.cache.set( self._profile_key(identifier), value=profile, timeout=self.settings.profile_cache_timeout, ) def get_subscriptions(self, profile_id: str) -> Sequence[Subscription] | None: return cast( Sequence[Subscription] | None, self.cache.get(self._subscription_key(profile_id)), ) def set_subscriptions( self, profile_id: str, subscriptions: Sequence[Subscription], ) -> None: key = self._subscription_key(profile_id) self.cache.set( key, subscriptions, timeout=self.settings.subscription_cache_timeout, ) def _profile_key(self, identifier: ProfileIdentifier) -> str: prefix = self.settings.profile_cache_prefix if isinstance(identifier, CRMProfileIdentifier): return f"{prefix}:{identifier.crm_id}" return f"{prefix}:{identifier.profile_id}" def _subscription_key(self, profile_id: str) -> str: return f"{self.settings.subscription_cache_prefix}:{profile_id}:" @staticmethod def _profile_identifiers(profile: Profile) -> list[ProfileIdentifier]: identifiers: list[ProfileIdentifier] = [ FansifterProfileIdentifier.model_construct( profile_id=profile.id, email_campaign_id=None, ) ] if profile.crm_id is not None: identifiers.append( CRMProfileIdentifier.model_construct( crm_id=profile.crm_id, email_campaign_id=None, ) ) return identifiers