|
| 1 | +"""Decorators to rethrow and log exceptions.""" |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from functools import cached_property, wraps |
| 5 | +from inspect import iscoroutinefunction |
| 6 | +from typing import Any, Callable, Type |
| 7 | + |
| 8 | +from cachetools import LRUCache # type:ignore |
| 9 | + |
| 10 | +from app.logger import logger |
| 11 | + |
| 12 | + |
| 13 | +class ExceptionContext: |
| 14 | + SENSITIVE_KEYS: frozenset[str] = frozenset( |
| 15 | + ("password", "token", "key", "secret", "auth", "credential", "passwd") |
| 16 | + ) |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + original_exception: Exception, |
| 21 | + func: Callable, |
| 22 | + args: tuple[Any, ...], |
| 23 | + kwargs: dict[str, Any], |
| 24 | + ): |
| 25 | + self.original_exception = original_exception |
| 26 | + self.func = func |
| 27 | + self.args = args |
| 28 | + self.kwargs = kwargs |
| 29 | + |
| 30 | + @cached_property |
| 31 | + def formatted_context(self) -> str: |
| 32 | + error_context = [ |
| 33 | + f"Error in function '{self.func.__module__}.{self.func.__qualname__}'" |
| 34 | + ] |
| 35 | + |
| 36 | + if self.args: |
| 37 | + args_str = ", ".join(self._sanitised_value(arg) for arg in self.args) |
| 38 | + error_context.append(f"Args: [{args_str}]") |
| 39 | + |
| 40 | + if self.kwargs: |
| 41 | + kwargs_str = ", ".join( |
| 42 | + f"{k}={self._sanitised_value(v, k)}" for k, v in self.kwargs.items() |
| 43 | + ) |
| 44 | + error_context.append(f"Kwargs: {kwargs_str}") |
| 45 | + |
| 46 | + return "\n".join(error_context).replace("{", "{{").replace("}", "}}") |
| 47 | + |
| 48 | + def _sanitised_value( |
| 49 | + self, |
| 50 | + value: Any, |
| 51 | + key: str | None = None, |
| 52 | + ) -> str: |
| 53 | + if key is not None and key.lower() in self.SENSITIVE_KEYS: |
| 54 | + return "****HIDDEN****" |
| 55 | + |
| 56 | + try: |
| 57 | + str_value = str(value) |
| 58 | + return f"{str_value[:100]}..." if len(str_value) > 100 else str_value |
| 59 | + except Exception: |
| 60 | + return f"<{type(value).__name__} object - str() failed>" |
| 61 | + |
| 62 | + |
| 63 | +class ExceptionFactory(ABC): |
| 64 | + """ |
| 65 | + Create and describe a factory for exceptions. |
| 66 | +
|
| 67 | + This class is an abstract base class meant to define the interface for an |
| 68 | + exception factory. |
| 69 | +
|
| 70 | + """ |
| 71 | + |
| 72 | + @abstractmethod |
| 73 | + def make_exception(self, context: ExceptionContext) -> Exception: |
| 74 | + """Make an exception based on the given context.""" |
| 75 | + |
| 76 | + |
| 77 | +class EnrichedExceptionFactory(ExceptionFactory): |
| 78 | + """ |
| 79 | + Create and manage enriched exceptions based on a given exception type. |
| 80 | +
|
| 81 | + This class provides a mechanism to create exceptions dynamically, |
| 82 | + enriching them with a formatted context. It extends the behavior of |
| 83 | + the base ExceptionFactory class by incorporating the concept of a |
| 84 | + generated error type and formatted context. |
| 85 | +
|
| 86 | + :ivar generated_error: The type of exception to generate when creating |
| 87 | + an enriched exception. |
| 88 | + :type generated_error: type[Exception] |
| 89 | + """ |
| 90 | + |
| 91 | + def __init__(self, generated_error: type[Exception]): |
| 92 | + self.generated_error = generated_error |
| 93 | + |
| 94 | + def make_exception(self, context: ExceptionContext) -> Exception: |
| 95 | + return self.generated_error(context.formatted_context) |
| 96 | + |
| 97 | + |
| 98 | +ExceptionOrTupleOfExceptions = Type[Exception] | tuple[Type[Exception], ...] |
| 99 | + |
| 100 | + |
| 101 | +class ExceptionMapper: |
| 102 | + """Exception-mapping decorator with bounded LRU caching and dynamic MRO lookup.""" |
| 103 | + |
| 104 | + def __init__( |
| 105 | + self, |
| 106 | + exception_map: dict[ExceptionOrTupleOfExceptions, ExceptionFactory], |
| 107 | + max_cache_size: int = 512, |
| 108 | + log_error: bool = True, |
| 109 | + is_bound_method: bool = False, |
| 110 | + ): |
| 111 | + self.mapping = self._get_flat_map(exception_map) |
| 112 | + self.exception_catchall_factory = self.mapping.pop(Exception, None) |
| 113 | + self._lru_cache: LRUCache = LRUCache(maxsize=max_cache_size) |
| 114 | + self.log_error = log_error |
| 115 | + self.is_bound_method = is_bound_method |
| 116 | + |
| 117 | + def __call__(self, func: Callable) -> Callable: |
| 118 | + return ( |
| 119 | + self._async_wrapper(func) |
| 120 | + if iscoroutinefunction(func) |
| 121 | + else self._sync_wrapper(func) |
| 122 | + ) |
| 123 | + |
| 124 | + def _get_flat_map( |
| 125 | + self, |
| 126 | + exception_map: dict[ExceptionOrTupleOfExceptions, ExceptionFactory], |
| 127 | + ) -> dict[Type[Exception], ExceptionFactory]: |
| 128 | + flat_map: dict[Type[Exception], ExceptionFactory] = {} |
| 129 | + for exception_class, factory in exception_map.items(): |
| 130 | + if isinstance(exception_class, tuple): |
| 131 | + for exc_type in exception_class: |
| 132 | + flat_map[exc_type] = factory |
| 133 | + else: |
| 134 | + flat_map[exception_class] = factory |
| 135 | + return flat_map |
| 136 | + |
| 137 | + def _async_wrapper(self, func: Callable) -> Callable: |
| 138 | + @wraps(func) |
| 139 | + async def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 140 | + try: |
| 141 | + return await func(*args, **kwargs) |
| 142 | + except Exception as exc: |
| 143 | + self._handle_exception_logic(exc, func, args, kwargs) |
| 144 | + |
| 145 | + return wrapper |
| 146 | + |
| 147 | + def _sync_wrapper(self, func: Callable) -> Callable: |
| 148 | + @wraps(func) |
| 149 | + def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 150 | + try: |
| 151 | + return func(*args, **kwargs) |
| 152 | + except Exception as exc: |
| 153 | + self._handle_exception_logic(exc, func, args, kwargs) |
| 154 | + |
| 155 | + return wrapper |
| 156 | + |
| 157 | + def _filtered_args(self, args: tuple[Any, ...]) -> tuple[Any, ...]: |
| 158 | + return args[1:] if args and self.is_bound_method else args |
| 159 | + |
| 160 | + def _handle_exception_logic( |
| 161 | + self, |
| 162 | + exc: Exception, |
| 163 | + func: Callable, |
| 164 | + args: tuple[Any, ...], |
| 165 | + kwargs: dict[str, Any], |
| 166 | + ) -> None: |
| 167 | + context = ExceptionContext(exc, func, self._filtered_args(args), kwargs) |
| 168 | + if self.log_error: |
| 169 | + logger.error(context.formatted_context, exc_info=True) |
| 170 | + |
| 171 | + if exception_factory := self._get_exception_factory(type(exc)): |
| 172 | + raise exception_factory.make_exception(context) from exc |
| 173 | + |
| 174 | + raise exc |
| 175 | + |
| 176 | + def _get_exception_factory( |
| 177 | + self, exc_type: Type[Exception] |
| 178 | + ) -> ExceptionFactory | None: |
| 179 | + # Try to get from_cache |
| 180 | + if cached_factory := self._lru_cache.get(exc_type): |
| 181 | + return cached_factory |
| 182 | + |
| 183 | + # Try to find exception parents in base mapping and put to cache if found |
| 184 | + for exc_class in exc_type.mro(): |
| 185 | + if target_exception_factory := self.mapping.get(exc_class): # type:ignore |
| 186 | + self._lru_cache[exc_type] = target_exception_factory |
| 187 | + return target_exception_factory |
| 188 | + |
| 189 | + # exception is not presented in base mapping, but Exception in base mapping |
| 190 | + if self.exception_catchall_factory: |
| 191 | + self._lru_cache[exc_type] = self.exception_catchall_factory |
| 192 | + return self.exception_catchall_factory |
| 193 | + |
| 194 | + return None |
0 commit comments