|
| 1 | +"""minos.api_gateway.rest.handler module.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import ( |
| 5 | + Any, |
| 6 | +) |
| 7 | + |
| 8 | +from aiohttp import ( |
| 9 | + ClientConnectorError, |
| 10 | + ClientResponse, |
| 11 | + ClientSession, |
| 12 | + web, |
| 13 | +) |
| 14 | +from yarl import ( |
| 15 | + URL, |
| 16 | +) |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +async def orchestrate(request: web.Request) -> web.Response: |
| 22 | + """ Orchestrate discovery and microservice call """ |
| 23 | + discovery_host = request.app["config"].discovery.connection.host |
| 24 | + discovery_port = request.app["config"].discovery.connection.port |
| 25 | + |
| 26 | + verb = request.method |
| 27 | + url = f"/{request.match_info['endpoint']}" |
| 28 | + |
| 29 | + discovery_data = await discover(discovery_host, int(discovery_port), "/microservices", verb, url) |
| 30 | + |
| 31 | + microservice_response = await call(**discovery_data, original_req=request) |
| 32 | + return microservice_response |
| 33 | + |
| 34 | + |
| 35 | +async def discover(host: str, port: int, path: str, verb: str, endpoint: str) -> dict[str, Any]: |
| 36 | + """Call discovery service and get microservice connection data. |
| 37 | +
|
| 38 | + :param host: Discovery host name. |
| 39 | + :param port: Discovery port. |
| 40 | + :param path: Discovery path. |
| 41 | + :param verb: Endpoint Verb. |
| 42 | + :param endpoint: Endpoint url. |
| 43 | + :return: The response of the discovery. |
| 44 | + """ |
| 45 | + |
| 46 | + url = URL.build(scheme="http", host=host, port=port, path=path, query={"verb": verb, "path": endpoint}) |
| 47 | + try: |
| 48 | + async with ClientSession() as session: |
| 49 | + async with session.get(url=url) as response: |
| 50 | + if not response.ok: |
| 51 | + raise web.HTTPBadGateway(text="The discovery response is not okay.") |
| 52 | + data = await response.json() |
| 53 | + except ClientConnectorError: |
| 54 | + raise web.HTTPGatewayTimeout(text="The discovery is not available.") |
| 55 | + |
| 56 | + data["port"] = int(data["port"]) |
| 57 | + |
| 58 | + return data |
| 59 | + |
| 60 | + |
| 61 | +# noinspection PyUnusedLocal |
| 62 | +async def call(address: str, port: int, original_req: web.Request, **kwargs) -> web.Response: |
| 63 | + """Call microservice (redirect the original call) |
| 64 | +
|
| 65 | + :param address: The ip of the microservices. |
| 66 | + :param port: The port of the microservice. |
| 67 | + :param original_req: The original request. |
| 68 | + :param kwargs: Additional named arguments. |
| 69 | + :return: The web response to be retrieved to the client. |
| 70 | + """ |
| 71 | + |
| 72 | + headers = original_req.headers |
| 73 | + url = original_req.url.with_scheme("http").with_host(address).with_port(port) |
| 74 | + method = original_req.method |
| 75 | + content = await original_req.text() |
| 76 | + |
| 77 | + logger.info(f"Redirecting {method!r} request to {url!r}...") |
| 78 | + |
| 79 | + try: |
| 80 | + async with ClientSession(headers=headers) as session: |
| 81 | + async with session.request(method=method, url=url, data=content) as response: |
| 82 | + return await _clone_response(response) |
| 83 | + except ClientConnectorError: |
| 84 | + raise web.HTTPServiceUnavailable(text="The requested endpoint is not available.") |
| 85 | + |
| 86 | + |
| 87 | +# noinspection PyMethodMayBeStatic |
| 88 | +async def _clone_response(response: ClientResponse) -> web.Response: |
| 89 | + return web.Response( |
| 90 | + body=await response.read(), status=response.status, reason=response.reason, headers=response.headers, |
| 91 | + ) |
0 commit comments