Light, fluffy, and always free - The AWS Local Emulator alternative
feat(stepfunctions): route RDS Data execute statement (#4179)
vamsiakffe56f735de1
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.mdindex 0132943ee9..14791a8c01 100644--- a/docs/services/step-functions.md+++ b/docs/services/step-functions.md@@ -435,6 +435,7 @@ the wire and the task fails with `Sfn.StateMachineDoesNotExistException`.| `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | execution envelope | `Sfn.StateMachineTypeNotSupportedException` for a Standard child || `arn:aws:states:::aws-sdk:sfn:sendTaskSuccess` | `{}` | `Sfn.InvalidTokenException` when no task is waiting on the token || `arn:aws:states:::aws-sdk:sfn:sendTaskFailure` | `{}` | `Sfn.InvalidTokenException` |+| `arn:aws:states:::aws-sdk:rdsdata:executeStatement` | RDS Data statement result | `RdsData.BadRequestException` for an invalid request || `arn:aws:states:::aws-sdk:scheduler:createSchedule` | `{ScheduleArn}` | `Scheduler.ConflictException` when the name is taken || `arn:aws:states:::aws-sdk:scheduler:updateSchedule` | `{ScheduleArn}` | `Scheduler.ResourceNotFoundException` || `arn:aws:states:::aws-sdk:scheduler:deleteSchedule` | `{}` | `Scheduler.ResourceNotFoundException` |@@ -449,6 +450,11 @@ field. Textual JSON remains unchanged, and malformed text reaches the existing Stoken nobody is waiting for fails the calling task rather than reporting a delivery that neverhappened.+`rdsdata:executeStatement` uses the existing RDS Data API implementation. Task arguments use SDK+PascalCase names such as `ResourceArn`, `SecretArn`, `Sql` and `Parameters`; the adapter translates+them to the direct API shape and returns a recursively PascalCase result. Other RDS Data actions are+not routed through Step Functions yet.+## Publishing to SNS`arn:aws:states:::sns:publish` calls the SNS Publish API with the task's parameters and returns thediff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.javaindex 312d61211f..06d119eb7a 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;import io.github.hectorvent.floci.services.lambda.model.InvocationType;import io.github.hectorvent.floci.services.lambda.model.InvokeResult;import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import io.github.hectorvent.floci.services.rdsdata.RdsDataService;import io.github.hectorvent.floci.services.s3.model.S3Object;import io.github.hectorvent.floci.services.sns.SnsJsonHandler;import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;@@ -182,6 +183,7 @@ public class AslExecutor {Set.of("MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512");private static final String QUERY_LANGUAGE_JSONATA = "JSONata";+ private static final String AWS_SDK_RDS_DATA_PREFIX = "arn:aws:states:::aws-sdk:rdsdata:";private static final String AWS_SDK_SFN_PREFIX = "arn:aws:states:::aws-sdk:sfn:";private static final String AWS_SDK_SCHEDULER_PREFIX = "arn:aws:states:::aws-sdk:scheduler:";@@ -243,6 +245,7 @@ public class AslExecutor {private final EventBridgeHandler eventBridgeHandler;private final SchedulerService schedulerService;private final SchedulerController schedulerController;+ private final RdsDataService rdsDataService;private final ObjectMapper objectMapper;private final Configuration jsonPathConfiguration;private final JsonataEvaluator jsonataEvaluator;@@ -269,14 +272,14 @@ public class AslExecutor {Ec2Service ec2Service, S3Service s3Service,EcsService ecsService, EcsJsonHandler ecsJsonHandler,EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,- SchedulerController schedulerController,+ SchedulerController schedulerController, RdsDataService rdsDataService,ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,CustomResourceLiveness customResourceLiveness) {this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler,sqsJsonHandler, snsJsonHandler, cloudFormationHandler,ec2Service, s3Service, ecsService, ecsJsonHandler,- eventBridgeHandler, schedulerService, schedulerController,+ eventBridgeHandler, schedulerService, schedulerController, rdsDataService,objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null);}@@ -288,7 +291,7 @@ public class AslExecutor {Ec2Service ec2Service, S3Service s3Service,EcsService ecsService, EcsJsonHandler ecsJsonHandler,EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,- SchedulerController schedulerController,+ SchedulerController schedulerController, RdsDataService rdsDataService,ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,CustomResourceLiveness customResourceLiveness,@@ -308,6 +311,7 @@ public class AslExecutor {this.eventBridgeHandler = eventBridgeHandler;this.schedulerService = schedulerService;this.schedulerController = schedulerController;+ this.rdsDataService = rdsDataService;this.objectMapper = objectMapper;this.jsonPathConfiguration = objectMapper == null? null@@ -330,12 +334,49 @@ public class AslExecutor {}}+ AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,+ DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler,+ SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,+ CloudFormationQueryHandler cloudFormationHandler,+ Ec2Service ec2Service, S3Service s3Service,+ EcsService ecsService, EcsJsonHandler ecsJsonHandler,+ EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,+ SchedulerController schedulerController,+ ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,+ Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,+ CustomResourceLiveness customResourceLiveness,+ Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) {+ this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler,+ sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service,+ ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService,+ schedulerController, null, objectMapper, jsonataEvaluator, sfnService, config,+ vertx, customResourceLiveness, clock, sleeper, maxWaitSecondsOverride);+ }+/** Test seam: lets Wait states be exercised without real time passing. */@FunctionalInterfaceinterface Sleeper {void sleep(long nanos) throws InterruptedException;}+ AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,+ DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler,+ SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,+ CloudFormationQueryHandler cloudFormationHandler,+ Ec2Service ec2Service, S3Service s3Service,+ EcsService ecsService, EcsJsonHandler ecsJsonHandler,+ EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,+ SchedulerController schedulerController,+ ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,+ Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,+ CustomResourceLiveness customResourceLiveness) {+ this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler,+ sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service,+ ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService,+ schedulerController, null, objectMapper, jsonataEvaluator, sfnService, config,+ vertx, customResourceLiveness);+ }+@PreDestroyvoid stop() {executor.shutdownNow();@@ -1074,6 +1115,13 @@ public class AslExecutor {return invokeAwsSdkDynamoDb(camelCaseAction, input, region);}+ // AWS SDK service integration: RDS Data API ExecuteStatement+ if (resource.startsWith(AWS_SDK_RDS_DATA_PREFIX)) {+ String action = resource.substring(AWS_SDK_RDS_DATA_PREFIX.length());+ String region = extractRegionFromArn(sm.getStateMachineArn());+ return invokeAwsSdkRdsData(action, input, region);+ }+// SQS optimized integrationif (resource.equals("arn:aws:states:::sqs:sendMessage")) {String region = extractRegionFromArn(sm.getStateMachineArn());@@ -2008,6 +2056,20 @@ public class AslExecutor {return objectMapper.createObjectNode();}+ private JsonNode invokeAwsSdkRdsData(String action, JsonNode input, String region) {+ if (!"executeStatement".equals(action)) {+ throw new FailStateException("States.TaskFailed",+ "Unsupported resource: " + AWS_SDK_RDS_DATA_PREFIX + action);+ }+ try {+ JsonNode request = recaseKeys(objectMapper, input, false);+ JsonNode response = rdsDataService.executeStatement(request, region);+ return recaseKeys(objectMapper, response, true);+ } catch (AwsException e) {+ throw new FailStateException(sdkExceptionName("RdsData", e.getErrorCode()), e.getMessage());+ }+ }+private JsonNode invokeOptimizedSqsSendMessage(JsonNode input, String region) {ObjectNode request = normalizeSqsSendMessageInput(input);return invokeSqsAction("SendMessage", request, region, "SQS.");diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsRdsDataIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsRdsDataIntegrationTest.javanew file mode 100644index 0000000000..fa3917bad8--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsRdsDataIntegrationTest.java@@ -0,0 +1,264 @@+package io.github.hectorvent.floci.services.stepfunctions;++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.rdsdata.RdsDataService;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.InjectMock;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++@QuarkusTest+class StepFunctionsRdsDataIntegrationTest {++ private static final String CONTENT_TYPE = "application/x-amz-json-1.0";+ private static final String RESOURCE = "arn:aws:states:::aws-sdk:rdsdata:executeStatement";+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();++ @InjectMock+ RdsDataService rdsDataService;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @BeforeEach+ void stubExecuteStatement() {+ when(rdsDataService.executeStatement(any(JsonNode.class), anyString())).thenAnswer(invocation -> {+ JsonNode request = invocation.getArgument(0);+ if ("fail".equals(request.path("sql").asText())) {+ throw new AwsException("BadRequestException", "synthetic failure", 400);+ }++ ObjectNode response = OBJECT_MAPPER.createObjectNode();+ ArrayNode records = response.putArray("records");+ ArrayNode row = records.addArray();+ row.addObject().put("longValue", request.path("parameters").path(0)+ .path("value").path("longValue").asLong());+ row.addObject().put("stringValue", "quoted \"value\"");+ response.putArray("columnMetadata")+ .addObject()+ .put("name", "id")+ .put("typeName", "BIGINT");+ response.put("numberOfRecordsUpdated", 0);+ return response;+ });+ }++ @Test+ void jsonataArgumentsReachRdsDataAndReturnSdkFieldCasing() throws Exception {+ String definition = """+ {+ "QueryLanguage": "JSONata",+ "StartAt": "Execute",+ "States": {+ "Execute": {+ "Type": "Task",+ "Resource": "RESOURCE",+ "Arguments": {+ "ResourceArn": "arn:aws:rds:us-east-1:000000000000:cluster:test",+ "SecretArn": "arn:aws:secretsmanager:us-east-1:000000000000:secret:test",+ "Database": "app",+ "Sql": "select :id",+ "Parameters": [{"Name": "id", "Value": {"LongValue": 7}}],+ "IncludeResultMetadata": true+ },+ "End": true+ }+ }+ }+ """.replace("RESOURCE", RESOURCE);++ JsonNode result = OBJECT_MAPPER.readTree(succeedingOutput(definition, "{}"));+ assertEquals(7, result.path("Records").path(0).path(0).path("LongValue").asInt());+ assertEquals("quoted \"value\"",+ result.path("Records").path(0).path(1).path("StringValue").asText());+ assertEquals("BIGINT", result.path("ColumnMetadata").path(0).path("TypeName").asText());+ assertEquals(0, result.path("NumberOfRecordsUpdated").asInt());+ assertTrue(result.path("records").isMissingNode());++ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);+ verify(rdsDataService).executeStatement(request.capture(), anyString());+ assertEquals("select :id", request.getValue().path("sql").asText());+ assertEquals(7, request.getValue().path("parameters").path(0)+ .path("value").path("longValue").asInt());+ assertTrue(request.getValue().path("includeResultMetadata").asBoolean());+ }++ @Test+ void jsonPathParametersUseExecutionInputAndExecutionRegion() throws Exception {+ String definition = """+ {+ "StartAt": "Execute",+ "States": {+ "Execute": {+ "Type": "Task",+ "Resource": "RESOURCE",+ "Parameters": {+ "ResourceArn.$": "$.resourceArn",+ "SecretArn.$": "$.secretArn",+ "Sql.$": "$.sql",+ "Parameters.$": "$.parameters"+ },+ "End": true+ }+ }+ }+ """.replace("RESOURCE", RESOURCE);+ String input = """+ {+ "resourceArn": "arn:aws:rds:us-east-1:000000000000:cluster:test",+ "secretArn": "arn:aws:secretsmanager:us-east-1:000000000000:secret:test",+ "sql": "select :id",+ "parameters": [{"Name": "id", "Value": {"LongValue": 11}}]+ }+ """;++ JsonNode result = OBJECT_MAPPER.readTree(succeedingOutput(definition, input));+ assertEquals(11, result.path("Records").path(0).path(0).path("LongValue").asInt());++ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);+ ArgumentCaptor<String> region = ArgumentCaptor.forClass(String.class);+ verify(rdsDataService).executeStatement(request.capture(), region.capture());+ assertEquals("select :id", request.getValue().path("sql").asText());+ assertEquals(11, request.getValue().path("parameters").path(0)+ .path("value").path("longValue").asInt());+ assertEquals("us-east-1", region.getValue());+ }++ @Test+ void serviceFailureCanBeCaughtByItsSdkExceptionName() throws Exception {+ String definition = """+ {+ "QueryLanguage": "JSONata",+ "StartAt": "Execute",+ "States": {+ "Execute": {+ "Type": "Task",+ "Resource": "RESOURCE",+ "Arguments": {"Sql": "fail"},+ "Catch": [{+ "ErrorEquals": ["RdsData.BadRequestException"],+ "Next": "Recovered",+ "Output": {"Error": "{% $states.errorOutput.Error %}"}+ }],+ "End": true+ },+ "Recovered": {"Type": "Pass", "End": true}+ }+ }+ """.replace("RESOURCE", RESOURCE);++ JsonNode result = OBJECT_MAPPER.readTree(succeedingOutput(definition, "{}"));+ assertEquals("RdsData.BadRequestException", result.path("Error").asText());+ }++ @Test+ void unsupportedRdsDataActionFailsWithoutCallingTheService() {+ String definition = """+ {+ "StartAt": "Execute",+ "States": {+ "Execute": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:rdsdata:beginTransaction",+ "Parameters": {},+ "End": true+ }+ }+ }+ """;++ Response describe = terminalExecution(definition, "{}");+ assertEquals("FAILED", describe.jsonPath().getString("status"));+ assertEquals("States.TaskFailed", describe.jsonPath().getString("error"));+ verify(rdsDataService, never()).executeStatement(any(JsonNode.class), anyString());+ }++ private static String succeedingOutput(String definition, String input) {+ Response describe = terminalExecution(definition, input);+ assertEquals("SUCCEEDED", describe.jsonPath().getString("status"),+ "cause: " + describe.jsonPath().getString("cause"));+ return describe.jsonPath().getString("output");+ }++ private static Response terminalExecution(String definition, String input) {+ String stateMachineArn = createStateMachine(definition);+ String executionArn = startExecution(stateMachineArn, input);+ for (int i = 0; i < 150; i++) {+ Response response = describeExecution(executionArn);+ if (!"RUNNING".equals(response.jsonPath().getString("status"))) {+ return response;+ }+ try {+ Thread.sleep(100);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ fail("Interrupted while waiting for execution " + executionArn);+ }+ }+ fail("Execution did not complete within timeout: " + executionArn);+ return null;+ }++ private static String createStateMachine(String definition) {+ Response response = given()+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")+ .contentType(CONTENT_TYPE)+ .body("""+ {"name": "rdsdata-%s", "roleArn": "%s", "definition": %s}+ """.formatted(System.nanoTime(), ROLE_ARN, quote(definition)))+ .when().post("/");+ response.then().statusCode(200);+ return response.jsonPath().getString("stateMachineArn");+ }++ private static String startExecution(String stateMachineArn, String input) {+ Response response = given()+ .header("X-Amz-Target", "AWSStepFunctions.StartExecution")+ .contentType(CONTENT_TYPE)+ .body("""+ {"stateMachineArn": "%s", "input": %s}+ """.formatted(stateMachineArn, quote(input)))+ .when().post("/");+ response.then().statusCode(200);+ return response.jsonPath().getString("executionArn");+ }++ private static Response describeExecution(String executionArn) {+ return given()+ .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")+ .contentType(CONTENT_TYPE)+ .body("{\"executionArn\":\"%s\"}".formatted(executionArn))+ .when().post("/");+ }++ private static String quote(String raw) {+ return "\"" + raw+ .replace("\\", "\\\\")+ .replace("\"", "\\\"")+ .replace("\n", "\\n")+ .replace("\r", "\\r")+ .replace("\t", "\\t")+ + "\"";+ }+}