-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat: support for local Event invocation type #8590
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,14 +3,17 @@ | |
| 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 flask import Flask, Response, request | ||
| from werkzeug.routing import BaseConverter | ||
|
|
||
| from samcli.commands.local.cli_common.durable_context import DurableContext | ||
| from samcli.commands.local.lib.exceptions import TenantIdValidationError, UnsupportedInlineCodeError | ||
| 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 | ||
|
|
@@ -67,6 +70,7 @@ def __init__(self, lambda_runner, port, host, stderr=None, ssl_context=None): | |
| 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): | ||
| """ | ||
|
|
@@ -240,32 +244,36 @@ def _invoke_request_handler(self, function_name): | |
| # Extract durable execution name from headers | ||
| durable_execution_name = flask_request.headers.get("X-Amz-Durable-Execution-Name") | ||
|
|
||
| stdout_stream_string = io.StringIO() | ||
| stdout_stream_bytes = io.BytesIO() | ||
| stdout_stream_writer = StreamWriter(stdout_stream_string, stdout_stream_bytes, auto_flush=True) | ||
| arguments = { | ||
| "function_name": function_name, | ||
| "request_data": request_data, | ||
| "invocation_type": invocation_type, | ||
| "durable_execution_name": durable_execution_name, | ||
| "tenant_id": tenant_id, | ||
| } | ||
|
|
||
| headers = {"Content-Type": "application/json"} | ||
|
|
||
| if invocation_type == EVENT: | ||
| # Validate function exists before submitting async task | ||
| if validation_error := self._validate_function_for_invocation(function_name): | ||
| return validation_error | ||
|
|
||
| self.executor.submit(self._invoke_async_lambda, **arguments) | ||
| return self.service_response("", headers, 202) | ||
|
|
||
| try: | ||
| # Normalize function name from ARN if provided | ||
| 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, | ||
| stdout=stdout_stream_writer, | ||
| stderr=self.stderr, | ||
| ) | ||
| invoke_headers, stdout_stream_string, stdout_stream_bytes = self._invoke_lambda(**arguments) | ||
| except (InvalidFunctionNameException, TenantIdValidationError) as e: | ||
| LOG.error("Validation error: %s", str(e)) | ||
| return LambdaErrorResponses.validation_exception(str(e)) | ||
| except UnsupportedInvocationType as e: | ||
| LOG.warning("invocation-type: %s is not supported. RequestResponse is only supported.", invocation_type) | ||
| LOG.warning( | ||
| "invocation-type: %s is not supported. Event and RequestResponse are only supported.", invocation_type | ||
| ) | ||
| return LambdaErrorResponses.not_implemented_locally(str(e)) | ||
| except FunctionNotFound: | ||
| LOG.debug("%s was not found to invoke.", normalized_function_name) | ||
| return LambdaErrorResponses.resource_not_found(normalized_function_name) | ||
| return self._handle_function_not_found(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." | ||
|
|
@@ -278,20 +286,94 @@ def _invoke_request_handler(self, function_name): | |
| ) | ||
|
|
||
| # Prepare headers | ||
| headers = {"Content-Type": "application/json"} | ||
| if invoke_headers and isinstance(invoke_headers, dict): | ||
| headers.update(invoke_headers) | ||
|
|
||
| if is_lambda_user_error_response: | ||
| headers["x-amz-function-error"] = "Unhandled" | ||
| return self.service_response(lambda_response, headers, 200) | ||
|
|
||
| # For async invocations (Event type), return 202 | ||
| if invocation_type == "Event": | ||
| return self.service_response("", headers, 202) | ||
|
|
||
| return self.service_response(lambda_response, headers, 200) | ||
|
|
||
| def _validate_function_for_invocation(self, function_name: str) -> Optional[Response]: | ||
| """ | ||
| Validates that a function exists and can be invoked. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| function_name : str | ||
| Name or ARN of the function to validate | ||
|
|
||
| Returns | ||
| ------- | ||
| Flask.Response or None | ||
| Error response if validation fails, None if validation succeeds | ||
| """ | ||
| try: | ||
| self.lambda_runner.get_function(function_name) | ||
| return None | ||
| except FunctionNotFound: | ||
| return self._handle_function_not_found(function_name) | ||
| except InvalidFunctionNameException as e: | ||
| LOG.error("Validation error: %s", str(e)) | ||
| return LambdaErrorResponses.validation_exception(str(e)) | ||
|
|
||
| def _handle_function_not_found(self, function_name: str) -> Response: | ||
| """ | ||
| Handles FunctionNotFound exception by returning appropriate error response. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| function_name : str | ||
| Name or ARN of the function that was not found | ||
|
|
||
| Returns | ||
| ------- | ||
| Flask.Response | ||
| Error response for function not found | ||
| """ | ||
| 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) | ||
|
|
||
| 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], | ||
| ) -> 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) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we call the |
||
|
|
||
| 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, | ||
| 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} | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -13,6 +13,7 @@ | |||||||||
|
|
||||||||||
| from samcli.lib.telemetry.metric import capture_parameter | ||||||||||
| from samcli.lib.utils.file_observer import LambdaFunctionObserver | ||||||||||
| from samcli.lib.utils.invocation_type import EVENT, REQUEST_RESPONSE | ||||||||||
| from samcli.lib.utils.packagetype import ZIP | ||||||||||
| from samcli.local.docker.container import Container, ContainerContext | ||||||||||
| from samcli.local.docker.container_analyzer import ContainerAnalyzer | ||||||||||
|
|
@@ -305,9 +306,10 @@ def invoke( | |||||||||
| ) | ||||||||||
| else: | ||||||||||
| # Only RequestResponse supported for regular Lambda functions | ||||||||||
| if invocation_type != "RequestResponse": | ||||||||||
| if invocation_type not in [EVENT, REQUEST_RESPONSE]: | ||||||||||
| raise UnsupportedInvocationType( | ||||||||||
| f"invocation-type: {invocation_type} is not supported. RequestResponse is only supported." | ||||||||||
| f"invocation-type: {invocation_type} is not supported. " | ||||||||||
| "Event and RequestResponse are only supported." | ||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| ) | ||||||||||
|
|
||||||||||
| # The container handles concurrency control internally via its semaphore. | ||||||||||
|
|
||||||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It makes sense to sink the exceptions like you're doing here, but how does this appear for the user? Do you have a screenshot of what it looks like when you try async invoking a function that has a syntax error (so the sandbox crashes)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's two cases, one if the invocation fails, with the exception above. Then the case if the user's code raises an exception seen below, where it will log the exception from the container.