-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
349 lines (277 loc) · 12.5 KB
/
Copy pathhandler.py
File metadata and controls
349 lines (277 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import json
import logging
from collections.abc import Callable
from dataclasses import dataclass
from typing import Generic, Literal, Optional, TypeAlias, TypeVar, cast
from aibs_informatics_aws_utils.s3 import download_to_json_object, upload_json
from aibs_informatics_core.executors.base import BaseExecutor
from aibs_informatics_core.models.aws.s3 import S3Path
from aibs_informatics_core.models.base import ModelProtocol
from aibs_informatics_core.utils.json import JSON
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
SqsFifoPartialProcessor,
batch_processor,
process_partial_response,
)
from aws_lambda_powertools.utilities.batch.types import PartialItemFailureResponse
from aws_lambda_powertools.utilities.data_classes.dynamo_db_stream_event import DynamoDBRecord
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
from aibs_informatics_aws_lambda.common.base import HandlerMixins
from aibs_informatics_aws_lambda.common.logging import LoggingMixins
from aibs_informatics_aws_lambda.common.metrics import MetricsMixins
LambdaEvent: TypeAlias = JSON
LambdaHandlerType = Callable[[LambdaEvent, LambdaContext], Optional[JSON]]
logger = logging.getLogger(__name__)
REQUEST = TypeVar("REQUEST", bound=ModelProtocol)
RESPONSE = TypeVar("RESPONSE", bound=ModelProtocol)
@dataclass # type: ignore[misc] # mypy #5374
class LambdaHandler(
LoggingMixins,
MetricsMixins,
HandlerMixins,
BaseExecutor[REQUEST, RESPONSE],
Generic[REQUEST, RESPONSE],
):
"""Base class for creating strongly-typed AWS Lambda handlers.
Provides a foundation for Lambda functions with built-in support for:
- Request/response serialization and deserialization
- Structured logging via AWS Lambda Powertools
- CloudWatch metrics collection
- SQS batch processing
- DynamoDB Streams processing
Inherit from the LambdaHandler class to create a custom strongly typed lambda handler
that expects a REQUEST object and returns a RESPONSE object that follow the `ModelProtocol`.
Type Parameters:
REQUEST: The request model type (must implement ModelProtocol).
RESPONSE: The response model type (must implement ModelProtocol).
Example:
```python
class MyRequest(PydanticBaseModel):
name: str
class MyResponse(PydanticBaseModel):
message: str
class MyHandler(LambdaHandler[MyRequest, MyResponse]):
def handle(self, request: MyRequest) -> MyResponse:
return MyResponse(message=f"Hello, {request.name}!")
handler = MyHandler.get_handler()
```
"""
def __post_init__(self):
self.context = LambdaContext()
super().__post_init__()
@classmethod
def load_input__remote(cls, remote_path: S3Path) -> JSON:
"""Load input data from a remote S3 location.
Args:
remote_path (S3Path): The S3 URI to download the input from.
Returns:
The JSON content from the S3 object.
"""
return download_to_json_object(remote_path)
@classmethod
def write_output__remote(cls, output: JSON, remote_path: S3Path) -> None:
"""Write output data to a remote S3 location.
Args:
output (JSON): The JSON content to upload.
remote_path (S3Path): The S3 URI to upload the output to.
"""
return upload_json(output, remote_path)
# --------------------------------------------------------------------
# Handler provider methods
# --------------------------------------------------------------------
@classmethod
def get_handler(cls, *args, **kwargs) -> LambdaHandlerType:
"""Create a Lambda handler function for this handler class.
Creates a wrapped handler function that:
- Injects Lambda context for logging
- Instantiates the handler class
- Deserializes the incoming event
- Invokes the handle method
- Serializes and returns the response
Args:
*args: Positional arguments passed to the handler constructor.
**kwargs: Keyword arguments passed to the handler constructor.
Returns:
A callable Lambda handler function suitable for AWS Lambda.
Example:
```python
# In your Lambda module
handler = MyHandler.get_handler()
```
"""
logger = cls.get_logger(service=cls.service_name(), add_to_root=False)
@logger.inject_lambda_context(log_event=True)
def handler(event: LambdaEvent, context: LambdaContext) -> JSON | None:
lambda_handler = cls(*args, **kwargs) # type: ignore[call-arg]
logger.info(f"Instantiated {lambda_handler}.")
lambda_handler.log = logger
lambda_handler.context = context
lambda_handler.add_logger_to_root()
lambda_handler.log.info(f"Deserializing event: {event}")
request = lambda_handler.deserialize_request(event)
lambda_handler.log.info("Event successfully deserialized. Calling handler...")
response = lambda_handler.handle(request=request)
lambda_handler.log.info(
f"Handler completed and returned following response: {response}"
)
if response:
lambda_handler.log.info("Serializing response")
return lambda_handler.serialize_response(response)
return None
handler._handler_class = cls # type: ignore[attr-defined]
return handler
@classmethod
def should_process_sqs_record(cls, record: SQSRecord) -> bool:
"""Filter for whether to handle an SQS Record.
This is invoked prior to deserializing and handling that SQS message.
Args:
record (SQSRecord): An SQS record
Returns:
True if handler should process request
"""
return True
@classmethod
def deserialize_sqs_record(cls, record: SQSRecord) -> REQUEST:
"""Deserialize an SQS Record into the Request object of this handler
By default, the "body" of the SQS record is deserialized using
the class default `deserialize_request` method.
Args:
record (SQSRecord): An SQS record
Returns:
The expected Request object for this handler class
"""
return cls.deserialize_request(json.loads(record["body"]))
@classmethod
def get_sqs_batch_handler(
cls, *args, queue_type: Literal["standard", "fifo"] = "standard", **kwargs
) -> LambdaHandlerType:
"""Create a handler for processing SQS batch records.
Creates a Lambda handler that processes batches of SQS messages
with partial failure support, allowing successful messages to be
acknowledged even if some fail.
See Also:
https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/
Args:
*args: Positional arguments passed to the handler constructor.
queue_type (Literal["standard", "fifo"]): The SQS queue type - "standard" or "fifo".
Defaults to "standard".
**kwargs: Keyword arguments passed to the handler constructor.
Returns:
A callable Lambda handler function for SQS batch processing.
Raises:
RuntimeError: If an invalid queue_type is provided.
Example:
```python
handler = MyHandler.get_sqs_batch_handler(queue_type="fifo")
```
"""
if queue_type == "standard":
processor = BatchProcessor(event_type=EventType.SQS)
elif queue_type == "fifo":
processor = SqsFifoPartialProcessor()
else:
raise RuntimeError(
"An invalid SQS queue_type ({queue_type}) was provided to the "
"get_sqs_batch_handler() method. Valid values include: "
"[standard, fifo]"
)
logger = cls.get_logger(cls.service_name())
# Create a record handler for each record in batch.
def record_handler(record: SQSRecord) -> JSON | None:
if not cls.should_process_sqs_record(record):
logger.info(f"SQS record {record} elected not to be processed.")
return None
lambda_handler = cls(*args, **kwargs)
lambda_handler.log = logger
lambda_handler.add_logger_to_root()
request = lambda_handler.deserialize_sqs_record(record)
response = lambda_handler.handle(request=request)
if response:
lambda_handler.log.info("Sending Response")
return lambda_handler.serialize_response(response)
lambda_handler.log.info("Not sending Response")
return None
# Now create top-level handler
@logger.inject_lambda_context(log_event=True)
def handler(event: dict, context: LambdaContext) -> PartialItemFailureResponse:
return process_partial_response(
event=event,
record_handler=record_handler,
processor=processor,
context=context,
)
return cast(LambdaHandlerType, handler)
@classmethod
def should_process_dynamodb_record(cls, record: DynamoDBRecord) -> bool:
"""Filter for whether to handle an DynamoDB record
This allows to filter all stream events based on:
1. The type of event (entry modification, insertion, deletion...)
2. The content of the affected record.
Args:
record (DynamoDBRecord): A DynamoDB record generated from a DynamoDB Stream
Returns:
True if handler should process request
"""
return True
@classmethod
def deserialize_dynamodb_record(cls, record: DynamoDBRecord) -> REQUEST:
"""Parse a DynamoDB record into a request object.
This should be implemented if expected to process a dynamo DB record
Args:
record (DynamoDBRecord): A DynamoDB record generated from a DynamoDB Stream
Returns:
Expected Request object
"""
raise NotImplementedError( # pragma: no cover
"You must implement this method if processing dynamoDB stream events"
)
@classmethod
def get_dynamodb_stream_handler(cls, *args, **kwargs) -> LambdaHandlerType:
"""Create a handler for processing DynamoDB Stream events.
Creates a Lambda handler that processes batches of DynamoDB Stream
records with partial failure support.
See Also:
https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/
Args:
*args: Positional arguments passed to the handler constructor.
**kwargs: Keyword arguments passed to the handler constructor.
Returns:
A callable Lambda handler function for DynamoDB Streams.
Example:
```python
handler = MyHandler.get_dynamodb_stream_handler()
```
"""
processor = BatchProcessor(event_type=EventType.DynamoDBStreams)
logger = cls.get_logger(cls.service_name())
# Create a record handler for each record in batch.
def record_handler(record: DynamoDBRecord) -> JSON | None:
if not cls.should_process_dynamodb_record(record):
logger.info(f"DynamoDB record {record} will not be processed.")
return None
lambda_handler = cls(*args, **kwargs) # type: ignore[call-arg]
lambda_handler.log = logger
lambda_handler.add_logger_to_root()
request = lambda_handler.deserialize_dynamodb_record(record)
response = lambda_handler.handle(request=request)
if response:
lambda_handler.log.info("Sending Response")
return lambda_handler.serialize_response(response)
lambda_handler.log.info("Not sending Response")
return None
# Now create top-level handler
@logger.inject_lambda_context(log_event=True)
@batch_processor(record_handler=record_handler, processor=processor) # type: ignore
def handler(event, context: LambdaContext):
return processor.response()
return handler # type: ignore
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}("
f"request: {self.get_request_cls()}, "
f"response: {self.get_response_cls()}"
")"
)