Source code for smarter.apps.account.caching

"""
Cached lookups of accounts, users and user profiles, and the commonly used objects of the Smarter account.

Like each app's ``caching`` module (e.g. :mod:`smarter.apps.llmclient.caching`), this holds the account app's
cached reads, through ``@cache_results``:

- :data:`smarter_cached_objects`, the Smarter account, its admin and the platform admin, lazily loaded.
- ``get_cached_*`` functions: the default account, a user's account, a user by id or by username, a user's
  avatar url, and an account's admin user, which :func:`get_cached_admin_user_for_account` creates if the
  account has none.
"""

from typing import Optional, Union

from cache_results import cache_results
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django.templatetags.static import static
from typing_extensions import deprecated

from smarter.apps.account.models import (
    Account,
    User,
    UserProfile,
)
from smarter.apps.account.models.user_profile import DEFAULT_PROFILE_IMAGE
from smarter.common.conf import smarter_settings
from smarter.common.const import SMARTER_ACCOUNT_NUMBER
from smarter.common.exceptions import SmarterConfigurationError
from smarter.lib import logging
from smarter.lib.django.waffle import SmarterWaffleSwitches

logger = logging.getSmarterLogger(
    __name__, any_switches=[SmarterWaffleSwitches.ACCOUNT_LOGGING, SmarterWaffleSwitches.CACHE_LOGGING]
)


# commonly fetched objects
# ----------------------------
# pylint: disable=W0613
[docs] class SmarterCachedObjects: """ Lazy instantiations of cached objects for the smarter account. This is a much-simplified means of caching commonly used objects without having to actually decorate every function that fetches them. :raises SmarterConfigurationError: If the smarter account or admin user cannot be found. .. note:: This class uses lazy loading to fetch and cache the smarter account and admin user only when accessed. """ _smarter_admin_user_profile: Optional[UserProfile] = None _admin_user: Optional[User] = None
[docs] def __init__(self): self.base_cache_key = f"{__name__}.{SmarterCachedObjects.__name__}[{id(self)}]"
@property def smarter_account(self) -> Account: """ Retrieve the smarter account instance. :returns: Account instance representing the smarter account. :raises SmarterConfigurationError: If the smarter account cannot be found. """ retval = Account.get_cached_object(account_number=SMARTER_ACCOUNT_NUMBER) if not retval: raise SmarterConfigurationError( f"Smarter account with account number {SMARTER_ACCOUNT_NUMBER} does not exist." ) return retval @property def smarter_admin(self) -> User: """ Retrieve the smarter admin user instance. :returns: User instance representing the smarter admin. :raises SmarterConfigurationError: If the smarter admin user cannot be found. """ return self.smarter_admin_user_profile.user @property def smarter_admin_user_profile(self) -> UserProfile: """ Retrieve the UserProfile instance for the smarter admin user. Lazy loads and caches the UserProfile on first access. Subsequent accesses will return the cached UserProfile, with a periodic refresh from the database to ensure data consistency. :returns: UserProfile instance for the smarter admin user. :raises SmarterConfigurationError: If the UserProfile cannot be found. """ @cache_results(cache_key=self.base_cache_key + ".smarter_admin_user_profile") def _requery_smarter_admin_user_profile(class_name=SmarterCachedObjects.__name__) -> None: if isinstance(self._smarter_admin_user_profile, UserProfile): logger.debug( "re-queried %s", self._smarter_admin_user_profile, ) try: self._smarter_admin_user_profile.refresh_from_db() except UserProfile.DoesNotExist: self._smarter_admin_user_profile = None _requery_smarter_admin_user_profile.invalidate(class_name=SmarterCachedObjects.__name__) if not self._smarter_admin_user_profile: try: user_profile = ( UserProfile.objects.filter(account=self.smarter_account).filter(user__is_superuser=True).first() ) self._smarter_admin_user_profile = user_profile logger.debug( "initialized %s", user_profile, ) return self._smarter_admin_user_profile # type: ignore[return-value] except UserProfile.DoesNotExist as e: raise SmarterConfigurationError("No superuser user profile found for smarter account") from e _requery_smarter_admin_user_profile(class_name=SmarterCachedObjects.__name__) return self._smarter_admin_user_profile # type: ignore[return-value] @property def admin_user(self) -> User: """ Retrieve the admin user instance for the smarter account. Lazy loads and caches the user on first access. Subsequent accesses will return the cached user, with a periodic refresh from the database to ensure data consistency. :returns: User instance representing the admin user. :raises SmarterConfigurationError: If the admin user cannot be found. """ @cache_results(cache_key=self.base_cache_key + ".admin_user") def _requery_admin_user(class_name=SmarterCachedObjects.__name__) -> None: if self._admin_user: self._admin_user.refresh_from_db() logger.debug( "re-queried %s", self._admin_user, ) if not self._admin_user: try: self._admin_user = User.objects.get( username=smarter_settings.platform_admin_username, is_superuser=True ) logger.debug( "initialized %s", self._admin_user, ) return self._admin_user except User.DoesNotExist as e: raise SmarterConfigurationError("No superuser found for smarter account") from e _requery_admin_user(class_name=SmarterCachedObjects.__name__) return self._admin_user # type: ignore[return-value]
smarter_cached_objects = SmarterCachedObjects() """ Smarter_cached_objects = SmarterCachedObjects(). An instance of `SmarterCachedObjects` for accessing commonly used cached objects. Functions as a singleton for the project. """
[docs] def get_cached_default_account(invalidate: bool = False) -> Account: """ Retrieve the default account instance, using caching for performance. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: The default Account instance. .. important:: The default account is determined by the ``is_default_account=True`` flag in the database. .. warning:: If no default account exists, an exception may be raised. **Example usage**:: # Get the default account default_account = get_cached_default_account() # Invalidate cache before fetching default_account = get_cached_default_account(invalidate=True) """ @cache_results(cache_key="smarter.apps.account.caching.get_cached_default_account") def _get_default_account() -> Account: try: return Account.objects.get(is_default_account=True) except Account.DoesNotExist as e: raise SmarterConfigurationError( "No default account found. Please ensure an account is marked as the default account." ) from e except Account.MultipleObjectsReturned as e: accounts = Account.objects.filter(is_default_account=True) accounts_list = [str(account) for account in accounts] raise SmarterConfigurationError( f"Multiple default accounts found: {', '.join(accounts_list)}. Please ensure only one account is marked as the default account." ) from e if invalidate: _get_default_account.invalidate() return _get_default_account()
@cache_results() def _get_cached_account_for_user_id(user_id: int, class_name: str = UserProfile.__name__) -> Account: """ Return the account of a user's profile in the default account, else of their first profile. :func:`get_cached_account_for_user` caches it, for a user who chose no profile in the web console. :param user_id: The user's primary key. :param class_name: Part of the cache key, the model whose rows the result depends on. :returns: The account. :raises Account.DoesNotExist: If the user has no profile. """ user_profiles = UserProfile.objects.filter(user_id=user_id) for user_profile in user_profiles: if not isinstance(user_profile, UserProfile): raise SmarterConfigurationError(f"Expected UserProfile instance, got {type(user_profile)}") if user_profile.account.is_default_account: logger.debug( "retrieving and caching default account %s for user ID %s", user_profile.cached_account, user_id, ) return user_profile.cached_account # type: ignore[return-value] # If no default account is found, return the first account user_profile = user_profiles.first() if not user_profile: logger.warning("no UserProfile found for user ID %s", user_id) raise Account.DoesNotExist() account = user_profile.cached_account logger.debug( "retrieving and caching default account %s for user ID %s", account, user_id, ) return account # type: ignore[return-value]
[docs] def get_cached_account_for_user( invalidate: Optional[bool] = False, user: Optional[Union[User, AnonymousUser]] = None ) -> Account: """ Locate the Account associated with a given user, using caching for performance. The account is that of the UserProfile that the user chose in the web console's user menu, for this request (see :meth:`UserProfile.get_selected_object() <smarter.apps.account.models.UserProfile.get_selected_object>`), else the default account, if the user belongs to it, else the account of the user's first profile. :param user: User instance. The user whose account should be located. Any other user, such as an AnonymousUser, has no account. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: Account instance if found, otherwise None. .. warning:: If no account is found for the user, None is returned and a warning is logged. .. tip:: Use ``invalidate=True`` after updating user or account data to ensure cache consistency. **Example usage**:: # Locate account for a user account = get_cached_account_for_user(user) # Invalidate cache before fetching account = get_cached_account_for_user(user, invalidate=True) """ if not isinstance(user, User): logger.warning("invalid user type: %s", type(user)) raise Account.DoesNotExist() username = getattr(user, "username") if username == smarter_settings.platform_admin_username: return smarter_cached_objects.smarter_account user_id = getattr(user, "id", None) if not user_id: logger.warning("user has no ID: %s", user) raise Account.DoesNotExist() # the account of the profile that the user chose in the web console's user menu, if any. selected_user_profile = UserProfile.get_selected_object(user_id) if selected_user_profile: return selected_user_profile.cached_account if invalidate: _get_cached_account_for_user_id.invalidate(user_id, class_name=UserProfile.__name__) return _get_cached_account_for_user_id(user_id, class_name=UserProfile.__name__)
[docs] def get_cached_user_for_user_id(invalidate: Optional[bool] = False, user_id: Optional[int] = None) -> User: """ Retrieve a User instance by its primary key, using caching for performance. :param user_id: Integer. The primary key of the user to retrieve. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: User instance if found, otherwise None. .. warning:: If no user exists for the given ID, None is returned and an error is logged. .. tip:: Use ``invalidate=True`` after updating user data to ensure cache consistency. **Example usage**:: # Retrieve user by ID user = get_cached_user_for_user_id(user_id=123) # Invalidate cache before fetching user = get_cached_user_for_user_id(user_id=123, invalidate=True) """ @cache_results() def _get_user(user_id: int, class_name: str = User.__name__) -> User: """In-memory cache for user objects.""" try: user = User.objects.get(id=user_id) logger.debug("retrieving and caching user %s", user) return user # type: ignore[return-value] except User.DoesNotExist as e: logger.error("user with ID %s does not exist", user_id) raise e if user_id is None: logger.error("user with ID %s does not exist", user_id) raise User.DoesNotExist() if invalidate: _get_user.invalidate(user_id, class_name=User.__name__) return _get_user(user_id, class_name=User.__name__)
[docs] def get_cached_avatar_url(user_id: int, invalidate: Optional[bool] = False) -> str: """ Return the url of the image that represents a user in the web console, using caching for performance. The url is :attr:`UserProfile.avatar_url`: the image the user uploaded, else the one the oauth provider supplied, else the default profile image. A user with no UserProfile gets the default profile image. The UserProfile is the one that the user chose in the web console's user menu, for this request, else their newest. :param user_id: Integer. The primary key of the user. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: The image's url. .. tip:: Use ``invalidate=True`` after changing a user's profile image, so that the console shows it at once. **Example usage**:: url = get_cached_avatar_url(user_id=request.user.id) """ @cache_results() def _get_avatar_url(user_id: int, class_name: str = UserProfile.__name__) -> str: user_profile = UserProfile.objects.filter(user_id=user_id).order_by("-pk").first() if user_profile is None: return static(DEFAULT_PROFILE_IMAGE) return user_profile.avatar_url if invalidate: _get_avatar_url.invalidate(user_id, class_name=UserProfile.__name__) # the image of the profile that the user chose in the web console's user menu, if any. selected_user_profile = UserProfile.get_selected_object(user_id) if selected_user_profile: return selected_user_profile.avatar_url return _get_avatar_url(user_id, class_name=UserProfile.__name__)
[docs] def get_cached_user_for_username(invalidate: Optional[bool] = False, username: Optional[str] = None) -> User: """ Retrieve a User instance by its username, using caching for performance. :param username: String. The username of the user to retrieve. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: User instance if found, otherwise None. .. warning:: If no user exists for the given username, a User.DoesNotExist exception is raised and an error is logged. .. tip:: Use ``invalidate=True`` after updating user data to ensure cache consistency. **Example usage**:: # Retrieve user by username user = get_cached_user_for_username("johndoe") # Invalidate cache before fetching user = get_cached_user_for_username("johndoe", invalidate=True) """ @cache_results() def _in_memory_user_by_username(username: str, class_name: str = User.__name__) -> User: """In-memory cache for user objects by username.""" try: user = User.objects.get(username=username) logger.debug("retrieving and caching user %s", user) return user # type: ignore[return-value] except User.DoesNotExist as e: logger.debug("user with username %s does not exist", username) raise e if username is None: logger.debug("user with username %s does not exist", username) raise User.DoesNotExist() if invalidate: _in_memory_user_by_username.invalidate(username, class_name=User.__name__) if username == smarter_settings.platform_admin_username: return smarter_cached_objects.admin_user return _in_memory_user_by_username(username, class_name=User.__name__)
ACCOUNT_ADMIN_USERNAME_SUFFIX = "-admin" """The username of the admin user that :func:`get_cached_admin_user_for_account` creates is its account number plus this."""
[docs] def account_admin_username(account_number: str) -> str: """ The username of the admin user that :func:`get_cached_admin_user_for_account` creates for an account. :param account_number: The account's number, e.g. ``1234-5678-9012``. :returns: e.g. ``1234-5678-9012-admin``. """ retval = f"{account_number}{ACCOUNT_ADMIN_USERNAME_SUFFIX}" return retval
[docs] def get_cached_admin_user_for_account(account: Account, invalidate: Optional[bool] = False) -> User: """ Retrieve the admin user for a given account, creating one if necessary. :param account: Account instance. The account for which to retrieve the admin user. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: User instance representing the account admin. .. important:: If no admin user exists for the account, a new staff user and UserProfile will be created automatically. .. warning:: If the account is missing or misconfigured, an exception is raised. .. tip:: Use ``invalidate=True`` after updating admin user data to ensure cache consistency. **Example usage**:: # Retrieve the admin user for an account admin_user = get_cached_admin_user_for_account(account=account) # Invalidate cache before fetching admin_user = get_cached_admin_user_for_account(invalidate=True, account=account) """ if not isinstance(account, Account): raise User.DoesNotExist("Invalid account provided") @cache_results() def _admin_user_for_account_number(account_number: str, class_name=User.__name__) -> User: # reinstantiate the account try: account = Account.objects.get(account_number=account_number) except Account.DoesNotExist as e: logger.error( "account with number %s does not exist", account_number, ) raise e user_profile = ( UserProfile.objects.filter(account=account) .filter(Q(user__is_staff=True) | Q(user__is_superuser=True) | Q(is_account_admin=True)) .select_related("user", "account") .order_by("pk") .first() ) if user_profile: logger.debug("found and cached admin UserProfile %s for account %s", user_profile, account) return user_profile.cached_user # type: ignore[return-value] else: logger.warning("no admin user found for account %s. Creating new admin user.", account) # an account whose every profile is a test profile is a test account, e.g. the end-to-end tests' # throwaway account. Its admin is a test profile too, so that its contact's welcome email is sent # quietly, rather than to <account>-admin@<root domain>, and the test teardown deletes it. account_profiles = UserProfile.objects.filter(account=account) has_profiles = account_profiles.exists() has_real_profiles = account_profiles.filter(is_test=False).exists() is_test_account = has_profiles and not has_real_profiles username = account_admin_username(str(account.account_number)) # the administrator of this account only: UserProfile.is_account_admin. Never a superuser or a # staff user, who would administer, or read, other accounts too. new_user = User.objects.create( username=username, email=f"{username}@{smarter_settings.platform_root_domain}", is_staff=False, is_superuser=False, is_active=True, ) user_profile = UserProfile.objects.create( name=username, user=new_user, account=account, is_test=is_test_account, is_account_admin=True ) return user_profile.user # type: ignore[return-value] account_number = str(account.account_number) if invalidate: _admin_user_for_account_number.invalidate(account_number=account_number, class_name=User.__name__) return _admin_user_for_account_number(account_number=account_number, class_name=User.__name__)
[docs] @deprecated( "This function is deprecated and may be removed in a future release. Please use smarter_cached_objects.smarter_admin_user_profile" ) def get_cached_smarter_admin_user_profile() -> UserProfile: """ Retrieve the admin UserProfile for the smarter account, using caching for performance. :returns: UserProfile instance for the smarter admin user. .. note:: The smarter admin user is typically a superuser or staff user associated with the platform's main account. **Example usage**:: # Retrieve the smarter admin user profile admin_profile = get_cached_smarter_admin_user_profile() # Invalidate cache before fetching admin_profile = get_cached_smarter_admin_user_profile(invalidate=True) """ return smarter_cached_objects.smarter_admin_user_profile
__all__ = [ "ACCOUNT_ADMIN_USERNAME_SUFFIX", "SmarterCachedObjects", "account_admin_username", "get_cached_account_for_user", "get_cached_admin_user_for_account", "get_cached_avatar_url", "get_cached_default_account", "get_cached_smarter_admin_user_profile", "get_cached_user_for_user_id", "get_cached_user_for_username", "smarter_cached_objects", ]