-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathlocal_lambda_http_service.py
More file actions
481 lines (399 loc) · 19.1 KB
/
local_lambda_http_service.py
File metadata and controls
481 lines (399 loc) · 19.1 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""Local Lambda Service that handles a subset of lambda APIs: Invoke, GetDurableExecution, GetDurableExecutionHistory"""
import io
import json
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from typing import Dict, Optional, Tuple
from urllib.parse import unquote
from flask import Flask, request
from werkzeug.routing import BaseConverter
from samcli.commands.local.cli_common.durable_context import DurableContext
from samcli.commands.local.lib.exceptions import (
InvalidIntermediateImageError,
TenantIdValidationError,
UnsupportedInlineCodeError,
)
from samcli.lib.providers.provider import Function
from samcli.lib.utils.invocation_type import EVENT
from samcli.lib.utils.name_utils import InvalidFunctionNameException, normalize_sam_function_identifier
from samcli.lib.utils.stream_writer import StreamWriter
from samcli.local.docker.exceptions import DockerContainerCreationFailedException
from samcli.local.lambdafn.exceptions import DurableExecutionNotFound, FunctionNotFound, UnsupportedInvocationType
from samcli.local.services.base_local_service import BaseLocalService, LambdaOutputParser
from .lambda_error_responses import LambdaErrorResponses
LOG = logging.getLogger(__name__)
class DateTimeEncoder(json.JSONEncoder):
"""Custom JSON encoder that handles datetime objects"""
def default(self, obj):
if isinstance(obj, datetime):
return obj.timestamp()
return super().default(obj)
class FunctionNamePathConverter(BaseConverter):
regex = ".+"
weight = 300
part_isolating = False
def to_python(self, value):
return value
def to_url(self, value):
return value
class LocalLambdaHttpService(BaseLocalService):
INVOKE_ENDPOINT = "/2015-03-31/functions/<function_path:function_name>/invocations"
def __init__(self, lambda_runner, port, host, stderr=None, ssl_context=None):
"""
Creates a Local Lambda Service that handles both regular invocations and durable functions
Parameters
----------
lambda_runner samcli.commands.local.lib.local_lambda.LocalLambdaRunner
The Lambda runner class capable of invoking the function
port int
Optional. port for the service to start listening on
host str
Optional. host to start the service on
ssl_context : (str, str)
Optional. tuple(str, str) indicating the cert and key files to use to start in https mode
Defaults to None
stderr io.BaseIO
Optional stream where the stderr from Docker container should be written to
"""
super().__init__(lambda_runner.is_debugging(), port=port, host=host, ssl_context=ssl_context)
self.lambda_runner = lambda_runner
self.stderr = stderr
self.executor = ThreadPoolExecutor()
def create(self):
"""
Creates a Flask Application that can be started.
"""
self._app = Flask(__name__)
# add converter to support nested stack function path
self._app.url_map.converters["function_path"] = FunctionNamePathConverter
# Lambda invocation endpoint
self._app.add_url_rule(
self.INVOKE_ENDPOINT,
endpoint=self.INVOKE_ENDPOINT,
view_func=self._invoke_request_handler,
methods=["POST"],
provide_automatic_options=False,
)
# Durable functions endpoints
self._app.add_url_rule(
"/2025-12-01/durable-executions/<durable_execution_arn>",
endpoint="get_durable_execution",
view_func=self._get_durable_execution_handler,
methods=["GET"],
)
self._app.add_url_rule(
"/2025-12-01/durable-executions/<durable_execution_arn>/history",
endpoint="get_durable_execution_history",
view_func=self._get_durable_execution_history_handler,
methods=["GET"],
)
self._app.add_url_rule(
"/2025-12-01/durable-executions/<durable_execution_arn>/stop",
endpoint="stop_durable_execution",
view_func=self._stop_durable_execution_handler,
methods=["POST"],
)
# Callback endpoints
self._app.add_url_rule(
"/2025-12-01/durable-execution-callbacks/<callback_id>/succeed",
endpoint="send_callback_success",
view_func=self._send_callback_success_handler,
methods=["POST"],
)
self._app.add_url_rule(
"/2025-12-01/durable-execution-callbacks/<callback_id>/fail",
endpoint="send_callback_failure",
view_func=self._send_callback_failure_handler,
methods=["POST"],
)
self._app.add_url_rule(
"/2025-12-01/durable-execution-callbacks/<callback_id>/heartbeat",
endpoint="send_callback_heartbeat",
view_func=self._send_callback_heartbeat_handler,
methods=["POST"],
)
# setup request validation before Flask calls the view_func
self._app.before_request(LocalLambdaHttpService.validate_request)
self._construct_error_handling()
@staticmethod
def validate_request():
"""
Validates incoming requests based on the endpoint
For invoke endpoints, performs specific validation checks.
Other endpoints pass through without validation.
"""
if request.endpoint == LocalLambdaHttpService.INVOKE_ENDPOINT:
return LocalLambdaHttpService._validate_invoke_request(request)
return None
@staticmethod
def _validate_invoke_request(flask_request):
"""
Validates the incoming invoke request specifically
The following are invalid for invoke requests:
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' header is not 'None'
5. 'X-Amz-Invocation-Type' header is not 'RequestResponse'
Args:
flask_request: The Flask request object to validate
Returns
-------
flask.Response
If the request is not valid a flask Response is returned
None:
If the request passes all validation
"""
request_data = flask_request.get_data()
if not request_data:
request_data = b"{}"
request_data = request_data.decode("utf-8")
try:
json.loads(request_data)
except ValueError as json_error:
LOG.debug("Request body was not json. Exception: %s", str(json_error))
return LambdaErrorResponses.invalid_request_content(
"Could not parse request body into json: No JSON object could be decoded"
)
if flask_request.args:
LOG.debug("Query parameters are in the request but not supported for invoke endpoint")
return LambdaErrorResponses.invalid_request_content("Query Parameters are not supported")
request_headers = flask_request.headers
log_type = request_headers.get("X-Amz-Log-Type", "None")
if log_type != "None":
LOG.debug("log-type: %s is not supported. None is only supported.", log_type)
return LambdaErrorResponses.not_implemented_locally(
"log-type: {} is not supported. None is only supported.".format(log_type)
)
return None
def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
self._app.register_error_handler(500, LambdaErrorResponses.generic_service_exception)
self._app.register_error_handler(404, LambdaErrorResponses.generic_path_not_found)
self._app.register_error_handler(405, LambdaErrorResponses.generic_method_not_allowed)
def _invoke_request_handler(self, function_name):
"""
Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming
request and invoking the Local Lambda Function
Parameters
----------
function_name str
Name or ARN of the function to invoke
Returns
-------
A Flask Response response object as if it was returned from Lambda
"""
flask_request = request
request_data = flask_request.get_data()
if not request_data:
request_data = b"{}"
request_data = request_data.decode("utf-8")
# Get invocation type from headers
invocation_type = flask_request.headers.get("X-Amz-Invocation-Type", "RequestResponse")
# Extract tenant-id from request header
tenant_id = flask_request.headers.get("X-Amz-Tenant-Id")
# Extract durable execution name from headers
durable_execution_name = flask_request.headers.get("X-Amz-Durable-Execution-Name")
headers = {"Content-Type": "application/json"}
try:
function = self.lambda_runner.get_function(function_name, tenant_id)
except (InvalidFunctionNameException, TenantIdValidationError, InvalidIntermediateImageError) as e:
LOG.error("Validation error: %s", str(e))
return LambdaErrorResponses.validation_exception(str(e))
except FunctionNotFound:
normalized_function_name = normalize_sam_function_identifier(function_name)
LOG.debug("%s was not found to invoke.", normalized_function_name)
return LambdaErrorResponses.resource_not_found(normalized_function_name)
except UnsupportedInlineCodeError:
return LambdaErrorResponses.not_implemented_locally(
"Inline code is not supported for sam local commands. Please write your code in a separate file."
)
arguments = {
"function_name": function_name,
"request_data": request_data,
"invocation_type": invocation_type,
"durable_execution_name": durable_execution_name,
"tenant_id": tenant_id,
"function": function,
}
is_durable = function is not None and function.durable_config is not None
# Non-durable EVENT invocations run fully async
if invocation_type == EVENT and not is_durable:
self.executor.submit(self._invoke_async_lambda, **arguments)
return self.service_response("", headers, 202)
try:
invoke_headers, stdout_stream_string, stdout_stream_bytes = self._invoke_lambda(**arguments)
except UnsupportedInvocationType as e:
LOG.warning(
"invocation-type: %s is not supported. Only Event and RequestResponse are supported.", invocation_type
)
return LambdaErrorResponses.not_implemented_locally(str(e))
except DockerContainerCreationFailedException as ex:
return LambdaErrorResponses.container_creation_failed(ex.message)
lambda_response, is_lambda_user_error_response = LambdaOutputParser.get_lambda_output(
stdout_stream_string, stdout_stream_bytes
)
# Prepare headers
if invoke_headers and isinstance(invoke_headers, dict):
headers.update(invoke_headers)
# Durable EVENT invocations return 202 with execution ARN header but empty body
if is_durable and invocation_type == EVENT:
return self.service_response("", headers, 202)
if is_lambda_user_error_response:
headers["x-amz-function-error"] = "Unhandled"
return self.service_response(lambda_response, headers, 200)
def _invoke_async_lambda(self, function_name: str, **kwargs) -> None:
"""
Wrapper for _invoke_lambda that runs in an async context (Event invocation type)
"""
try:
self._invoke_lambda(function_name=function_name, **kwargs)
except Exception as e:
LOG.error("Async invocation failed for function %s: %s", function_name, str(e), exc_info=True)
def _invoke_lambda(
self,
function_name: str,
request_data: str,
invocation_type: str,
durable_execution_name: Optional[str],
tenant_id: Optional[str],
function: Optional[Function],
) -> Tuple[Optional[Dict[str, str]], io.StringIO, io.BytesIO]:
"""
Invokes a Lambda function and returns the result
"""
stdout_stream_string = io.StringIO()
stdout_stream_bytes = io.BytesIO()
stdout_stream_writer = StreamWriter(stdout_stream_string, stdout_stream_bytes, auto_flush=True)
normalized_function_name = normalize_sam_function_identifier(function_name)
invoke_headers = self.lambda_runner.invoke(
normalized_function_name,
request_data,
invocation_type=invocation_type,
durable_execution_name=durable_execution_name,
tenant_id=tenant_id,
function=function,
stdout=stdout_stream_writer,
stderr=self.stderr,
)
return invoke_headers, stdout_stream_string, stdout_stream_bytes
def _get_durable_execution_handler(self, durable_execution_arn):
"""
Handler for GET /2025-12-01/durable-executions/{DurableExecutionArn}
"""
# URL-decode the ARN since it comes from the URL path
decoded_arn = unquote(durable_execution_arn)
LOG.debug("Calling GetDurableExecution: %s", decoded_arn)
try:
with DurableContext() as context:
response = context.client.get_durable_execution(decoded_arn)
return self.service_response(
json.dumps(response, cls=DateTimeEncoder), {"Content-Type": "application/json"}, 200
)
except DurableExecutionNotFound:
LOG.debug("Durable execution not found: %s", decoded_arn)
return LambdaErrorResponses.durable_execution_not_found(decoded_arn)
def _get_durable_execution_history_handler(self, durable_execution_arn):
"""
Handler for GET /2025-12-01/durable-executions/{DurableExecutionArn}/history
"""
# URL-decode the ARN since it comes from the URL path
decoded_arn = unquote(durable_execution_arn)
LOG.debug("Calling GetDurableExecutionHistory: %s", decoded_arn)
# Parse query parameters
include_execution_data = request.args.get("IncludeExecutionData", "false") == "true"
try:
with DurableContext() as context:
response = context.client.get_durable_execution_history(
decoded_arn, include_execution_data=include_execution_data
)
return self.service_response(
json.dumps(response, cls=DateTimeEncoder), {"Content-Type": "application/json"}, 200
)
except DurableExecutionNotFound:
LOG.debug("Durable execution not found: %s", decoded_arn)
return LambdaErrorResponses.durable_execution_not_found(decoded_arn)
def _stop_durable_execution_handler(self, durable_execution_arn):
"""
Handler for POST /2025-12-01/durable-executions/{DurableExecutionArn}/stop
"""
# URL-decode the ARN since it comes from the URL path
decoded_arn = unquote(durable_execution_arn)
LOG.debug("Calling StopDurableExecution: %s", decoded_arn)
try:
# Parse request body for error details - handle empty payloads gracefully
request_data = request.get_json(silent=True) or {}
error_dict = request_data.get("Error", {})
with DurableContext() as context:
response = context.client.stop_durable_execution(
durable_execution_arn=decoded_arn,
error_message=error_dict.get("ErrorMessage"),
error_type=error_dict.get("ErrorType"),
error_data=error_dict.get("ErrorData"),
stack_trace=error_dict.get("StackTrace"),
)
return self.service_response(
json.dumps(response, cls=DateTimeEncoder), {"Content-Type": "application/json"}, 200
)
except DurableExecutionNotFound:
LOG.debug("Durable execution not found: %s", decoded_arn)
return LambdaErrorResponses.durable_execution_not_found(decoded_arn)
except Exception as e:
LOG.error("Failed to stop durable execution: %s", str(e))
return LambdaErrorResponses.generic_service_exception()
def _send_callback_success_handler(self, callback_id):
"""
Handler for POST /2025-12-01/durable-execution-callbacks/{CallbackId}/succeed
"""
LOG.debug("Calling SendDurableExecutionCallbackSuccess: %s", callback_id)
try:
request_data = request.get_json(silent=True) or {}
with DurableContext() as context:
response = context.client.send_callback_success(
callback_id=callback_id,
result=request_data.get("Result"),
)
return self.service_response(
json.dumps(response, cls=DateTimeEncoder), {"Content-Type": "application/json"}, 200
)
except Exception as e:
LOG.error("Failed to send callback success: %s", str(e))
return LambdaErrorResponses.generic_service_exception()
def _send_callback_failure_handler(self, callback_id):
"""
Handler for POST /2025-12-01/durable-execution-callbacks/{CallbackId}/fail
"""
LOG.debug("Calling SendDurableExecutionCallbackFailure: %s", callback_id)
try:
request_data = request.get_json(silent=True) or {}
with DurableContext() as context:
response = context.client.send_callback_failure(
callback_id=callback_id,
error_data=request_data.get("ErrorData"),
stack_trace=request_data.get("StackTrace"),
error_type=request_data.get("ErrorType"),
error_message=request_data.get("ErrorMessage"),
)
return self.service_response(
json.dumps(response, cls=DateTimeEncoder), {"Content-Type": "application/json"}, 200
)
except Exception as e:
LOG.error("Failed to send callback failure: %s", str(e))
return LambdaErrorResponses.generic_service_exception()
def _send_callback_heartbeat_handler(self, callback_id):
"""
Handler for POST /2025-12-01/durable-execution-callbacks/{CallbackId}/heartbeat
"""
LOG.debug("Calling SendDurableExecutionCallbackHeartbeat: %s", callback_id)
try:
with DurableContext() as context:
response = context.client.send_callback_heartbeat(callback_id=callback_id)
return self.service_response(
json.dumps(response, cls=DateTimeEncoder), {"Content-Type": "application/json"}, 200
)
except Exception as e:
LOG.error("Failed to send callback heartbeat: %s", str(e))
return LambdaErrorResponses.generic_service_exception()