|
| 1 | +from types import CoroutineType |
| 2 | +from typing import Any |
| 3 | +from collections.abc import Callable, Awaitable |
| 4 | + |
| 5 | +from faststream import BaseMiddleware |
| 6 | +from faststream.broker.message import StreamMessage |
| 7 | +from faststream.rabbit.message import RabbitMessage |
| 8 | + |
| 9 | +from src.env import queue |
| 10 | +from src.utils.logger import Logger |
| 11 | +from src.api.services.UtilityService import UtilityService |
| 12 | +from src.api.constants.signature_sources import SIGNATURE_SOURCES |
| 13 | + |
| 14 | + |
| 15 | +class PublishMiddleware(BaseMiddleware): |
| 16 | + """ |
| 17 | + Middleware to handle subscription messages. |
| 18 | + """ |
| 19 | + |
| 20 | + async def publish_scope( |
| 21 | + self, |
| 22 | + call_next: Callable[..., Awaitable[Any]], |
| 23 | + msg: RabbitMessage, |
| 24 | + *args: tuple[Any, ...], |
| 25 | + **kwargs: dict[str, Any], |
| 26 | + ) -> CoroutineType: |
| 27 | + timestamp = UtilityService.get_timestamp() |
| 28 | + signature = UtilityService.generate_signature(queue["key"], timestamp) |
| 29 | + |
| 30 | + headers = {} |
| 31 | + |
| 32 | + headers["X-BROKER-SIGNATURE"] = signature |
| 33 | + headers["X-BROKER-TIMESTAMP"] = timestamp |
| 34 | + headers["X-BROKER-KEY"] = queue["key"] |
| 35 | + |
| 36 | + kwargs["headers"] = headers |
| 37 | + return await super().publish_scope(call_next, msg, *args, **kwargs) |
| 38 | + |
| 39 | + |
| 40 | +class SubscribeMiddleware(BaseMiddleware): |
| 41 | + async def consume_scope( |
| 42 | + self, call_next: Callable[[Any], Awaitable[Any]], msg: StreamMessage |
| 43 | + ) -> CoroutineType | None: |
| 44 | + logger = Logger(__name__) |
| 45 | + try: |
| 46 | + UtilityService.verify_signature( |
| 47 | + logger=logger, |
| 48 | + signature_data={ |
| 49 | + "signature": msg.headers["X-BROKER-SIGNATURE"], |
| 50 | + "timestamp": msg.headers["X-BROKER-TIMESTAMP"], |
| 51 | + "key": queue["key"], |
| 52 | + "ttl": queue["ttl"], |
| 53 | + "title": SIGNATURE_SOURCES["gateway"], |
| 54 | + }, |
| 55 | + ) |
| 56 | + |
| 57 | + return await super().consume_scope(call_next, msg) |
| 58 | + except KeyError as e: |
| 59 | + message = f"Missing required header: {e}" |
| 60 | + logger.error( |
| 61 | + { |
| 62 | + "activity_type": "Authenticate GatewaBroker Queue Request", |
| 63 | + "message": message, |
| 64 | + "metadata": {"headers": msg.headers}, |
| 65 | + } |
| 66 | + ) |
| 67 | + except Exception as e: |
| 68 | + queue_operation = msg.raw_message.routing_key |
| 69 | + message = f"`{queue_operation}` operation failed: {e}" |
| 70 | + logger.error( |
| 71 | + { |
| 72 | + "activity_type": "Authenticate GatewaBroker Queue Request", |
| 73 | + "message": message, |
| 74 | + "metadata": {"headers": msg.headers, "message": msg._decoded_body}, |
| 75 | + } |
| 76 | + ) |
0 commit comments