"""Make requests to other OWS microservices.""" import httpx from owsclient import OwsClient from moneyhub.config import Config from moneyhub.constants.constants import JWTKeys from moneyhub.constants.constants import OK_RESPONSE from moneyhub.constants.constants import SUCCESS_UPPER_BOUNDARY from moneyhub.utils.request_context import g class RequestContext: """Request context class that conforms to the ows_client RequestContext protocol.""" authorization: str | None = None identity_id: str | None = None profile_id: int | None = None profile_type: str | None = None def __init__( self, authorization: str | None, identity_id: str | None, profile_id: int | None, profile_type: str | None ): """Initialize the class. Args: authorization (str): Authorization header. identity_id (str): Identity ID. profile_id (str): Profile ID. profile_type (str): Profile type. """ self.authorization = authorization self.identity_id = identity_id self.profile_id = profile_id self.profile_type = profile_type def _correlation_id_getter() -> str | None: """Get the correlation ID from the current request context. Returns: str | None: The correlation ID. """ correlation_id = g().correlation_id return f'{correlation_id}.1' if correlation_id else None def _request_context_getter() -> RequestContext: """Build a context object to pass to OwsClient based on the current request context. Returns: str | None: The correlation ID. """ token = g().token or {} return RequestContext( g().authorization, token.get(JWTKeys.ORCHARD_IDENTITY_ID), token.get(JWTKeys.PROFILE_ID), token.get(JWTKeys.PROFILE_TYPE), ) ows_client = OwsClient( environment=Config.ENVIRONMENT, service_name=Config.SERVICE_NAME, correlation_id_getter=_correlation_id_getter, request_context_getter=_request_context_getter, timeout=httpx.Timeout(20) ) def get(service: str, path: str) -> dict | list: """Send a GET request to a service, returning the results. Args: service (str): Microservice to send the request to. path (str): URI to send the request to. Returns: dict | list: Response data. """ response = ows_client.get(service, path) if response.status_code < OK_RESPONSE or response.status_code > SUCCESS_UPPER_BOUNDARY: raise ConnectionError( f'Unexpected response from {service} ({response.status_code}): {response.text}' ) return response