Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): support AWS::Lambda::EventSourceMapping resource type (#654)
Hector Ventura37c7969cb4a1
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.javanew file mode 100644index 0000000000..4437ecead5--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventSourceMappingTest.java@@ -0,0 +1,201 @@+package com.floci.test;++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.ListEventSourceMappingsResponse;+import software.amazon.awssdk.services.sqs.SqsClient;++import java.util.List;++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.+ */+@DisplayName("CloudFormation AWS::Lambda::EventSourceMapping")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class CloudFormationEventSourceMappingTest {++ private static final String STACK_NAME = "compat-cfn-esm-stack";+ private static final String FUNC_NAME = "compat-cfn-esm-func";+ private static final String QUEUE_NAME = "compat-cfn-esm-queue";+ private static final String ROLE = "arn:aws:iam::000000000000:role/cfn-lambda-role";+ private static final String ACCOUNT = "000000000000";+ private static final String REGION = "us-east-1";++ private static CloudFormationClient cfn;+ private static LambdaClient lambda;+ private static SqsClient sqs;++ private static String esmUuid;++ @BeforeAll+ static void setup() {+ cfn = TestFixtures.cloudFormationClient();+ lambda = TestFixtures.lambdaClient();+ sqs = TestFixtures.sqsClient();+ }++ @AfterAll+ static void cleanup() {+ try {+ if (cfn != null) {+ cfn.deleteStack(DeleteStackRequest.builder().stackName(STACK_NAME).build());+ }+ } catch (Exception ignored) {}+ if (cfn != null) cfn.close();+ if (lambda != null) lambda.close();+ if (sqs != null) sqs.close();+ }++ @Test+ @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);++ cfn.createStack(CreateStackRequest.builder()+ .stackName(STACK_NAME)+ .templateBody(template)+ .build());++ String status = waitForTerminal(STACK_NAME, 30);+ assertThat(status).isEqualTo("CREATE_COMPLETE");+ }++ @Test+ @Order(2)+ @DisplayName("ESM resource appears in DescribeStackResources with CREATE_COMPLETE")+ void esmResourceIsComplete() {+ List<StackResource> resources = cfn.describeStackResources(+ DescribeStackResourcesRequest.builder().stackName(STACK_NAME).build()+ ).stackResources();++ StackResource esmResource = resources.stream()+ .filter(r -> "AWS::Lambda::EventSourceMapping".equals(r.resourceType()))+ .findFirst()+ .orElseThrow(() -> new AssertionError("No EventSourceMapping resource found"));++ assertThat(esmResource.resourceStatusAsString()).isEqualTo("CREATE_COMPLETE");+ assertThat(esmResource.physicalResourceId()).isNotBlank();++ esmUuid = esmResource.physicalResourceId();+ }++ @Test+ @Order(3)+ @DisplayName("ListEventSourceMappings returns ESM linked to the Lambda function")+ void esmAppearsInLambdaList() {+ ListEventSourceMappingsResponse resp = lambda.listEventSourceMappings(+ r -> r.functionName(FUNC_NAME));++ assertThat(resp.eventSourceMappings()).isNotEmpty();++ boolean found = resp.eventSourceMappings().stream()+ .anyMatch(e -> e.functionArn().contains(FUNC_NAME)+ && e.eventSourceArn().contains(QUEUE_NAME));+ assertThat(found).as("ESM for queue %s not found in listing", QUEUE_NAME).isTrue();+ }++ @Test+ @Order(4)+ @DisplayName("GetEventSourceMapping by UUID matches the created ESM")+ void getEventSourceMappingByUuid() {+ assertThat(esmUuid).as("ESM UUID must have been captured in earlier test").isNotNull();++ var 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");+ }++ @Test+ @Order(5)+ @DisplayName("DeleteStack removes the ESM")+ void deleteStack_removesEsm() throws InterruptedException {+ assertThat(esmUuid).as("ESM UUID must have been captured in earlier test").isNotNull();++ cfn.deleteStack(DeleteStackRequest.builder().stackName(STACK_NAME).build());+ waitForDeleted(STACK_NAME, 30);++ assertThatThrownBy(() -> lambda.getEventSourceMapping(r -> r.uuid(esmUuid)))+ .isInstanceOf(software.amazon.awssdk.services.lambda.model.ResourceNotFoundException.class);+ }++ private String waitForTerminal(String stackName, int maxSeconds) throws InterruptedException {+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;+ while (System.currentTimeMillis() < deadline) {+ List<Stack> stacks = cfn.describeStacks(+ DescribeStacksRequest.builder().stackName(stackName).build()+ ).stacks();+ if (!stacks.isEmpty()) {+ String status = stacks.get(0).stackStatusAsString();+ if (!status.endsWith("_IN_PROGRESS")) {+ return status;+ }+ }+ Thread.sleep(500);+ }+ throw new AssertionError("Stack " + stackName + " did not reach terminal state within " + maxSeconds + "s");+ }++ private void waitForDeleted(String stackName, int maxSeconds) throws InterruptedException {+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;+ while (System.currentTimeMillis() < deadline) {+ try {+ List<Stack> stacks = cfn.describeStacks(+ DescribeStacksRequest.builder().stackName(stackName).build()+ ).stacks();+ if (stacks.isEmpty() || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {+ return;+ }+ } catch (CloudFormationException e) {+ if (e.getMessage() != null && e.getMessage().contains("does not exist")) {+ return;+ }+ throw e;+ }+ Thread.sleep(500);+ }+ throw new AssertionError("Stack " + stackName + " was not deleted within " + maxSeconds + "s");+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex 6501c9fef8..0db25471dc 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -136,6 +136,8 @@ public class CloudFormationResourceProvisioner {case "AWS::ApiGatewayV2::Stage" -> provisionApiGatewayV2Stage(resource, properties, engine, region);case "AWS::ApiGatewayV2::Deployment" -> provisionApiGatewayV2Deployment(resource, properties, engine, region);case "AWS::Pipes::Pipe" -> provisionPipe(resource, properties, engine, region, stackName);+ case "AWS::Lambda::EventSourceMapping" ->+ provisionLambdaEventSourceMapping(resource, properties, engine, region);default -> {LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId);resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));@@ -174,6 +176,7 @@ public class CloudFormationResourceProvisioner {case "AWS::ECR::Repository" ->ecrService.deleteRepository(physicalId, null, true, "us-east-1");case "AWS::Pipes::Pipe" -> pipesService.deletePipe(physicalId, region);+ case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);}} catch (Exception e) {@@ -739,6 +742,29 @@ public class CloudFormationResourceProvisioner {}}+ // ── Lambda EventSourceMapping ─────────────────────────────────────────────++ private void provisionLambdaEventSourceMapping(StackResource r, JsonNode props,+ CloudFormationTemplateEngine engine, String region) {+ Map<String, Object> req = new HashMap<>();+ req.put("FunctionName", resolveOptional(props, "FunctionName", engine));+ req.put("EventSourceArn", resolveOptional(props, "EventSourceArn", engine));++ String enabledStr = resolveOptional(props, "Enabled", engine);+ if (enabledStr != null) {+ req.put("Enabled", Boolean.parseBoolean(enabledStr));+ }++ String batchSize = resolveOptional(props, "BatchSize", engine);+ if (batchSize != null) {+ try { req.put("BatchSize", Integer.parseInt(batchSize)); } catch (NumberFormatException ignored) {}+ }++ var esm = lambdaService.createEventSourceMapping(region, req);+ r.setPhysicalId(esm.getUuid());+ r.getAttributes().put("Id", esm.getUuid());+ }+// ── Pipes ──────────────────────────────────────────────────────────────────private void provisionPipe(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.javaindex 09988de44d..eb5decea6e 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java@@ -2390,4 +2390,126 @@ class CloudFormationIntegrationTest {.then().statusCode(200);}++ @Test+ void createStack_lambdaEventSourceMapping() throws Exception {+ String stackName = "cfn-esm-stack";+ String funcName = "cfn-esm-func";+ String queueName = "cfn-esm-queue";++ 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": "arn:aws:iam::000000000000:role/lambda-role",+ "Code": {+ "ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"+ }+ }+ },+ "MyESM": {+ "Type": "AWS::Lambda::EventSourceMapping",+ "Properties": {+ "FunctionName": { "Ref": "MyFunction" },+ "EventSourceArn": { "Fn::GetAtt": ["MyQueue", "Arn"] },+ "Enabled": true,+ "BatchSize": 5+ }+ }+ }+ }+ """.formatted(queueName, funcName);++ // 1. Create stack+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackId>"));++ // 2. Stack must reach CREATE_COMPLETE+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ // 3. ESM resource must be present with CREATE_COMPLETE+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("AWS::Lambda::EventSourceMapping"))+ .body(containsString("CREATE_COMPLETE"));++ // 4. Lambda list-event-source-mappings must return our ESM; extract UUID from JSON+ String esmJson = given()+ .when()+ .get("/2015-03-31/event-source-mappings?FunctionName=" + funcName)+ .then()+ .statusCode(200)+ .body(containsString(funcName))+ .extract().body().asString();++ JsonNode esmList = OBJECT_MAPPER.readTree(esmJson);+ String esmUuid = esmList.path("EventSourceMappings").get(0).path("UUID").asText();++ // 5. Delete stack and verify ESM is gone+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // Wait for async stack deletion to complete+ long deadline = System.currentTimeMillis() + 10_000;+ while (System.currentTimeMillis() < deadline) {+ String deleteStatus = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .extract().body().asString();+ if (deleteStatus.contains("DELETE_COMPLETE") || deleteStatus.contains("does not exist")) {+ break;+ }+ Thread.sleep(200);+ }++ given()+ .when()+ .get("/2015-03-31/event-source-mappings/" + esmUuid)+ .then()+ .statusCode(404);+ }+}