Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Mario Toffia4abba5a218f8
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventSourceMappingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventSourceMappingTest.java
index 4437ecead5..57a256e155 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventSourceMappingTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventSourceMappingTest.java
@@ -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) {
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index da6712dbbe..40494b9540 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -128,7 +128,7 @@ cross-resource references.
| SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) |
| SNS | `Topic`, `Subscription`, `TopicPolicy` |
| DynamoDB | `Table`, `GlobalTable` |
-| Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig`, `MicrovmImage`, `NetworkConnector`, `Url`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
+| Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig`, `MicrovmImage`, `NetworkConnector`, `Url`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
| IAM | `Role`, `User` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
| Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` |
| SSM | `Parameter` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java
index e7279b2966..264a969369 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisioner.java
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -24,6 +26,11 @@ public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvis
private static final ObjectMapper MAPPER = new ObjectMapper();
+ // Options that update in place: omitting one from an UpdateStack template clears it.
+ private static final List<String> CLEARABLE_OPTIONS = List.of(
+ "MaximumBatchingWindowInSeconds", "MaximumRetryAttempts", "MaximumRecordAgeInSeconds",
+ "BisectBatchOnFunctionError", "FilterCriteria", "DestinationConfig", "ScalingConfig");
+
private final LambdaService lambdaService;
@Inject
@@ -61,14 +68,41 @@ public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvis
req.put("Enabled", Boolean.parseBoolean(enabledStr));
}
- String batchSize = ctx.resolveOptional(props, "BatchSize");
- if (batchSize != null) {
+ for (String name : List.of("BatchSize", "MaximumBatchingWindowInSeconds",
+ "MaximumRetryAttempts", "MaximumRecordAgeInSeconds")) {
+ putInteger(req, props, ctx, name);
+ }
+
+ String bisect = ctx.resolveOptional(props, "BisectBatchOnFunctionError");
+ if (bisect != null && !bisect.isEmpty()) {
+ if (!"true".equalsIgnoreCase(bisect) && !"false".equalsIgnoreCase(bisect)) {
+ throw new AwsException("ValidationError", "BisectBatchOnFunctionError must be a boolean", 400);
+ }
+ req.put("BisectBatchOnFunctionError", Boolean.parseBoolean(bisect));
+ }
+
+ for (String name : List.of("FilterCriteria", "DestinationConfig", "ScalingConfig")) {
+ if (props != null && props.has(name)) {
+ JsonNode resolved = ctx.engine().resolveNode(props.get(name));
+ if (resolved == null || resolved.isNull() || (resolved.isTextual() && resolved.textValue().isEmpty())) {
+ continue;
+ }
+ if (!resolved.isObject()) {
+ throw new AwsException("ValidationError", name + " must be an object", 400);
+ }
+ req.put(name, MAPPER.convertValue(withoutNoValue(resolved), Map.class));
+ }
+ }
+ if (req.get("ScalingConfig") instanceof Map<?, ?> scaling
+ && scaling.get("MaximumConcurrency") instanceof String concurrency) {
+ Map<Object, Object> coerced = new HashMap<>(scaling);
try {
- req.put("BatchSize", Integer.parseInt(batchSize));
+ coerced.put("MaximumConcurrency", Integer.parseInt(concurrency));
} catch (NumberFormatException e) {
throw new AwsException("ValidationError",
- "Value of property BatchSize must be an integer.", 400);
+ "Value of property ScalingConfig.MaximumConcurrency must be an integer.", 400);
}
+ req.put("ScalingConfig", coerced);
}
String startingPosition = ctx.resolveOptional(props, "StartingPosition");
@@ -116,6 +150,12 @@ public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvis
req.put("SourceAccessConfigurations", null);
}
+ if (ctx.isUpdate()) {
+ for (String name : CLEARABLE_OPTIONS) {
+ req.putIfAbsent(name, null);
+ }
+ }
+
if (ctx.isUpdate() && ctx.priorPhysicalId() != null) {
String uuid = ctx.priorPhysicalId();
EventSourceMapping existing = findExisting(uuid);
@@ -151,6 +191,50 @@ public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvis
}
}
+ private static void putInteger(Map<String, Object> req, JsonNode props, ProvisionContext ctx, String name) {
+ String value = ctx.resolveOptional(props, name);
+ if (value == null || value.isEmpty()) {
+ return;
+ }
+ try {
+ req.put(name, Integer.parseInt(value));
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError",
+ "Value of property " + name + " must be an integer.", 400);
+ }
+ }
+
+ /**
+ * Drops the empty text a nested {@code AWS::NoValue} resolves to, as CloudFormation removes such
+ * members. Returns null for an empty text node.
+ */
+ private static JsonNode withoutNoValue(JsonNode node) {
+ if (node.isTextual() && node.textValue().isEmpty()) {
+ return null;
+ }
+ if (node.isObject()) {
+ ObjectNode out = MAPPER.createObjectNode();
+ node.fields().forEachRemaining(e -> {
+ JsonNode value = withoutNoValue(e.getValue());
+ if (value != null) {
+ out.set(e.getKey(), value);
+ }
+ });
+ return out;
+ }
+ if (node.isArray()) {
+ ArrayNode out = MAPPER.createArrayNode();
+ for (JsonNode item : node) {
+ JsonNode value = withoutNoValue(item);
+ if (value != null) {
+ out.add(value);
+ }
+ }
+ return out;
+ }
+ return node;
+ }
+
private EventSourceMapping findExisting(String uuid) {
try {
return lambdaService.getEventSourceMapping(uuid);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java
index f6fd05fbcb..38049a54ce 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
@@ -17,6 +18,7 @@ import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -32,6 +34,10 @@ import static org.mockito.Mockito.when;
class LambdaEventSourceMappingCfnProvisionerTest {
+ private static final List<String> CLEARABLE_OPTIONS = List.of(
+ "MaximumBatchingWindowInSeconds", "MaximumRetryAttempts", "MaximumRecordAgeInSeconds",
+ "BisectBatchOnFunctionError", "FilterCriteria", "DestinationConfig", "ScalingConfig");
+
private final LambdaService lambdaService = mock(LambdaService.class);
private final LambdaEventSourceMappingCfnProvisioner provisioner =
new LambdaEventSourceMappingCfnProvisioner(lambdaService);
@@ -51,6 +57,10 @@ class LambdaEventSourceMappingCfnProvisionerTest {
if (node.isObject() && node.has("Ref")) {
return "resolved-" + node.get("Ref").asText();
}
+ if (node.isObject() && node.has("Fn::GetAtt")) {
+ JsonNode getAtt = node.get("Fn::GetAtt");
+ return "resolved-" + getAtt.get(0).asText() + "." + getAtt.get(1).asText();
+ }
return node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> resolveMockNode((JsonNode) inv.getArgument(0), engine));
@@ -89,7 +99,7 @@ class LambdaEventSourceMappingCfnProvisionerTest {
return node;
}
if (node.isObject()) {
- if (node.has("Ref")) {
+ if (node.has("Ref") || node.has("Fn::GetAtt")) {
return mapper.getNodeFactory().textNode(engine.resolve(node));
}
ObjectNode resolved = mapper.createObjectNode();
@@ -281,6 +291,269 @@ class LambdaEventSourceMappingCfnProvisionerTest {
assertEquals("Value of property BatchSize must be an integer.", ex.getMessage());
}
+ private Map<String, Object> provisionAndCaptureCreateRequest(ObjectNode props) {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("options-esm-uuid");
+ when(lambdaService.createEventSourceMapping(eq("us-east-1"), any())).thenReturn(esm);
+
+ provisioner.provision(r, props, ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).createEventSourceMapping(eq("us-east-1"), captor.capture());
+ return captor.getValue();
+ }
+
+ @Test
+ void provisionForwardsBatchingRetryAndStructureOptionsOnCreate() {
+ String pattern = "{\"body\":{\"kind\":[\"order\"]}}";
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:my-queue");
+ props.put("MaximumBatchingWindowInSeconds", 10);
+ props.put("MaximumRetryAttempts", 3);
+ props.put("MaximumRecordAgeInSeconds", 120);
+ props.put("BisectBatchOnFunctionError", true);
+ props.putObject("FilterCriteria").putArray("Filters").addObject().put("Pattern", pattern);
+ props.putObject("DestinationConfig").putObject("OnFailure")
+ .put("Destination", "arn:aws:sqs:us-east-1:000000000000:my-dlq");
+ props.putObject("ScalingConfig").put("MaximumConcurrency", 5);
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertEquals(Integer.valueOf(10), req.get("MaximumBatchingWindowInSeconds"));
+ assertEquals(Integer.valueOf(3), req.get("MaximumRetryAttempts"));
+ assertEquals(Integer.valueOf(120), req.get("MaximumRecordAgeInSeconds"));
+ assertEquals(Boolean.TRUE, req.get("BisectBatchOnFunctionError"));
+ assertEquals(Map.of("Filters", List.of(Map.of("Pattern", pattern))), req.get("FilterCriteria"));
+ assertEquals(Map.of("OnFailure", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:my-dlq")),
+ req.get("DestinationConfig"));
+ assertEquals(Map.of("MaximumConcurrency", 5), req.get("ScalingConfig"));
+ }
+
+ @Test
+ void provisionResolvesGetAttInDestinationConfig() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ ObjectNode getAtt = mapper.createObjectNode();
+ getAtt.set("Fn::GetAtt", mapper.createArrayNode().add("MyDlq").add("Arn"));
+ props.putObject("DestinationConfig").putObject("OnFailure").set("Destination", getAtt);
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertEquals(Map.of("OnFailure", Map.of("Destination", "resolved-MyDlq.Arn")), req.get("DestinationConfig"));
+ }
+
+ @Test
+ void provisionOmitsAbsentOptionsOnCreate() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:my-queue");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ for (String option : CLEARABLE_OPTIONS) {
+ assertFalse(req.containsKey(option), option + " must not be sent when absent");
+ }
+ }
+
+ @Test
+ void provisionTreatsNoValueStructureAsAbsentOnCreate() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("DestinationConfig", "");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertFalse(req.containsKey("DestinationConfig"));
+ }
+
+ @Test
+ void provisionClearsNoValueStructureOnUpdate() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("DestinationConfig", "");
+
+ provisioner.provision(r, props, ctx(true, "existing-esm-uuid"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).updateEventSourceMapping(eq("existing-esm-uuid"), captor.capture());
+ assertTrue(captor.getValue().containsKey("DestinationConfig"));
+ assertNull(captor.getValue().get("DestinationConfig"));
+ }
+
+ @Test
+ void provisionTreatsNoValueScalarsAsAbsentOnCreate() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("MaximumRetryAttempts", "");
+ props.put("BisectBatchOnFunctionError", "");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertFalse(req.containsKey("MaximumRetryAttempts"));
+ assertFalse(req.containsKey("BisectBatchOnFunctionError"));
+ }
+
+ @Test
+ void provisionRejectsWhitespaceBatchSize() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("BatchSize", " ");
+
+ AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Value of property BatchSize must be an integer.", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsNonBooleanBisectBatchOnFunctionError() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("BisectBatchOnFunctionError", "yes");
+
+ AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("BisectBatchOnFunctionError must be a boolean", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsNonObjectDestinationConfig() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("DestinationConfig", "arn:aws:sqs:us-east-1:000000000000:my-dlq");
+
+ AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("DestinationConfig must be an object", ex.getMessage());
+ }
+
+ @Test
+ void provisionKeepsWhitespaceMemberForLambdaValidation() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.putObject("DestinationConfig").put("OnFailure", " ");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertEquals(Map.of("OnFailure", " "), req.get("DestinationConfig"));
+ }
+
+ @Test
+ void provisionDropsNestedNoValueFromDestinationConfig() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.putObject("DestinationConfig").put("OnFailure", "");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ // LambdaService treats a DestinationConfig without OnFailure as no destination.
+ assertEquals(Map.of(), req.get("DestinationConfig"));
+ }
+
+ @Test
+ void provisionDropsNoValueFilterElement() {
+ String pattern = "{\"body\":{\"kind\":[\"order\"]}}";
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ ArrayNode filters = props.putObject("FilterCriteria").putArray("Filters");
+ filters.addObject().put("Pattern", pattern);
+ filters.add("");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertEquals(Map.of("Filters", List.of(Map.of("Pattern", pattern))), req.get("FilterCriteria"));
+ }
+
+ @Test
+ void provisionDropsNestedNoValueMaximumConcurrency() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("EventSourceArn", "arn:aws:sqs:us-east-1:000000000000:my-queue");
+ props.putObject("ScalingConfig").put("MaximumConcurrency", "");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ // LambdaService treats an empty ScalingConfig on an SQS mapping as clearing the cap.
+ assertEquals(Map.of(), req.get("ScalingConfig"));
+ }
+
+ @Test
+ void provisionCoercesTextMaximumConcurrencyToInteger() {
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.putObject("ScalingConfig").put("MaximumConcurrency", "5");
+
+ Map<String, Object> req = provisionAndCaptureCreateRequest(props);
+
+ assertEquals(Map.of("MaximumConcurrency", 5), req.get("ScalingConfig"));
+ }
+
+ @Test
+ void provisionRejectsInvalidMaximumConcurrency() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.putObject("ScalingConfig").put("MaximumConcurrency", "many");
+
+ AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Value of property ScalingConfig.MaximumConcurrency must be an integer.", ex.getMessage());
+ }
+
+ @Test
+ void provisionRejectsInvalidMaximumRetryAttempts() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+ props.put("MaximumRetryAttempts", "not-a-number");
+
+ AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", ex.getErrorCode());
+ assertEquals("Value of property MaximumRetryAttempts must be an integer.", ex.getMessage());
+ }
+
+ @Test
+ void provisionUpdateClearsRemovedBatchingRetryAndStructureOptions() {
+ StackResource r = new StackResource();
+ r.setResourceType("AWS::Lambda::EventSourceMapping");
+ r.setPhysicalId("existing-esm-uuid");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("FunctionName", "my-function");
+
+ provisioner.provision(r, props, ctx(true, "existing-esm-uuid"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(lambdaService).updateEventSourceMapping(eq("existing-esm-uuid"), captor.capture());
+ Map<String, Object> req = captor.getValue();
+ for (String option : CLEARABLE_OPTIONS) {
+ assertTrue(req.containsKey(option), option + " must be sent so the update clears it");
+ assertNull(req.get(option), option + " must be cleared");
+ }
+ }
+
@Test
void provisionUpdatesClearsSourceAccessConfigurationsWhenRemoved() {
StackResource r = new StackResource();
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index 4cfcb52c31..03335416de 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -152,7 +152,7 @@ notes:
AWS::S3::BucketPolicy: document stored on the bucket; S3 does not evaluate it
AWS::SQS::QueuePolicy: accepted; policy not enforced
AWS::Lambda::Function: Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket
- AWS::Lambda::EventSourceMapping: SQS, Kinesis, DynamoDB Streams
+ AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored'
AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands into
AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported
AWS::RDS::DBInstance: starts a real container