from aiohttp import web from apollo_utils.service.exceptions import UnsupportedCacheMode from contextvars import ContextVar from enum import Enum from server import config class CacheMode(Enum): """Supported cache modes. REGULAR - regular usage: first try to find data in cache, if nothing was found, load new data and store it in cache. UPDATE - do not check cache, load new data and store it in cache. IGNORE - load new data and return it without saving to cache. """ REGULAR = "regular" UPDATE = "update" IGNORE = "ignore" @classmethod def has(cls, value): return value in cls._value2member_map_ DEFAULT_CACHE_MODE = CacheMode.REGULAR cache_mode = ContextVar("cache_mode", default=DEFAULT_CACHE_MODE) def set_cache_mode(request: web.Request): """Set cache mode based on headers value and configuration.""" mode = request.headers.get("Cache-Mode") if not mode or not config.ALLOW_CACHE_MODES: return if not CacheMode.has(mode): raise UnsupportedCacheMode(f"Got unsupported cache mode value {mode}") cache_mode.set(CacheMode(mode))