Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions aws_lambda_powertools/utilities/parser/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@
from .sns import SnsModel, SnsNotificationModel, SnsRecordModel
from .sqs import SqsAttributesModel, SqsModel, SqsMsgAttributeModel, SqsRecordModel
from .transfer_family import TransferFamilyAuthorizer
from .tumbling_window import TumblingWindowEventModel, TumblingWindowModel
from .vpc_lattice import VpcLatticeModel
from .vpc_latticev2 import VpcLatticeV2Model

Expand Down Expand Up @@ -277,6 +278,8 @@
"SqsMsgAttributeModel": "sqs",
"SqsRecordModel": "sqs",
"TransferFamilyAuthorizer": "transfer_family",
"TumblingWindowEventModel": "tumbling_window",
"TumblingWindowModel": "tumbling_window",
"VpcLatticeModel": "vpc_lattice",
"VpcLatticeV2Model": "vpc_latticev2",
}
Expand Down Expand Up @@ -392,6 +395,8 @@ def __dir__() -> list[str]:
"S3SqsEventNotificationModel",
"S3SqsEventNotificationRecordModel",
"TransferFamilyAuthorizer",
"TumblingWindowEventModel",
"TumblingWindowModel",
"APIGatewayProxyEventModel",
"APIGatewayEventRequestContext",
"APIGatewayEventAuthorizer",
Expand Down
3 changes: 2 additions & 1 deletion aws_lambda_powertools/utilities/parser/models/dynamodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from pydantic.alias_generators import to_camel

from aws_lambda_powertools.shared.dynamodb_deserializer import TypeDeserializer
from aws_lambda_powertools.utilities.parser.models.tumbling_window import TumblingWindowEventModel

_DESERIALIZER = TypeDeserializer()

Expand Down Expand Up @@ -87,7 +88,7 @@ class DynamoDBStreamRecordModel(BaseModel):
)


class DynamoDBStreamModel(BaseModel):
class DynamoDBStreamModel(TumblingWindowEventModel):
Records: list[DynamoDBStreamRecordModel] = Field(
description="A list of records that contain the details of the DynamoDB stream events.",
examples=[
Expand Down
3 changes: 2 additions & 1 deletion aws_lambda_powertools/utilities/parser/models/kinesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from aws_lambda_powertools.utilities.parser.models.cloudwatch import (
CloudWatchLogsDecode,
)
from aws_lambda_powertools.utilities.parser.models.tumbling_window import TumblingWindowEventModel


class KinesisDataStreamRecordPayload(BaseModel):
Expand Down Expand Up @@ -75,7 +76,7 @@ def decompress_zlib_record_data_as_json(self) -> dict:
return json.loads(zlib.decompress(self.kinesis.data, zlib.MAX_WBITS | 32))


class KinesisDataStreamModel(BaseModel):
class KinesisDataStreamModel(TumblingWindowEventModel):
Records: list[KinesisDataStreamRecord] = Field(
description="A list of Kinesis Data Stream records that triggered the Lambda function.",
examples=[[]],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# ruff: noqa: FA100
from datetime import datetime
from typing import Any

from pydantic import BaseModel, Field


class TumblingWindowModel(BaseModel):
start: datetime = Field(
description="The time the tumbling window started, in ISO-8601 format.",
examples=["2020-12-09T07:04:00Z"],
)
end: datetime = Field(
description="The time the tumbling window ends, in ISO-8601 format.",
examples=["2020-12-09T07:06:00Z"],
)


class TumblingWindowEventModel(BaseModel):
window: TumblingWindowModel | None = Field(
default=None,
description="The tumbling window for this invocation, when tumbling windows are enabled.",
examples=[{"start": "2020-12-09T07:04:00Z", "end": "2020-12-09T07:06:00Z"}],
)
state: dict[str, Any] | None = Field(
default=None,
description="The state from previous invocations of the tumbling window.",
examples=[{"1": 282, "2": 715}],
)
shardId: str | None = Field(
default=None,
description="The shard ID of the stream shard that contains the records.",
examples=["shardId-000000000006"],
)
eventSourceARN: str | None = Field(
default=None,
description="The Amazon Resource Name (ARN) of the stream that generated the event.",
examples=["arn:aws:kinesis:us-east-1:123456789012:stream/lambda-stream"],
)
isFinalInvokeForWindow: bool | None = Field(
default=None,
description="Whether this is the final invoke for the tumbling window.",
examples=[False],
)
isWindowTerminatedEarly: bool | None = Field(
default=None,
description="Whether the tumbling window was terminated early.",
examples=[False],
)
33 changes: 32 additions & 1 deletion tests/unit/parser/_pydantic/test_dynamodb.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from datetime import datetime, timezone
from typing import Any

import pytest

from aws_lambda_powertools.utilities.parser import ValidationError, envelopes, parse
from aws_lambda_powertools.utilities.parser.models import DynamoDBStreamLambdaOnFailureDestinationModel
from aws_lambda_powertools.utilities.parser.models import (
DynamoDBStreamLambdaOnFailureDestinationModel,
DynamoDBStreamModel,
)
from tests.functional.utils import load_event
from tests.unit.parser._pydantic.schemas import MyAdvancedDynamoBusiness, MyDynamoBusiness

Expand Down Expand Up @@ -136,3 +140,30 @@ def test_dynamo_db_stream_lambda_invocation_event(response_context: dict[str, An
assert parsed_event.response_context.function_error == response_context.get("functionError")
assert parsed_event.timestamp.strftime("%Y-%m-%dT%H:%M:%SZ") == raw_event["timestamp"]
assert parsed_event.version == raw_event["version"]


def test_dynamo_db_stream_tumbling_window_event():
raw_event = load_event("dynamoStreamTumblingWindowEvent.json")
parsed_event = DynamoDBStreamModel(**raw_event)

assert len(parsed_event.Records) == 3
assert parsed_event.window is not None
assert parsed_event.window.start == datetime(2020, 7, 30, 17, 0, tzinfo=timezone.utc)
assert parsed_event.window.end == datetime(2020, 7, 30, 17, 5, tzinfo=timezone.utc)
assert parsed_event.state == {"1": "state1"}
assert parsed_event.shardId == "shard123456789"
assert parsed_event.eventSourceARN == "stream-ARN"
assert parsed_event.isFinalInvokeForWindow is False
assert parsed_event.isWindowTerminatedEarly is False


def test_dynamo_db_stream_event_without_tumbling_window():
raw_event = load_event("dynamoStreamEvent.json")
parsed_event = DynamoDBStreamModel(**raw_event)

assert parsed_event.window is None
assert parsed_event.state is None
assert parsed_event.shardId is None
assert parsed_event.eventSourceARN is None
assert parsed_event.isFinalInvokeForWindow is None
assert parsed_event.isWindowTerminatedEarly is None
29 changes: 29 additions & 0 deletions tests/unit/parser/_pydantic/test_kinesis.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import datetime, timezone

import pytest

from aws_lambda_powertools.utilities.parser import BaseModel, ValidationError, envelopes, parse
Expand Down Expand Up @@ -130,3 +132,30 @@ def test_kinesis_stream_event_with_cloud_watch_logs_data_fails_using_envelope():
# THEN a ValueError should be thrown
with pytest.raises(ValueError):
envelopes.KinesisDataStreamEnvelope().parse(raw_event, CloudWatchLogsDecode)


def test_kinesis_tumbling_window_event():
raw_event = load_event("kinesisStreamTumblingWindowEvent.json")
parsed_event = KinesisDataStreamModel(**raw_event)

assert len(parsed_event.Records) == 1
assert parsed_event.window is not None
assert parsed_event.window.start == datetime(2020, 12, 9, 7, 4, tzinfo=timezone.utc)
assert parsed_event.window.end == datetime(2020, 12, 9, 7, 6, tzinfo=timezone.utc)
assert parsed_event.state == {"1": 282, "2": 715}
assert parsed_event.shardId == "shardId-000000000006"
assert parsed_event.eventSourceARN == "arn:aws:kinesis:us-east-1:123456789012:stream/lambda-stream"
assert parsed_event.isFinalInvokeForWindow is False
assert parsed_event.isWindowTerminatedEarly is False


def test_kinesis_event_without_tumbling_window():
raw_event = load_event("kinesisStreamEventOneRecord.json")
parsed_event = KinesisDataStreamModel(**raw_event)

assert parsed_event.window is None
assert parsed_event.state is None
assert parsed_event.shardId is None
assert parsed_event.eventSourceARN is None
assert parsed_event.isFinalInvokeForWindow is None
assert parsed_event.isWindowTerminatedEarly is None