|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from functools import cached_property |
| 5 | +from typing import TYPE_CHECKING, Any |
| 6 | + |
| 7 | +from aws_lambda_powertools.utilities.data_classes.common import CaseInsensitiveDict |
| 8 | +from aws_lambda_powertools.utilities.data_classes.kafka_event import KafkaEventBase, KafkaEventRecordBase |
| 9 | +from aws_lambda_powertools.utilities.kafka.deserializer.deserializer import get_deserializer |
| 10 | +from aws_lambda_powertools.utilities.kafka.serialization.serialization import serialize_to_output_type |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from collections.abc import Iterator |
| 14 | + |
| 15 | + from aws_lambda_powertools.utilities.kafka.schema_config import SchemaConfig |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class ConsumerRecordRecords(KafkaEventRecordBase): |
| 21 | + """ |
| 22 | + A Kafka Consumer Record |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, data: dict[str, Any], schema_config: SchemaConfig | None = None): |
| 26 | + super().__init__(data) |
| 27 | + self.schema_config = schema_config |
| 28 | + |
| 29 | + @cached_property |
| 30 | + def key(self) -> Any: |
| 31 | + key = self.get("key") |
| 32 | + |
| 33 | + # Return None if key doesn't exist |
| 34 | + if not key: |
| 35 | + return None |
| 36 | + |
| 37 | + logger.debug("Deserializing key field") |
| 38 | + |
| 39 | + # Determine schema type and schema string |
| 40 | + schema_type = None |
| 41 | + schema_value = None |
| 42 | + output_serializer = None |
| 43 | + |
| 44 | + if self.schema_config and self.schema_config.key_schema_type: |
| 45 | + schema_type = self.schema_config.key_schema_type |
| 46 | + schema_value = self.schema_config.key_schema |
| 47 | + output_serializer = self.schema_config.key_output_serializer |
| 48 | + |
| 49 | + # Always use get_deserializer if None it will default to DEFAULT |
| 50 | + deserializer = get_deserializer( |
| 51 | + schema_type=schema_type, |
| 52 | + schema_value=schema_value, |
| 53 | + field_metadata=self.key_schema_metadata, |
| 54 | + ) |
| 55 | + deserialized_value = deserializer.deserialize(key) |
| 56 | + |
| 57 | + # Apply output serializer if specified |
| 58 | + if output_serializer: |
| 59 | + return serialize_to_output_type(deserialized_value, output_serializer) |
| 60 | + |
| 61 | + return deserialized_value |
| 62 | + |
| 63 | + @cached_property |
| 64 | + def value(self) -> Any: |
| 65 | + value = self["value"] |
| 66 | + |
| 67 | + # Determine schema type and schema string |
| 68 | + schema_type = None |
| 69 | + schema_value = None |
| 70 | + output_serializer = None |
| 71 | + |
| 72 | + logger.debug("Deserializing value field") |
| 73 | + |
| 74 | + if self.schema_config and self.schema_config.value_schema_type: |
| 75 | + schema_type = self.schema_config.value_schema_type |
| 76 | + schema_value = self.schema_config.value_schema |
| 77 | + output_serializer = self.schema_config.value_output_serializer |
| 78 | + |
| 79 | + # Always use get_deserializer if None it will default to DEFAULT |
| 80 | + deserializer = get_deserializer( |
| 81 | + schema_type=schema_type, |
| 82 | + schema_value=schema_value, |
| 83 | + field_metadata=self.value_schema_metadata, |
| 84 | + ) |
| 85 | + deserialized_value = deserializer.deserialize(value) |
| 86 | + |
| 87 | + # Apply output serializer if specified |
| 88 | + if output_serializer: |
| 89 | + return serialize_to_output_type(deserialized_value, output_serializer) |
| 90 | + |
| 91 | + return deserialized_value |
| 92 | + |
| 93 | + @property |
| 94 | + def original_value(self) -> str: |
| 95 | + """The original (base64 encoded) Kafka record value.""" |
| 96 | + return self["value"] |
| 97 | + |
| 98 | + @property |
| 99 | + def original_key(self) -> str | None: |
| 100 | + """ |
| 101 | + The original (base64 encoded) Kafka record key. |
| 102 | +
|
| 103 | + This key is optional; if not provided, |
| 104 | + a round-robin algorithm will be used to determine |
| 105 | + the partition for the message. |
| 106 | + """ |
| 107 | + |
| 108 | + return self.get("key") |
| 109 | + |
| 110 | + @property |
| 111 | + def original_headers(self) -> list[dict[str, list[int]]]: |
| 112 | + """The raw Kafka record headers.""" |
| 113 | + return self["headers"] |
| 114 | + |
| 115 | + @cached_property |
| 116 | + def headers(self) -> dict[str, bytes]: |
| 117 | + """Decodes the headers as a single dictionary.""" |
| 118 | + return CaseInsensitiveDict((k, bytes(v)) for chunk in self.original_headers for k, v in chunk.items()) |
| 119 | + |
| 120 | + |
| 121 | +class ConsumerRecords(KafkaEventBase): |
| 122 | + """Self-managed or MSK Apache Kafka event trigger |
| 123 | + Documentation: |
| 124 | + -------------- |
| 125 | + - https://docs.aws.amazon.com/lambda/latest/dg/with-kafka.html |
| 126 | + - https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html |
| 127 | + """ |
| 128 | + |
| 129 | + def __init__(self, data: dict[str, Any], schema_config: SchemaConfig | None = None): |
| 130 | + super().__init__(data) |
| 131 | + self._records: Iterator[ConsumerRecordRecords] | None = None |
| 132 | + self.schema_config = schema_config |
| 133 | + |
| 134 | + @property |
| 135 | + def records(self) -> Iterator[ConsumerRecordRecords]: |
| 136 | + """The Kafka records.""" |
| 137 | + for chunk in self["records"].values(): |
| 138 | + for record in chunk: |
| 139 | + yield ConsumerRecordRecords(data=record, schema_config=self.schema_config) |
| 140 | + |
| 141 | + @property |
| 142 | + def record(self) -> ConsumerRecordRecords: |
| 143 | + """ |
| 144 | + Returns the next Kafka record using an iterator. |
| 145 | +
|
| 146 | + Returns |
| 147 | + ------- |
| 148 | + ConsumerRecordRecords |
| 149 | + The next Kafka record. |
| 150 | +
|
| 151 | + Raises |
| 152 | + ------ |
| 153 | + StopIteration |
| 154 | + If there are no more records available. |
| 155 | +
|
| 156 | + """ |
| 157 | + if self._records is None: |
| 158 | + self._records = self.records |
| 159 | + return next(self._records) |
0 commit comments