fix(lambda): preserve CloudFormation event source mapping options (#4316)

AWS::Lambda::EventSourceMapping now forwards MaximumBatchingWindowInSeconds,
MaximumRetryAttempts, MaximumRecordAgeInSeconds, BisectBatchOnFunctionError,
FilterCriteria, DestinationConfig and ScalingConfig to LambdaService, so a
stack-created mapping matches an API-created one. On UpdateStack each of
these that the template omits is sent as null, which clears it.

ParallelizationFactor and TumblingWindowInSeconds are not modeled and remain
ignored; the resource-type table notes this.

Fixes #4313
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-24 21:05:00 -04:00
1 parent eb2872f578
commit 4abba5a218
5 files changed
+547 -44

No files matched your search

@@ -4,6 +4,7 @@ import org.junit.jupiter.api.*;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.*;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.GetEventSourceMappingResponse;
import software.amazon.awssdk.services.lambda.model.ListEventSourceMappingsResponse;
import software.amazon.awssdk.services.sqs.SqsClient;
@@ -13,7 +14,9 @@ import static org.assertj.core.api.Assertions.*;
/**
* Verifies that CloudFormation AWS::Lambda::EventSourceMapping provisions and
* deletes an ESM backed by an SQS queue, matching the use-case from issue #593.
* deletes an ESM backed by an SQS queue, matching the use-case from issue #593,
* and that batching, filtering, scaling, retry and destination options set in the
* template reach the mapping and are cleared when removed on update (issue #4313).
*/
@DisplayName("CloudFormation AWS::Lambda::EventSourceMapping")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -26,11 +29,18 @@ class CloudFormationEventSourceMappingTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String DDB_STACK_NAME = "compat-cfn-esm-ddb-stack";
private static final String DDB_FUNC_NAME = "compat-cfn-esm-ddb-func";
private static final String DDB_TABLE_NAME = "compat-cfn-esm-ddb-table";
private static final String DLQ_NAME = "compat-cfn-esm-ddb-dlq";
private static final String FILTER_PATTERN = "{\"body\":{\"kind\":[\"order\"]}}";
private static CloudFormationClient cfn;
private static LambdaClient lambda;
private static SqsClient sqs;
private static String esmUuid;
private static String ddbEsmUuid;
@BeforeAll
static void setup() {
@@ -44,6 +54,7 @@ class CloudFormationEventSourceMappingTest {
try {
if (cfn != null) {
cfn.deleteStack(DeleteStackRequest.builder().stackName(STACK_NAME).build());
cfn.deleteStack(DeleteStackRequest.builder().stackName(DDB_STACK_NAME).build());
}
} catch (Exception ignored) {}
if (cfn != null) cfn.close();
@@ -55,41 +66,11 @@ class CloudFormationEventSourceMappingTest {
@Order(1)
@DisplayName("CreateStack with Lambda + SQS + EventSourceMapping reaches CREATE_COMPLETE")
void createStack_withEventSourceMapping() throws InterruptedException {
String queueArn = "arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":" + QUEUE_NAME;
String template = """
{
"Resources": {
"MyQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "%s"
}
},
"MyFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Handler": "index.handler",
"Role": "%s",
"Code": {
"ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"
}
}
},
"MyESM": {
"Type": "AWS::Lambda::EventSourceMapping",
"Properties": {
"FunctionName": "%s",
"EventSourceArn": { "Fn::GetAtt": ["MyQueue", "Arn"] },
"Enabled": true,
"BatchSize": 5
}
}
}
}
""".formatted(QUEUE_NAME, FUNC_NAME, ROLE, FUNC_NAME);
String template = sqsStackTemplate("""
"MaximumBatchingWindowInSeconds": 5,
"FilterCriteria": { "Filters": [ { "Pattern": "{\\"body\\":{\\"kind\\":[\\"order\\"]}}" } ] },
"ScalingConfig": { "MaximumConcurrency": 5 }
""");
cfn.createStack(CreateStackRequest.builder()
.stackName(STACK_NAME)
@@ -140,16 +121,98 @@ class CloudFormationEventSourceMappingTest {
void getEventSourceMappingByUuid() {
assertThat(esmUuid).as("ESM UUID must have been captured in earlier test").isNotNull();
var esm = lambda.getEventSourceMapping(r -> r.uuid(esmUuid));
GetEventSourceMappingResponse esm = lambda.getEventSourceMapping(r -> r.uuid(esmUuid));
assertThat(esm.uuid()).isEqualTo(esmUuid);
assertThat(esm.functionArn()).contains(FUNC_NAME);
assertThat(esm.eventSourceArn()).contains(QUEUE_NAME);
assertThat(esm.batchSize()).isEqualTo(5);
assertThat(esm.state()).isIn("Enabled", "Enabling");
assertThat(esm.maximumBatchingWindowInSeconds()).isEqualTo(5);
assertThat(esm.filterCriteria()).isNotNull();
assertThat(esm.filterCriteria().filters()).singleElement()
.satisfies(f -> assertThat(f.pattern()).isEqualTo(FILTER_PATTERN));
assertThat(esm.scalingConfig()).isNotNull();
assertThat(esm.scalingConfig().maximumConcurrency()).isEqualTo(5);
}
@Test
@Order(5)
@DisplayName("UpdateStack changes the batching window and clears removed FilterCriteria and ScalingConfig")
void updateStack_changesWindowAndClearsRemovedOptions() throws InterruptedException {
assertThat(esmUuid).as("ESM UUID must have been captured in earlier test").isNotNull();
cfn.updateStack(UpdateStackRequest.builder()
.stackName(STACK_NAME)
.templateBody(sqsStackTemplate("""
"MaximumBatchingWindowInSeconds": 20
"""))
.build());
assertThat(waitForTerminal(STACK_NAME, 30)).isEqualTo("UPDATE_COMPLETE");
GetEventSourceMappingResponse esm = lambda.getEventSourceMapping(r -> r.uuid(esmUuid));
assertThat(esm.uuid()).isEqualTo(esmUuid);
assertThat(esm.maximumBatchingWindowInSeconds()).isEqualTo(20);
assertThat(esm.filterCriteria()).isNull();
assertThat(esm.scalingConfig() == null || esm.scalingConfig().maximumConcurrency() == null).isTrue();
}
@Test
@Order(6)
@DisplayName("DynamoDB stream ESM carries retry, record age, bisect and DestinationConfig from the template")
void createDynamoDbStreamStack_withRetryAndDestinationOptions() throws InterruptedException {
cfn.createStack(CreateStackRequest.builder()
.stackName(DDB_STACK_NAME)
.templateBody(ddbStackTemplate("""
"MaximumRetryAttempts": 2,
"MaximumRecordAgeInSeconds": 3600,
"BisectBatchOnFunctionError": true,
"DestinationConfig": { "OnFailure": { "Destination": { "Fn::GetAtt": ["MyDlq", "Arn"] } } }
"""))
.build());
assertThat(waitForTerminal(DDB_STACK_NAME, 30)).isEqualTo("CREATE_COMPLETE");
ddbEsmUuid = cfn.describeStackResources(
DescribeStackResourcesRequest.builder().stackName(DDB_STACK_NAME).build()
).stackResources().stream()
.filter(r -> "AWS::Lambda::EventSourceMapping".equals(r.resourceType()))
.findFirst()
.orElseThrow(() -> new AssertionError("No EventSourceMapping resource found"))
.physicalResourceId();
GetEventSourceMappingResponse esm = lambda.getEventSourceMapping(r -> r.uuid(ddbEsmUuid));
assertThat(esm.eventSourceArn()).contains(":dynamodb:").contains(DDB_TABLE_NAME);
assertThat(esm.maximumRetryAttempts()).isEqualTo(2);
assertThat(esm.maximumRecordAgeInSeconds()).isEqualTo(3600);
assertThat(esm.bisectBatchOnFunctionError()).isTrue();
assertThat(esm.destinationConfig()).isNotNull();
assertThat(esm.destinationConfig().onFailure().destination())
.isEqualTo("arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":" + DLQ_NAME);
}
@Test
@Order(7)
@DisplayName("UpdateStack clears retry, record age, bisect and DestinationConfig removed from the template")
void updateDynamoDbStreamStack_clearsRemovedOptions() throws InterruptedException {
assertThat(ddbEsmUuid).as("DynamoDB ESM UUID must have been captured in earlier test").isNotNull();
cfn.updateStack(UpdateStackRequest.builder()
.stackName(DDB_STACK_NAME)
.templateBody(ddbStackTemplate("""
"MaximumRetryAttempts": 5
"""))
.build());
assertThat(waitForTerminal(DDB_STACK_NAME, 30)).isEqualTo("UPDATE_COMPLETE");
GetEventSourceMappingResponse esm = lambda.getEventSourceMapping(r -> r.uuid(ddbEsmUuid));
assertThat(esm.uuid()).isEqualTo(ddbEsmUuid);
assertThat(esm.maximumRetryAttempts()).isEqualTo(5);
assertThat(esm.maximumRecordAgeInSeconds()).isNull();
assertThat(esm.bisectBatchOnFunctionError()).isNull();
assertThat(esm.destinationConfig() == null || esm.destinationConfig().onFailure() == null).isTrue();
}
@Test
@Order(8)
@DisplayName("DeleteStack removes the ESM")
void deleteStack_removesEsm() throws InterruptedException {
assertThat(esmUuid).as("ESM UUID must have been captured in earlier test").isNotNull();
@@ -161,6 +224,89 @@ class CloudFormationEventSourceMappingTest {
.isInstanceOf(software.amazon.awssdk.services.lambda.model.ResourceNotFoundException.class);
}
private static String sqsStackTemplate(String esmOptions) {
return """
{
"Resources": {
"MyQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "%s"
}
},
"MyFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Handler": "index.handler",
"Role": "%s",
"Code": {
"ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"
}
}
},
"MyESM": {
"Type": "AWS::Lambda::EventSourceMapping",
"Properties": {
"FunctionName": "%s",
"EventSourceArn": { "Fn::GetAtt": ["MyQueue", "Arn"] },
"Enabled": true,
"BatchSize": 5,
%s
}
}
}
}
""".formatted(QUEUE_NAME, FUNC_NAME, ROLE, FUNC_NAME, esmOptions);
}
private static String ddbStackTemplate(String esmOptions) {
return """
{
"Resources": {
"MyTable": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"BillingMode": "PAY_PER_REQUEST",
"AttributeDefinitions": [ { "AttributeName": "pk", "AttributeType": "S" } ],
"KeySchema": [ { "AttributeName": "pk", "KeyType": "HASH" } ],
"StreamSpecification": { "StreamViewType": "NEW_AND_OLD_IMAGES" }
}
},
"MyDlq": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "%s"
}
},
"MyFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Handler": "index.handler",
"Role": "%s",
"Code": {
"ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"
}
}
},
"MyESM": {
"Type": "AWS::Lambda::EventSourceMapping",
"Properties": {
"FunctionName": { "Ref": "MyFunction" },
"EventSourceArn": { "Fn::GetAtt": ["MyTable", "StreamArn"] },
"StartingPosition": "TRIM_HORIZON",
%s
}
}
}
}
""".formatted(DDB_TABLE_NAME, DLQ_NAME, DDB_FUNC_NAME, ROLE, esmOptions);
}
private String waitForTerminal(String stackName, int maxSeconds) throws InterruptedException {
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
while (System.currentTimeMillis() < deadline) {