-
Notifications
You must be signed in to change notification settings - Fork 433
feat(parser): add models for API GW Websockets events #5597
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
leandrodamascena
merged 15 commits into
aws-powertools:develop
from
ran-isenberg:websocket
Nov 24, 2024
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
b8a45ac
feature(parser): Parser models for API GW Websockets Events
efb0d79
Merge branch 'develop' into websocket
ran-isenberg bb7ef68
Merge branch 'develop' into websocket
ran-isenberg 90ff222
Merge branch 'develop' into websocket
ran-isenberg 5d7573c
Merge branch 'develop' into websocket
anafalcao 963b508
code review fixes
b23f9f3
Merge branch 'develop' into websocket
anafalcao 1c8f1c6
fix typo in the doc. add optional model
9aad542
fix optional field
ecc49cb
Merge branch 'develop' into websocket
leandrodamascena 1a100f7
Merge branch 'develop' into websocket
ran-isenberg f13d128
Merge branch 'develop' into websocket
leandrodamascena bffc462
change names to snake case
4c65191
Merge branch 'develop' into websocket
anafalcao a149ac1
Merge branch 'develop' into websocket
leandrodamascena 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
41 changes: 41 additions & 0 deletions
41
aws_lambda_powertools/utilities/parser/envelopes/apigw_websocket.py
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,41 @@ | ||
from __future__ import annotations | ||
|
||
import logging | ||
from typing import TYPE_CHECKING, Any | ||
|
||
from aws_lambda_powertools.utilities.parser.envelopes.base import BaseEnvelope | ||
from aws_lambda_powertools.utilities.parser.models import APIGatewayWebSocketMessageEventModel | ||
|
||
if TYPE_CHECKING: | ||
from aws_lambda_powertools.utilities.parser.types import Model | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class ApiGatewayWebSocketEnvelope(BaseEnvelope): | ||
"""API Gateway WebSockets envelope to extract data within body key of messages routes | ||
(not disconnect or connect)""" | ||
|
||
def parse(self, data: dict[str, Any] | Any | None, model: type[Model]) -> Model | None: | ||
"""Parses data found with model provided | ||
|
||
Parameters | ||
---------- | ||
data : dict | ||
Lambda event to be parsed | ||
model : type[Model] | ||
Data model provided to parse after extracting data using envelope | ||
|
||
Returns | ||
------- | ||
Any | ||
Parsed detail payload with model provided | ||
""" | ||
logger.debug( | ||
f"Parsing incoming data with Api Gateway WebSockets model {APIGatewayWebSocketMessageEventModel}", | ||
) | ||
parsed_envelope: APIGatewayWebSocketMessageEventModel = APIGatewayWebSocketMessageEventModel.model_validate( | ||
data, | ||
) | ||
logger.debug(f"Parsing event payload in `detail` with {model}") | ||
return self._parse(data=parsed_envelope.body, model=model) |
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
63 changes: 63 additions & 0 deletions
63
aws_lambda_powertools/utilities/parser/models/apigw_websocket.py
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,63 @@ | ||
from datetime import datetime | ||
from typing import Dict, List, Literal, Optional, Type, Union | ||
|
||
from pydantic import BaseModel, Field | ||
from pydantic.networks import IPvAnyNetwork | ||
|
||
|
||
class APIGatewayWebSocketEventIdentity(BaseModel): | ||
source_ip: IPvAnyNetwork = Field(alias="sourceIp") | ||
user_agent: Optional[str] = Field(None, alias="userAgent") | ||
|
||
class APIGatewayWebSocketEventRequestContextBase(BaseModel): | ||
extended_request_id: str = Field(alias="extendedRequestId") | ||
request_time: str = Field(alias="requestTime") | ||
stage: str = Field(alias="stage") | ||
connected_at: datetime = Field(alias="connectedAt") | ||
request_time_epoch: datetime = Field(alias="requestTimeEpoch") | ||
identity: APIGatewayWebSocketEventIdentity = Field(alias="identity") | ||
request_id: str = Field(alias="requestId") | ||
domain_name: str = Field(alias="domainName") | ||
connection_id: str = Field(alias="connectionId") | ||
api_id: str = Field(alias="apiId") | ||
|
||
|
||
class APIGatewayWebSocketMessageEventRequestContext(APIGatewayWebSocketEventRequestContextBase): | ||
route_key: str = Field(alias="routeKey") | ||
message_id: str = Field(alias="messageId") | ||
event_type: Literal["MESSAGE"] = Field(alias="eventType") | ||
message_direction: Literal["IN", "OUT"] = Field(alias="messageDirection") | ||
|
||
|
||
class APIGatewayWebSocketConnectEventRequestContext(APIGatewayWebSocketEventRequestContextBase): | ||
route_key: Literal["$connect"] = Field(alias="routeKey") | ||
event_type: Literal["CONNECT"] = Field(alias="eventType") | ||
message_direction: Literal["IN"] = Field(alias="messageDirection") | ||
|
||
|
||
class APIGatewayWebSocketDisconnectEventRequestContext(APIGatewayWebSocketEventRequestContextBase): | ||
route_key: Literal["$disconnect"] = Field(alias="routeKey") | ||
disconnect_status_code: int = Field(alias="disconnectStatusCode") | ||
event_type: Literal["DISCONNECT"] = Field(alias="eventType") | ||
message_direction: Literal["IN"] = Field(alias="messageDirection") | ||
disconnect_reason: str = Field(alias="disconnectReason") | ||
|
||
|
||
class APIGatewayWebSocketConnectEventModel(BaseModel): | ||
headers: Dict[str, str] = Field(alias="headers") | ||
multi_value_headers: Dict[str, List[str]] = Field(alias="multiValueHeaders") | ||
request_context: APIGatewayWebSocketConnectEventRequestContext = Field(alias="requestContext") | ||
is_base64_encoded: bool = Field(alias="isBase64Encoded") | ||
|
||
|
||
class APIGatewayWebSocketDisconnectEventModel(BaseModel): | ||
headers: Dict[str, str] = Field(alias="headers") | ||
multi_value_headers: Dict[str, List[str]] = Field(alias="multiValueHeaders") | ||
request_context: APIGatewayWebSocketDisconnectEventRequestContext = Field(alias="requestContext") | ||
is_base64_encoded: bool = Field(alias="isBase64Encoded") | ||
|
||
|
||
class APIGatewayWebSocketMessageEventModel(BaseModel): | ||
request_context: APIGatewayWebSocketMessageEventRequestContext = Field(alias="requestContext") | ||
is_base64_encoded: bool = Field(alias="isBase64Encoded") | ||
body: Optional[Union[str, Type[BaseModel]]] = Field(None, alias="body") |
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 |
---|---|---|
@@ -0,0 +1,40 @@ | ||
{ | ||
"headers": { | ||
"Host": "fjnq7njcv2.execute-api.us-east-1.amazonaws.com", | ||
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits", | ||
"Sec-WebSocket-Key": "+W5xw47OHh3OTFsWKjGu9Q==", | ||
"Sec-WebSocket-Version": "13", | ||
"X-Amzn-Trace-Id": "Root=1-6731ebfc-08e1e656421db73c5d2eef31", | ||
"X-Forwarded-For": "166.90.225.1", | ||
"X-Forwarded-Port": "443", | ||
"X-Forwarded-Proto": "https" | ||
}, | ||
"multiValueHeaders": { | ||
"Host": ["fjnq7njcv2.execute-api.us-east-1.amazonaws.com"], | ||
"Sec-WebSocket-Extensions": ["permessage-deflate; client_max_window_bits"], | ||
"Sec-WebSocket-Key": ["+W5xw47OHh3OTFsWKjGu9Q=="], | ||
"Sec-WebSocket-Version": ["13"], | ||
"X-Amzn-Trace-Id": ["Root=1-6731ebfc-08e1e656421db73c5d2eef31"], | ||
"X-Forwarded-For": ["166.90.225.1"], | ||
"X-Forwarded-Port": ["443"], | ||
"X-Forwarded-Proto": ["https"] | ||
}, | ||
"requestContext": { | ||
"routeKey": "$connect", | ||
"eventType": "CONNECT", | ||
"extendedRequestId": "BFHPhFe3IAMF95g=", | ||
"requestTime": "11/Nov/2024:11:35:24 +0000", | ||
"messageDirection": "IN", | ||
"stage": "prod", | ||
"connectedAt": 1731324924553, | ||
"requestTimeEpoch": 1731324924561, | ||
"identity": { | ||
"sourceIp": "166.90.225.1" | ||
}, | ||
"requestId": "BFHPhFe3IAMF95g=", | ||
"domainName": "asasasas.execute-api.us-east-1.amazonaws.com", | ||
"connectionId": "BFHPhfCWIAMCKlQ=", | ||
"apiId": "asasasas" | ||
}, | ||
"isBase64Encoded": false | ||
} |
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,34 @@ | ||
{ | ||
"headers": { | ||
"Host": "asasasas.execute-api.us-east-1.amazonaws.com", | ||
"x-api-key": "", | ||
"X-Forwarded-For": "", | ||
"x-restapi": "" | ||
}, | ||
"multiValueHeaders": { | ||
"Host": ["asasasas.execute-api.us-east-1.amazonaws.com"], | ||
"x-api-key": [""], | ||
"X-Forwarded-For": [""], | ||
"x-restapi": [""] | ||
}, | ||
"requestContext": { | ||
"routeKey": "$disconnect", | ||
"disconnectStatusCode": 1005, | ||
"eventType": "DISCONNECT", | ||
"extendedRequestId": "BFbOeE87IAMF31w=", | ||
"requestTime": "11/Nov/2024:13:51:49 +0000", | ||
"messageDirection": "IN", | ||
"disconnectReason": "Client-side close frame status not set", | ||
"stage": "prod", | ||
"connectedAt": 1731332735513, | ||
"requestTimeEpoch": 1731333109875, | ||
"identity": { | ||
"sourceIp": "166.90.225.1" | ||
}, | ||
"requestId": "BFbOeE87IAMF31w=", | ||
"domainName": "asasasas.execute-api.us-east-1.amazonaws.com", | ||
"connectionId": "BFaT_fALIAMCKug=", | ||
"apiId": "asasasas" | ||
}, | ||
"isBase64Encoded": false | ||
} |
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,22 @@ | ||
{ | ||
"requestContext": { | ||
"routeKey": "chat", | ||
"messageId": "BFaVtfGSIAMCKug=", | ||
"eventType": "MESSAGE", | ||
"extendedRequestId": "BFaVtH2HoAMFZEQ=", | ||
"requestTime": "11/Nov/2024:13:45:46 +0000", | ||
"messageDirection": "IN", | ||
"stage": "prod", | ||
"connectedAt": 1731332735513, | ||
"requestTimeEpoch": 1731332746514, | ||
"identity": { | ||
"sourceIp": "166.90.225.1" | ||
}, | ||
"requestId": "BFaVtH2HoAMFZEQ=", | ||
"domainName": "asasasas.execute-api.us-east-1.amazonaws.com", | ||
"connectionId": "BFaT_fALIAMCKug=", | ||
"apiId": "asasasas" | ||
}, | ||
"body": "{\"action\": \"chat\", \"message\": \"Hello from client\"}", | ||
"isBase64Encoded": false | ||
} |
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.
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.