|
| 1 | +import logging |
| 2 | +from abc import ABC, abstractmethod |
| 3 | +from typing import Any, Callable, Dict |
| 4 | + |
| 5 | +from pydantic import BaseModel, ValidationError |
| 6 | + |
| 7 | +from aws_lambda_powertools.middleware_factory import lambda_handler_decorator |
| 8 | +from aws_lambda_powertools.validation.schemas.dynamodb import DynamoDBSchema |
| 9 | +from aws_lambda_powertools.validation.schemas.eventbridge import EventBridgeSchema |
| 10 | +from aws_lambda_powertools.validation.schemas.sqs import SqsSchema |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class Envelope(ABC): |
| 16 | + def _parse_user_dict_schema(self, user_event: Dict[str, Any], inbound_schema_model: BaseModel) -> Any: |
| 17 | + logger.debug("parsing user dictionary schema") |
| 18 | + try: |
| 19 | + return inbound_schema_model(**user_event) |
| 20 | + except (ValidationError, TypeError): |
| 21 | + logger.exception("Valdation exception while extracting user custom schema") |
| 22 | + raise |
| 23 | + |
| 24 | + def _parse_user_json_string_schema(self, user_event: str, inbound_schema_model: BaseModel) -> Any: |
| 25 | + logger.debug("parsing user dictionary schema") |
| 26 | + if inbound_schema_model == str: |
| 27 | + logger.debug("input is string, returning") |
| 28 | + return user_event |
| 29 | + logger.debug("trying to parse as json encoded string") |
| 30 | + try: |
| 31 | + return inbound_schema_model.parse_raw(user_event) |
| 32 | + except (ValidationError, TypeError): |
| 33 | + logger.exception("Validation exception while extracting user custom schema") |
| 34 | + raise |
| 35 | + |
| 36 | + @abstractmethod |
| 37 | + def parse(self, event: Dict[str, Any], inbound_schema_model: BaseModel) -> Any: |
| 38 | + return NotImplemented |
| 39 | + |
| 40 | + |
| 41 | +class UserEnvelope(Envelope): |
| 42 | + def parse(self, event: Dict[str, Any], inbound_schema_model: BaseModel) -> Any: |
| 43 | + try: |
| 44 | + return inbound_schema_model(**event) |
| 45 | + except (ValidationError, TypeError): |
| 46 | + logger.exception("Validation exception received from input user custom envelope event") |
| 47 | + raise |
| 48 | + |
| 49 | + |
| 50 | +class EventBridgeEnvelope(Envelope): |
| 51 | + def parse(self, event: Dict[str, Any], inbound_schema_model: BaseModel) -> Any: |
| 52 | + try: |
| 53 | + parsed_envelope = EventBridgeSchema(**event) |
| 54 | + except (ValidationError, TypeError): |
| 55 | + logger.exception("Validation exception received from input eventbridge event") |
| 56 | + raise |
| 57 | + return self._parse_user_dict_schema(parsed_envelope.detail, inbound_schema_model) |
| 58 | + |
| 59 | + |
| 60 | +class SqsEnvelope(Envelope): |
| 61 | + def parse(self, event: Dict[str, Any], inbound_schema_model: BaseModel) -> Any: |
| 62 | + try: |
| 63 | + parsed_envelope = SqsSchema(**event) |
| 64 | + except (ValidationError, TypeError): |
| 65 | + logger.exception("Validation exception received from input sqs event") |
| 66 | + raise |
| 67 | + output = [] |
| 68 | + for record in parsed_envelope.Records: |
| 69 | + parsed_msg = self._parse_user_json_string_schema(record.body, inbound_schema_model) |
| 70 | + output.append({"body": parsed_msg, "attributes": record.messageAttributes}) |
| 71 | + return output |
| 72 | + |
| 73 | + |
| 74 | +class DynamoDBEnvelope(Envelope): |
| 75 | + def parse(self, event: Dict[str, Any], inbound_schema_model: BaseModel) -> Any: |
| 76 | + try: |
| 77 | + parsed_envelope = DynamoDBSchema(**event) |
| 78 | + except (ValidationError, TypeError): |
| 79 | + logger.exception("Validation exception received from input dynamodb stream event") |
| 80 | + raise |
| 81 | + output = [] |
| 82 | + for record in parsed_envelope.Records: |
| 83 | + parsed_new_image = ( |
| 84 | + {} |
| 85 | + if not record.dynamodb.NewImage |
| 86 | + else self._parse_user_dict_schema(record.dynamodb.NewImage, inbound_schema_model) |
| 87 | + ) # noqa: E501 |
| 88 | + parsed_old_image = ( |
| 89 | + {} |
| 90 | + if not record.dynamodb.OldImage |
| 91 | + else self._parse_user_dict_schema(record.dynamodb.OldImage, inbound_schema_model) |
| 92 | + ) # noqa: E501 |
| 93 | + output.append({"new": parsed_new_image, "old": parsed_old_image}) |
| 94 | + return output |
| 95 | + |
| 96 | + |
| 97 | +@lambda_handler_decorator |
| 98 | +def validator( |
| 99 | + handler: Callable[[Dict, Any], Any], |
| 100 | + event: Dict[str, Any], |
| 101 | + context: Dict[str, Any], |
| 102 | + inbound_schema_model: BaseModel, |
| 103 | + outbound_schema_model: BaseModel, |
| 104 | + envelope: Envelope, |
| 105 | +) -> Any: |
| 106 | + """Decorator to create validation for lambda handlers events - both inbound and outbound |
| 107 | +
|
| 108 | + As Lambda follows (event, context) signature we can remove some of the boilerplate |
| 109 | + and also capture any exception any Lambda function throws or its response as metadata |
| 110 | +
|
| 111 | + Example |
| 112 | + ------- |
| 113 | + **Lambda function using validation decorator** |
| 114 | +
|
| 115 | + @validator(inbound=inbound_schema_model, outbound=outbound_schema_model) |
| 116 | + def handler(parsed_event_model, context): |
| 117 | + ... |
| 118 | +
|
| 119 | + Parameters |
| 120 | + ---------- |
| 121 | + todo add |
| 122 | +
|
| 123 | + Raises |
| 124 | + ------ |
| 125 | + err |
| 126 | + TypeError or pydantic.ValidationError or any exception raised by the lambda handler itself |
| 127 | + """ |
| 128 | + lambda_handler_name = handler.__name__ |
| 129 | + logger.debug("Validating inbound schema") |
| 130 | + parsed_event_model = envelope.parse(event, inbound_schema_model) |
| 131 | + try: |
| 132 | + logger.debug(f"Calling handler {lambda_handler_name}") |
| 133 | + response = handler({"orig": event, "custom": parsed_event_model}, context) |
| 134 | + logger.debug("Received lambda handler response successfully") |
| 135 | + logger.debug(response) |
| 136 | + except Exception: |
| 137 | + logger.exception(f"Exception received from {lambda_handler_name}") |
| 138 | + raise |
| 139 | + |
| 140 | + try: |
| 141 | + logger.debug("Validating outbound response schema") |
| 142 | + outbound_schema_model(**response) |
| 143 | + except (ValidationError, TypeError): |
| 144 | + logger.exception(f"Validation exception received from {lambda_handler_name} response event") |
| 145 | + raise |
| 146 | + return response |
0 commit comments