"""Stream (getstream.io) Client.""" import functools from typing import Any, Callable, Mapping, Type, TypeVar, cast from ddtrace import tracer from getstream_connector import get_client from owsresponse import response, status as ows_status from stream import exceptions as stream_exceptions from notifications import config from notifications.connectors import sentry from notifications.constants import error EXCEPTION_STATUS_MAPPING: Mapping[Type[Exception], int] = { stream_exceptions.ApiKeyException: ows_status.UNAUTHORIZED, stream_exceptions.FeedConfigException: ows_status.NOT_FOUND, stream_exceptions.InputException: ows_status.BAD_REQUEST, } DEFAULT_STATUS = ows_status.INTERNAL_ERROR F = TypeVar('F', bound=Callable[..., response.Response]) def capture_exceptions(f: F) -> F: """Decorate the function to catch various exceptions. Args: f (callable): the function to decorate Returns: callable: the decorated function """ @functools.wraps(f) def wrapper(*args: Any, **kwargs: Any) -> response.Response: try: return f(*args, **kwargs) except Exception as e: res = response.create_error_response( status=EXCEPTION_STATUS_MAPPING.get(type(e), DEFAULT_STATUS), code=error.ERROR_CODE_STREAM_API, message=str(e), ) sentry.send_response_to_sentry(res, error.ERROR_CODE_STREAM_API) if current_span := tracer.current_span(): current_span.set_traceback() return res return cast(F, wrapper) if config.ENVIRONMENT == config.TEST_ENVIRONMENT: from unittest.mock import MagicMock stream_client = MagicMock() else: stream_client = get_client( api_key=config.STREAM_API_KEY, api_secret=config.STREAM_API_SECRET, location=config.STREAM_API_REGION, )