Skip to content

ESM-v2: Add SNS as a failure destination for Kinesis and DynamoDB #4

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,10 @@ def send_events_to_dlq(self, shard_id, events, context) -> None:
dlq_url = get_queue_url(dlq_arn)
# TODO: validate no FIFO queue because they are unsupported
sqs_client.send_message(QueueUrl=dlq_url, MessageBody=json.dumps(dlq_event))
elif service == "sns":
sns_client = get_internal_client(dlq_arn)
sns_client.publish(TopicArn=dlq_arn, Message=json.dumps(dlq_event))
else:
# TODO: implement sns DLQ
LOG.warning("Unsupported DLQ service %s", service)

def create_dlq_event(self, shard_id: str, events: list[dict], context: dict) -> dict:
Expand Down
1 change: 1 addition & 0 deletions localstack-core/localstack/testing/aws/lambda_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ def get_invoke_init_type(
"Effect": "Allow",
"Action": [
"sqs:*",
"sns:*",
"dynamodb:DescribeStream",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,130 @@ def test_deletion_event_source_mapping_with_dynamodb(
list_esm = aws_client.lambda_.list_event_source_mappings(EventSourceArn=latest_stream_arn)
snapshot.match("list_event_source_mapping_result", list_esm)

# FIXME UpdateTable is not returning a TableID
@markers.snapshot.skip_snapshot_verify(
paths=[
"$..TableDescription.TableId",
],
)
@markers.snapshot.skip_snapshot_verify(
condition=is_old_esm,
paths=[
"$..Message.DDBStreamBatchInfo.approximateArrivalOfFirstRecord", # Incorrect timestamp formatting
"$..Message.DDBStreamBatchInfo.approximateArrivalOfLastRecord",
"$..Message.requestContext.approximateInvokeCount",
"$..Message.responseContext.statusCode",
],
)
@markers.aws.validated
def test_dynamodb_event_source_mapping_with_sns_on_failure_destination_config(
self,
create_lambda_function,
sqs_get_queue_arn,
sqs_create_queue,
sns_create_topic,
sns_allow_topic_sqs_queue,
create_iam_role_with_policy,
dynamodb_create_table,
snapshot,
cleanups,
aws_client,
):
snapshot.add_transformer(snapshot.transform.sns_api())

snapshot.add_transformer(snapshot.transform.key_value("startSequenceNumber"))
snapshot.add_transformer(snapshot.transform.key_value("endSequenceNumber"))

function_name = f"lambda_func-{short_uid()}"
role = f"test-lambda-role-{short_uid()}"
policy_name = f"test-lambda-policy-{short_uid()}"
table_name = f"test-table-{short_uid()}"
partition_key = "my_partition_key"
item = {partition_key: {"S": "hello world"}}

# create topic and queue
queue_url = sqs_create_queue()
topic_info = sns_create_topic()
topic_arn = topic_info["TopicArn"]

# subscribe SQS to SNS
queue_arn = sqs_get_queue_arn(queue_url)
subscription = aws_client.sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=queue_arn,
)
cleanups.append(
lambda: aws_client.sns.unsubscribe(SubscriptionArn=subscription["SubscriptionArn"])
)

sns_allow_topic_sqs_queue(
sqs_queue_url=queue_url, sqs_queue_arn=queue_arn, sns_topic_arn=topic_arn
)

role_arn = create_iam_role_with_policy(
RoleName=role,
PolicyName=policy_name,
RoleDefinition=lambda_role,
PolicyDefinition=s3_lambda_permission,
)

create_lambda_function(
handler_file=TEST_LAMBDA_PYTHON_UNHANDLED_ERROR,
func_name=function_name,
runtime=Runtime.python3_12,
role=role_arn,
)
create_table_response = dynamodb_create_table(
table_name=table_name, partition_key=partition_key
)
_await_dynamodb_table_active(aws_client.dynamodb, table_name)
snapshot.match("create_table_response", create_table_response)

update_table_response = aws_client.dynamodb.update_table(
TableName=table_name,
StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_IMAGE"},
)
snapshot.match("update_table_response", update_table_response)
stream_arn = update_table_response["TableDescription"]["LatestStreamArn"]

destination_config = {"OnFailure": {"Destination": topic_arn}}
create_event_source_mapping_response = aws_client.lambda_.create_event_source_mapping(
FunctionName=function_name,
BatchSize=1,
StartingPosition="TRIM_HORIZON",
EventSourceArn=stream_arn,
MaximumBatchingWindowInSeconds=1,
MaximumRetryAttempts=1,
DestinationConfig=destination_config,
)
snapshot.match("create_event_source_mapping_response", create_event_source_mapping_response)
event_source_mapping_uuid = create_event_source_mapping_response["UUID"]
cleanups.append(
lambda: aws_client.lambda_.delete_event_source_mapping(UUID=event_source_mapping_uuid)
)

_await_event_source_mapping_enabled(aws_client.lambda_, event_source_mapping_uuid)

aws_client.dynamodb.put_item(TableName=table_name, Item=item)

def verify_failure_received():
res = aws_client.sqs.receive_message(QueueUrl=queue_url)
assert len(res.get("Messages", [])) == 1
return res

# It can take ~3 min against AWS until the message is received
sleep = 15 if is_aws_cloud() else 5
messages = retry(verify_failure_received, retries=15, sleep=sleep, sleep_before=5)
Comment on lines +446 to +447
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider using a constant for sleep time instead of a conditional


# The failure context payload of the SQS response is in JSON-string format.
# Rather extract, parse, and snapshot it since the SQS information is irrelevant.
failure_sns_payload = messages.get("Messages", []).pop(0)
failure_sns_body_json = failure_sns_payload.get("Body", {})
failure_sns_message = json.loads(failure_sns_body_json)

snapshot.match("failure_sns_message", failure_sns_message)

# FIXME UpdateTable is not returning a TableID
@markers.snapshot.skip_snapshot_verify(
paths=[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1959,5 +1959,150 @@
}
]
}
},
"tests/aws/services/lambda_/event_source_mapping/test_lambda_integration_dynamodbstreams.py::TestDynamoDBEventSourceMapping::test_dynamodb_event_source_mapping_with_sns_on_failure_destination_config": {
"recorded-date": "16-09-2024, 15:49:14",
"recorded-content": {
"create_table_response": {
"TableDescription": {
"AttributeDefinitions": [
{
"AttributeName": "my_partition_key",
"AttributeType": "S"
}
],
"BillingModeSummary": {
"BillingMode": "PAY_PER_REQUEST"
},
"CreationDateTime": "<datetime>",
"DeletionProtectionEnabled": false,
"ItemCount": 0,
"KeySchema": [
{
"AttributeName": "my_partition_key",
"KeyType": "HASH"
}
],
"ProvisionedThroughput": {
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 0,
"WriteCapacityUnits": 0
},
"TableArn": "arn:<partition>:dynamodb:<region>:111111111111:table/<resource:1>",
"TableId": "<uuid:1>",
"TableName": "<resource:1>",
"TableSizeBytes": 0,
"TableStatus": "CREATING"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
},
"update_table_response": {
"TableDescription": {
"AttributeDefinitions": [
{
"AttributeName": "my_partition_key",
"AttributeType": "S"
}
],
"BillingModeSummary": {
"BillingMode": "PAY_PER_REQUEST",
"LastUpdateToPayPerRequestDateTime": "<datetime>"
},
"CreationDateTime": "<datetime>",
"DeletionProtectionEnabled": false,
"ItemCount": 0,
"KeySchema": [
{
"AttributeName": "my_partition_key",
"KeyType": "HASH"
}
],
"LatestStreamArn": "arn:<partition>:dynamodb:<region>:111111111111:table/<resource:1>/stream/<resource:2>",
"LatestStreamLabel": "<resource:2>",
"ProvisionedThroughput": {
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 0,
"WriteCapacityUnits": 0
},
"StreamSpecification": {
"StreamEnabled": true,
"StreamViewType": "NEW_IMAGE"
},
"TableArn": "arn:<partition>:dynamodb:<region>:111111111111:table/<resource:1>",
"TableId": "<uuid:1>",
"TableName": "<resource:1>",
"TableSizeBytes": 0,
"TableStatus": "UPDATING"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
},
"create_event_source_mapping_response": {
"BatchSize": 1,
"BisectBatchOnFunctionError": false,
"DestinationConfig": {
"OnFailure": {
"Destination": "arn:<partition>:sns:<region>:111111111111:<resource:3>"
}
},
"EventSourceArn": "arn:<partition>:dynamodb:<region>:111111111111:table/<resource:1>/stream/<resource:2>",
"FunctionArn": "arn:<partition>:lambda:<region>:111111111111:function:<resource:4>",
"FunctionResponseTypes": [],
"LastModified": "<datetime>",
"LastProcessingResult": "No records processed",
"MaximumBatchingWindowInSeconds": 1,
"MaximumRecordAgeInSeconds": -1,
"MaximumRetryAttempts": 1,
"ParallelizationFactor": 1,
"StartingPosition": "TRIM_HORIZON",
"State": "Creating",
"StateTransitionReason": "User action",
"TumblingWindowInSeconds": 0,
"UUID": "<uuid:2>",
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 202
}
},
"failure_sns_message": {
"Message": {
"requestContext": {
"requestId": "<uuid:3>",
"functionArn": "arn:<partition>:lambda:<region>:111111111111:function:<resource:4>",
"condition": "RetryAttemptsExhausted",
"approximateInvokeCount": 2
},
"responseContext": {
"statusCode": 200,
"executedVersion": "$LATEST",
"functionError": "Unhandled"
},
"version": "1.0",
"timestamp": "<timestamp:2022-07-13T13:48:01.000Z>",
"DDBStreamBatchInfo": {
"shardId": "<shard-id:1>",
"startSequenceNumber": "<start-sequence-number:1>",
"endSequenceNumber": "<start-sequence-number:1>",
"approximateArrivalOfFirstRecord": "<timestamp:2022-07-13T13:48:01Z>",
"approximateArrivalOfLastRecord": "<timestamp:2022-07-13T13:48:01Z>",
"batchSize": 1,
"streamArn": "arn:<partition>:dynamodb:<region>:111111111111:table/<resource:1>/stream/<resource:2>"
}
},
"MessageId": "<uuid:4>",
"Signature": "<signature>",
"SignatureVersion": "1",
"SigningCertURL": "<cert-domain>/SimpleNotificationService-<signing-cert-file:1>",
"Timestamp": "<timestamp:2022-07-13T13:48:01.000Z>",
"TopicArn": "arn:<partition>:sns:<region>:111111111111:<resource:3>",
"Type": "Notification",
"UnsubscribeURL": "<unsubscribe-domain>/?Action=Unsubscribe&SubscriptionArn=arn:<partition>:sns:<region>:111111111111:<resource:3>:<resource:5>"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@
"tests/aws/services/lambda_/event_source_mapping/test_lambda_integration_dynamodbstreams.py::TestDynamoDBEventSourceMapping::test_dynamodb_event_source_mapping_with_on_failure_destination_config": {
"last_validated_date": "2024-09-03T14:58:05+00:00"
},
"tests/aws/services/lambda_/event_source_mapping/test_lambda_integration_dynamodbstreams.py::TestDynamoDBEventSourceMapping::test_dynamodb_event_source_mapping_with_sns_on_failure_destination_config": {
"last_validated_date": "2024-09-16T15:49:08+00:00"
},
"tests/aws/services/lambda_/event_source_mapping/test_lambda_integration_dynamodbstreams.py::TestDynamoDBEventSourceMapping::test_dynamodb_invalid_event_filter[[{\"eventName\": [\"INSERT\"=123}]]": {
"last_validated_date": "2024-09-03T15:10:35+00:00"
},
Expand Down
Loading