|
| 1 | +from datetime import datetime |
| 2 | +from typing import Dict, List, Type, Union |
| 3 | + |
| 4 | +from pydantic import BaseModel, validator |
| 5 | + |
| 6 | +from aws_lambda_powertools.shared.functions import base64_decode, bytes_to_string |
| 7 | +from aws_lambda_powertools.utilities.parser.types import Literal |
| 8 | + |
| 9 | +SERVERS_DELIMITER = "," |
| 10 | + |
| 11 | + |
| 12 | +class KafkaRecordModel(BaseModel): |
| 13 | + topic: str |
| 14 | + partition: int |
| 15 | + offset: int |
| 16 | + timestamp: datetime |
| 17 | + timestampType: str |
| 18 | + key: bytes |
| 19 | + value: Union[str, Type[BaseModel]] |
| 20 | + headers: List[Dict[str, bytes]] |
| 21 | + |
| 22 | + # validators |
| 23 | + _decode_key = validator("key", allow_reuse=True)(base64_decode) |
| 24 | + |
| 25 | + @validator("value", pre=True, allow_reuse=True) |
| 26 | + def data_base64_decode(cls, value): |
| 27 | + as_bytes = base64_decode(value) |
| 28 | + return bytes_to_string(as_bytes) |
| 29 | + |
| 30 | + @validator("headers", pre=True, allow_reuse=True) |
| 31 | + def decode_headers_list(cls, value): |
| 32 | + for header in value: |
| 33 | + for key, values in header.items(): |
| 34 | + header[key] = bytes(values) |
| 35 | + return value |
| 36 | + |
| 37 | + |
| 38 | +class KafkaBaseEventModel(BaseModel): |
| 39 | + bootstrapServers: List[str] |
| 40 | + records: Dict[str, List[KafkaRecordModel]] |
| 41 | + |
| 42 | + @validator("bootstrapServers", pre=True, allow_reuse=True) |
| 43 | + def split_servers(cls, value): |
| 44 | + return None if not value else value.split(SERVERS_DELIMITER) |
| 45 | + |
| 46 | + |
| 47 | +class KafkaSelfManagedEventModel(KafkaBaseEventModel): |
| 48 | + """Self-managed Apache Kafka event trigger |
| 49 | + Documentation: |
| 50 | + -------------- |
| 51 | + - https://docs.aws.amazon.com/lambda/latest/dg/with-kafka.html |
| 52 | + """ |
| 53 | + |
| 54 | + eventSource: Literal["aws:SelfManagedKafka"] |
| 55 | + |
| 56 | + |
| 57 | +class KafkaMskEventModel(KafkaBaseEventModel): |
| 58 | + """Fully-managed AWS Apache Kafka event trigger |
| 59 | + Documentation: |
| 60 | + -------------- |
| 61 | + - https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html |
| 62 | + """ |
| 63 | + |
| 64 | + eventSource: Literal["aws:kafka"] |
| 65 | + eventSourceArn: str |
0 commit comments