|
1 | 1 | import base64
|
2 |
| -from typing import Iterator, Optional |
| 2 | +import json |
| 3 | +import warnings |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Tuple |
| 6 | + |
| 7 | +from typing_extensions import Literal |
3 | 8 |
|
4 | 9 | from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
|
5 | 10 |
|
6 | 11 |
|
| 12 | +@dataclass(repr=False, order=False, frozen=True) |
| 13 | +class KinesisFirehoseDataTransformationRecordMetadata: |
| 14 | + """ |
| 15 | + Metadata in Firehose Data Transform Record. |
| 16 | +
|
| 17 | + Parameters |
| 18 | + ---------- |
| 19 | + partition_keys: Dict[str, str] |
| 20 | + A dict of partition keys/value in string format, e.g. `{"year":"2023","month":"09"}` |
| 21 | +
|
| 22 | + Documentation: |
| 23 | + -------------- |
| 24 | + - https://docs.aws.amazon.com/firehose/latest/dev/dynamic-partitioning.html |
| 25 | + """ |
| 26 | + |
| 27 | + partition_keys: Dict[str, str] = field(default_factory=lambda: {}) |
| 28 | + |
| 29 | + def asdict(self) -> Dict: |
| 30 | + if self.partition_keys is not None: |
| 31 | + return {"partitionKeys": self.partition_keys} |
| 32 | + return {} |
| 33 | + |
| 34 | + |
| 35 | +@dataclass(repr=False, order=False) |
| 36 | +class KinesisFirehoseDataTransformationRecord: |
| 37 | + """Record in Kinesis Data Firehose response object. |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + record_id: str |
| 42 | + uniquely identifies this record within the current batch |
| 43 | + result: Literal["Ok", "Dropped", "ProcessingFailed"] |
| 44 | + record data transformation status, whether it succeeded, should be dropped, or failed. |
| 45 | + data: str |
| 46 | + base64-encoded payload, by default empty string. |
| 47 | +
|
| 48 | + Use `data_from_text` or `data_from_json` methods to convert data if needed. |
| 49 | +
|
| 50 | + metadata: Optional[KinesisFirehoseDataTransformationRecordMetadata] |
| 51 | + Metadata associated with this record; can contain partition keys. |
| 52 | +
|
| 53 | + See: https://docs.aws.amazon.com/firehose/latest/dev/dynamic-partitioning.html |
| 54 | + json_serializer: Callable |
| 55 | + function to serialize `obj` to a JSON formatted `str`, by default json.dumps |
| 56 | + json_deserializer: Callable |
| 57 | + function to deserialize `str`, `bytes`, bytearray` containing a JSON document to a Python `obj`, |
| 58 | + by default json.loads |
| 59 | +
|
| 60 | + Documentation: |
| 61 | + -------------- |
| 62 | + - https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html |
| 63 | + """ |
| 64 | + |
| 65 | + _valid_result_types: ClassVar[Tuple[str, str, str]] = ("Ok", "Dropped", "ProcessingFailed") |
| 66 | + |
| 67 | + record_id: str |
| 68 | + result: Literal["Ok", "Dropped", "ProcessingFailed"] = "Ok" |
| 69 | + data: str = "" |
| 70 | + metadata: Optional[KinesisFirehoseDataTransformationRecordMetadata] = None |
| 71 | + json_serializer: Callable = json.dumps |
| 72 | + json_deserializer: Callable = json.loads |
| 73 | + _json_data: Optional[Any] = None |
| 74 | + |
| 75 | + def asdict(self) -> Dict: |
| 76 | + if self.result not in self._valid_result_types: |
| 77 | + warnings.warn( |
| 78 | + stacklevel=1, |
| 79 | + message=f'The result "{self.result}" is not valid, Choose from "Ok", "Dropped", "ProcessingFailed"', |
| 80 | + ) |
| 81 | + |
| 82 | + record: Dict[str, Any] = { |
| 83 | + "recordId": self.record_id, |
| 84 | + "result": self.result, |
| 85 | + "data": self.data, |
| 86 | + } |
| 87 | + if self.metadata: |
| 88 | + record["metadata"] = self.metadata.asdict() |
| 89 | + return record |
| 90 | + |
| 91 | + @property |
| 92 | + def data_as_bytes(self) -> bytes: |
| 93 | + """Decoded base64-encoded data as bytes""" |
| 94 | + if not self.data: |
| 95 | + return b"" |
| 96 | + return base64.b64decode(self.data) |
| 97 | + |
| 98 | + @property |
| 99 | + def data_as_text(self) -> str: |
| 100 | + """Decoded base64-encoded data as text""" |
| 101 | + if not self.data: |
| 102 | + return "" |
| 103 | + return self.data_as_bytes.decode("utf-8") |
| 104 | + |
| 105 | + @property |
| 106 | + def data_as_json(self) -> Dict: |
| 107 | + """Decoded base64-encoded data loaded to json""" |
| 108 | + if not self.data: |
| 109 | + return {} |
| 110 | + if self._json_data is None: |
| 111 | + self._json_data = self.json_deserializer(self.data_as_text) |
| 112 | + return self._json_data |
| 113 | + |
| 114 | + |
| 115 | +@dataclass(repr=False, order=False) |
| 116 | +class KinesisFirehoseDataTransformationResponse: |
| 117 | + """Kinesis Data Firehose response object |
| 118 | +
|
| 119 | + Documentation: |
| 120 | + -------------- |
| 121 | + - https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html |
| 122 | +
|
| 123 | + Parameters |
| 124 | + ---------- |
| 125 | + records : List[KinesisFirehoseResponseRecord] |
| 126 | + records of Kinesis Data Firehose response object, |
| 127 | + optional parameter at start. can be added later using `add_record` function. |
| 128 | +
|
| 129 | + Examples |
| 130 | + -------- |
| 131 | +
|
| 132 | + **Transforming data records** |
| 133 | +
|
| 134 | + ```python |
| 135 | + from aws_lambda_powertools.utilities.data_classes import ( |
| 136 | + KinesisFirehoseDataTransformationRecord, |
| 137 | + KinesisFirehoseDataTransformationResponse, |
| 138 | + KinesisFirehoseEvent, |
| 139 | + ) |
| 140 | + from aws_lambda_powertools.utilities.serialization import base64_from_json |
| 141 | + from aws_lambda_powertools.utilities.typing import LambdaContext |
| 142 | +
|
| 143 | +
|
| 144 | + def lambda_handler(event: dict, context: LambdaContext): |
| 145 | + firehose_event = KinesisFirehoseEvent(event) |
| 146 | + result = KinesisFirehoseDataTransformationResponse() |
| 147 | +
|
| 148 | + for record in firehose_event.records: |
| 149 | + payload = record.data_as_text # base64 decoded data as str |
| 150 | +
|
| 151 | + ## generate data to return |
| 152 | + transformed_data = {"tool_used": "powertools_dataclass", "original_payload": payload} |
| 153 | + processed_record = KinesisFirehoseDataTransformationRecord( |
| 154 | + record_id=record.record_id, |
| 155 | + data=base64_from_json(transformed_data), |
| 156 | + ) |
| 157 | +
|
| 158 | + result.add_record(processed_record) |
| 159 | +
|
| 160 | + # return transformed records |
| 161 | + return result.asdict() |
| 162 | + ``` |
| 163 | + """ |
| 164 | + |
| 165 | + records: List[KinesisFirehoseDataTransformationRecord] = field(default_factory=list) |
| 166 | + |
| 167 | + def add_record(self, record: KinesisFirehoseDataTransformationRecord): |
| 168 | + self.records.append(record) |
| 169 | + |
| 170 | + def asdict(self) -> Dict: |
| 171 | + if not self.records: |
| 172 | + raise ValueError("Amazon Kinesis Data Firehose doesn't accept empty response") |
| 173 | + |
| 174 | + return {"records": [record.asdict() for record in self.records]} |
| 175 | + |
| 176 | + |
7 | 177 | class KinesisFirehoseRecordMetadata(DictWrapper):
|
8 | 178 | @property
|
9 | 179 | def _metadata(self) -> dict:
|
@@ -77,6 +247,32 @@ def data_as_json(self) -> dict:
|
77 | 247 | self._json_data = self._json_deserializer(self.data_as_text)
|
78 | 248 | return self._json_data
|
79 | 249 |
|
| 250 | + def build_data_transformation_response( |
| 251 | + self, |
| 252 | + result: Literal["Ok", "Dropped", "ProcessingFailed"] = "Ok", |
| 253 | + data: str = "", |
| 254 | + metadata: Optional[KinesisFirehoseDataTransformationRecordMetadata] = None, |
| 255 | + ) -> KinesisFirehoseDataTransformationRecord: |
| 256 | + """Create a KinesisFirehoseResponseRecord directly using the record_id and given values |
| 257 | +
|
| 258 | + Parameters |
| 259 | + ---------- |
| 260 | + result : Literal["Ok", "Dropped", "ProcessingFailed"] |
| 261 | + processing result, supported value: Ok, Dropped, ProcessingFailed |
| 262 | + data : str, optional |
| 263 | + data blob, base64-encoded, optional at init. Allows pass in base64-encoded data directly or |
| 264 | + use either function like `data_from_text`, `data_from_json` to populate data |
| 265 | + metadata: KinesisFirehoseResponseRecordMetadata, optional |
| 266 | + Metadata associated with this record; can contain partition keys |
| 267 | + - https://docs.aws.amazon.com/firehose/latest/dev/dynamic-partitioning.html |
| 268 | + """ |
| 269 | + return KinesisFirehoseDataTransformationRecord( |
| 270 | + record_id=self.record_id, |
| 271 | + result=result, |
| 272 | + data=data, |
| 273 | + metadata=metadata, |
| 274 | + ) |
| 275 | + |
80 | 276 |
|
81 | 277 | class KinesisFirehoseEvent(DictWrapper):
|
82 | 278 | """Kinesis Data Firehose event
|
|
0 commit comments