-
Notifications
You must be signed in to change notification settings - Fork 432
feat(event-handler): add http ProxyEvent handler #369
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
heitorlessa
merged 47 commits into
aws-powertools:develop
from
gyft:feat-event-handler-apigw
Apr 28, 2021
Merged
Changes from 29 commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
1695911
feat(event-handler): Add http ProxyEvent handler
michaelbrewer d0f21f1
feat(event-handler): Lightweight rule matching
michaelbrewer 670f872
fix(event-handler): Python 3.6 support
michaelbrewer 633bff1
refactor(event-handler): Add lambda_context and current_request to app
michaelbrewer ad88b0b
refactor(event-handler): Resolv Pycharm warnings
michaelbrewer 8b72bd2
chore(event-handler): Refactoring
michaelbrewer d66f380
feat(event-handler): Ensure we reset routes in __init__
michaelbrewer 7588af0
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 001e8a9
refactor(event-handler): Rename to recent_event
michaelbrewer e7a9e42
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 8af2072
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 8c35ce7
chore(event-handler): Refactor name
michaelbrewer 4a30ddc
chore: Refactor
michaelbrewer d17c59b
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 6030340
feat(event-handler): Add mapping for api_gateway
michaelbrewer fe73699
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer c87a526
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 7abceae
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer a065474
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 1d6ea4d
feat(event-handler): Add cors support to apigw handler
michaelbrewer 306ee73
feat(event-handler): apigw compress and base64encode
michaelbrewer daaf137
feat(event-handler): apigwy cache_control option
michaelbrewer 6f6a55c
refactor(event-handler): Code cleanup
michaelbrewer 1484ac9
tests(event-handler): Add missing binary handling
michaelbrewer 9ee7702
fix(event-handler): Set Content-Encoding header for compress
michaelbrewer 85b5ff8
feat(event-handler): Add PATCH decorator
michaelbrewer 0cf5366
docs(event-handler): Add some docs to tests
michaelbrewer b5a057b
feat(event-handler): Rest API simplification with function returns a …
michaelbrewer e7e8d59
feat(event-handler): Add Response class
michaelbrewer 0fe00f6
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer e57b59e
feat(event-handler): Use shared json Encoder
michaelbrewer 569cdbd
fix(data-classes): Correct typing for json_body
michaelbrewer c1ea9b1
tests: Add shared test utils.load_event
michaelbrewer 7940c46
docs(tests): Add more docs to tests
michaelbrewer f74307f
refactor(event-handler): Final housekeeping
michaelbrewer 3370c14
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 4c20ceb
tests(event-handler): Fix import
michaelbrewer bb660b1
Merge branch 'develop' into feat-event-handler-apigw
michaelbrewer 785877c
refactor: precise handling of headers
michaelbrewer c5709bc
refactor: add to_response to simplify logic
michaelbrewer 318508f
feat(event-handler): Add a more complete implementation of cors
michaelbrewer f0e4f11
fix(event-handler): Default to false
michaelbrewer ee52aee
refactor: make some of the code-review changes
michaelbrewer be12f3e
feat(event-handler): Add auto generated preflight option
michaelbrewer 2eeee5c
chore: bump ci
michaelbrewer fbccaa1
fix(event-handler): make python 3.6 compatible
michaelbrewer 6ec444c
refactor: make more method as _
michaelbrewer 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
import base64 | ||
import json | ||
import re | ||
import zlib | ||
from enum import Enum | ||
from typing import Any, Callable, Dict, List, Optional, Tuple, Union | ||
|
||
from aws_lambda_powertools.utilities.data_classes import ALBEvent, APIGatewayProxyEvent, APIGatewayProxyEventV2 | ||
from aws_lambda_powertools.utilities.data_classes.common import BaseProxyEvent | ||
from aws_lambda_powertools.utilities.typing import LambdaContext | ||
|
||
|
||
class ProxyEventType(Enum): | ||
http_api_v1 = "APIGatewayProxyEvent" | ||
http_api_v2 = "APIGatewayProxyEventV2" | ||
alb_event = "ALBEvent" | ||
api_gateway = http_api_v1 | ||
|
||
|
||
class Route: | ||
def __init__( | ||
self, method: str, rule: Any, func: Callable, cors: bool, compress: bool, cache_control: Optional[str] | ||
): | ||
self.method = method.upper() | ||
self.rule = rule | ||
self.func = func | ||
self.cors = cors | ||
self.compress = compress | ||
self.cache_control = cache_control | ||
|
||
|
||
class Response: | ||
def __init__(self, status_code: int, content_type: str, body: Union[str, bytes], headers: Dict = None): | ||
self.status_code = status_code | ||
self.body = body | ||
self.base64_encoded = False | ||
self.headers: Dict = headers if headers is not None else {} | ||
if "Content-Type" not in self.headers: | ||
self.headers["Content-Type"] = content_type | ||
|
||
def add_cors(self, method: str): | ||
self.headers["Access-Control-Allow-Origin"] = "*" | ||
self.headers["Access-Control-Allow-Methods"] = method | ||
self.headers["Access-Control-Allow-Credentials"] = "true" | ||
michaelbrewer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def add_cache_control(self, cache_control: str): | ||
self.headers["Cache-Control"] = cache_control if self.status_code == 200 else "no-cache" | ||
|
||
def compress(self): | ||
self.headers["Content-Encoding"] = "gzip" | ||
if isinstance(self.body, str): | ||
self.body = bytes(self.body, "utf-8") | ||
gzip = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) | ||
self.body = gzip.compress(self.body) + gzip.flush() | ||
|
||
def to_dict(self): | ||
if isinstance(self.body, bytes): | ||
self.base64_encoded = True | ||
self.body = base64.b64encode(self.body).decode() | ||
return { | ||
"statusCode": self.status_code, | ||
"headers": self.headers, | ||
"body": self.body, | ||
"isBase64Encoded": self.base64_encoded, | ||
} | ||
|
||
|
||
class ApiGatewayResolver: | ||
michaelbrewer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
current_event: BaseProxyEvent | ||
lambda_context: LambdaContext | ||
|
||
def __init__(self, proxy_type: Enum = ProxyEventType.http_api_v1): | ||
self._proxy_type = proxy_type | ||
self._routes: List[Route] = [] | ||
|
||
def get(self, rule: str, cors: bool = False, compress: bool = False, cache_control: str = None): | ||
return self.route(rule, "GET", cors, compress, cache_control) | ||
|
||
def post(self, rule: str, cors: bool = False, compress: bool = False, cache_control: str = None): | ||
return self.route(rule, "POST", cors, compress, cache_control) | ||
|
||
def put(self, rule: str, cors: bool = False, compress: bool = False, cache_control: str = None): | ||
return self.route(rule, "PUT", cors, compress, cache_control) | ||
|
||
def delete(self, rule: str, cors: bool = False, compress: bool = False, cache_control: str = None): | ||
return self.route(rule, "DELETE", cors, compress, cache_control) | ||
|
||
def patch(self, rule: str, cors: bool = False, compress: bool = False, cache_control: str = None): | ||
return self.route(rule, "PATCH", cors, compress, cache_control) | ||
|
||
def route(self, rule: str, method: str, cors: bool = False, compress: bool = False, cache_control: str = None): | ||
def register_resolver(func: Callable): | ||
self._routes.append(Route(method, self._build_rule_pattern(rule), func, cors, compress, cache_control)) | ||
return func | ||
|
||
return register_resolver | ||
|
||
def resolve(self, event, context) -> Dict[str, Any]: | ||
self.current_event = self._as_data_class(event) | ||
self.lambda_context = context | ||
route, args = self._find_route(self.current_event.http_method, self.current_event.path) | ||
result = route.func(**args) | ||
|
||
if isinstance(result, Response): | ||
response = result | ||
elif isinstance(result, dict): | ||
response = Response(status_code=200, content_type="application/json", body=json.dumps(result)) | ||
michaelbrewer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
else: | ||
response = Response(*result) | ||
|
||
if route.cors: | ||
response.add_cors(route.method) | ||
if route.cache_control: | ||
response.add_cache_control(route.cache_control) | ||
if route.compress and "gzip" in (self.current_event.get_header_value("accept-encoding") or ""): | ||
response.compress() | ||
|
||
return response.to_dict() | ||
|
||
@staticmethod | ||
def _build_rule_pattern(rule: str): | ||
rule_regex: str = re.sub(r"(<\w+>)", r"(?P\1.+)", rule) | ||
return re.compile("^{}$".format(rule_regex)) | ||
|
||
def _as_data_class(self, event: Dict) -> BaseProxyEvent: | ||
if self._proxy_type == ProxyEventType.http_api_v1: | ||
return APIGatewayProxyEvent(event) | ||
if self._proxy_type == ProxyEventType.http_api_v2: | ||
return APIGatewayProxyEventV2(event) | ||
return ALBEvent(event) | ||
|
||
def _find_route(self, method: str, path: str) -> Tuple[Route, Dict]: | ||
method = method.upper() | ||
for route in self._routes: | ||
if method != route.method: | ||
continue | ||
match: Optional[re.Match] = route.rule.match(path) | ||
if match: | ||
return route, match.groupdict() | ||
|
||
raise ValueError(f"No route found for '{method}.{path}'") | ||
|
||
def __call__(self, event, context) -> Any: | ||
return self.resolve(event, context) |
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
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.
Uh oh!
There was an error while loading. Please reload this page.