feat(redshift): run Data API statements from Step Functions and Scheduler (#5312)

* feat(redshift): run Data API statements from Step Functions and Scheduler

Step Functions: add the arn:aws:states:::aws-sdk:redshiftdata:<action> Task
integration. It reuses RedshiftDataJsonHandler, so every Data API action
Floci implements works for provisioned clusters (ClusterIdentifier) and
Serverless workgroups (WorkgroupName). Arguments and results keep the wire
PascalCase names, CreatedAt and UpdatedAt are ISO-8601 at any depth, errors
surface as RedshiftData.<Code>Exception, and the task fails when redshift
or redshift-data is disabled. .sync resources are rejected, as AWS has no
such variant.

Scheduler: add the redshiftdata:executeStatement and
redshiftdata:batchExecuteStatement universal targets. The call runs as the
schedule's account and region, because the dispatcher thread carries no
request account and cluster and statement storage is account-aware. A SQL
error stays on the statement; a request the Data API rejects propagates so
the existing retry and dead-letter handling applies.

* fix(redshift-data): validate task input and isolate statement storage by account

* fix(redshift): run scheduled Data API statements off the dispatcher thread

Keep the request check on the dispatcher so a rejected request still
retries, and run the SQL on its own thread under the schedule's account.
Ask ServiceRegistry whether redshift-data is enabled instead of repeating
the rule, keep the resolver and connection factory package-private, and
cover the provisioned-cluster account in the resolver test.

* fix(scheduler): await scheduled Redshift Data statement in docker test
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-09 15:51:11 -04:00
1 parent 07b529e150
commit 1a6f336e9f
13 files changed
+1291 -16

No files matched your search

@@ -180,7 +180,7 @@ class RedshiftDataResourceResolver {
private String clusterArn(String clusterId, String region) {
String r = (region == null || region.isBlank()) ? regionResolver.getDefaultRegion() : region;
return AwsArnUtils.Arn.of("redshift", r, "000000000000", "cluster:" + clusterId).toString();
return AwsArnUtils.Arn.of("redshift", r, regionResolver.getAccountId(), "cluster:" + clusterId).toString();
}
private static AwsException validation(String message) {
@@ -67,6 +67,23 @@ public class RedshiftDataService implements Resettable {
// ── ExecuteStatement ────────────────────────────────────────────────────
public ObjectNode executeStatement(JsonNode request, String region) {
PendingStatement pending = prepareStatement(request, region);
pending.run().run();
return executeResponse(pending.statement());
}
/**
* Validates and resolves the request on the calling thread, so a rejected request throws here,
* and returns the SQL run for the caller to schedule. The statement is stored as {@code STARTED}
* first, as AWS does, so DescribeStatement can see it while the run is in flight.
*/
public Runnable submitStatement(JsonNode request, String region) {
PendingStatement pending = prepareStatement(request, region);
store.put(pending.statement());
return pending.run();
}
private PendingStatement prepareStatement(JsonNode request, String region) {
String sql = requiredText(request, "Sql");
rejectMultiStatement(sql);
Map<String, String> parameters = RedshiftDataSqlParameters.parseParameters(request, "Parameters");
@@ -82,11 +99,14 @@ public class RedshiftDataService implements Resettable {
stored.database = target.database();
stored.resultFormat = request.path("ResultFormat").asText("JSON");
runStatement(stored, target, sql, parameters);
store.put(stored);
return executeResponse(stored);
return new PendingStatement(stored, () -> {
runStatement(stored, target, sql, parameters);
store.put(stored);
});
}
private record PendingStatement(RedshiftDataStatementStore.StoredStatement statement, Runnable run) { }
private void runStatement(RedshiftDataStatementStore.StoredStatement stored,
RedshiftDataResourceResolver.DatabaseTarget target,
String sql, Map<String, String> parameters) {
@@ -316,6 +336,19 @@ public class RedshiftDataService implements Resettable {
// ── BatchExecuteStatement ──────────────────────────────────────────────
public ObjectNode batchExecuteStatement(JsonNode request, String region) {
PendingStatement pending = prepareBatch(request, region);
pending.run().run();
return executeResponse(pending.statement());
}
/** Batch counterpart of {@link #submitStatement}. */
public Runnable submitBatch(JsonNode request, String region) {
PendingStatement pending = prepareBatch(request, region);
store.put(pending.statement());
return pending.run();
}
private PendingStatement prepareBatch(JsonNode request, String region) {
JsonNode sqlsNode = request.get("Sqls");
if (sqlsNode == null || !sqlsNode.isArray() || sqlsNode.isEmpty()) {
throw new AwsException("ValidationException", "Sqls must be a non-empty array of SQL statements.", 400);
@@ -338,6 +371,11 @@ public class RedshiftDataService implements Resettable {
parent.resultFormat = request.path("ResultFormat").asText("JSON");
parent.subStatements = new ArrayList<>();
return new PendingStatement(parent, () -> runBatch(parent, sqls, target));
}
private void runBatch(RedshiftDataStatementStore.StoredStatement parent, List<String> sqls,
RedshiftDataResourceResolver.DatabaseTarget target) {
long totalDuration = 0;
try (Connection connection = connectionFactory.open(target)) {
BackendSql batchBackend = new RedshiftDataBackendSql(connection);
@@ -411,7 +449,6 @@ public class RedshiftDataService implements Resettable {
parent.durationNanos = totalDuration;
parent.updatedAt = Instant.now();
store.put(parent);
return executeResponse(parent);
}
// ── ListStatements ─────────────────────────────────────────────────────
@@ -6,11 +6,13 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
import io.github.hectorvent.floci.services.scheduler.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.scheduler.model.EcsParameters;
import io.github.hectorvent.floci.services.scheduler.model.EventBridgeParameters;
@@ -21,6 +23,7 @@ import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -34,12 +37,17 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
/**
* Delivers an EventBridge Scheduler target invocation to the underlying service.
* Supports templated SQS, Lambda, SNS, Step Functions, and EventBridge PutEvents targets, plus
* universal targets ({@code arn:aws:scheduler:::aws-sdk:<service>:<action>}) for
* {@code sns:publish} and {@code sqs:sendMessage}. Mirrors the subset handled by
* {@code sns:publish}, {@code sqs:sendMessage}, {@code redshiftdata:executeStatement} and
* {@code redshiftdata:batchExecuteStatement}. Mirrors the subset handled by
* {@code EventBridgeInvoker} but using Scheduler's {@link Target} model (raw
* {@code input} string, no JSONPath/template).
*/
@@ -59,9 +67,12 @@ public class ScheduleInvoker {
private final EventBridgeService eventBridgeService;
private final EcsService ecsService;
private final StepFunctionsService stepFunctionsService;
private final RedshiftDataService redshiftDataService;
private final ObjectMapper objectMapper;
private final String baseUrl;
private final String defaultRegion;
private final ServiceRegistry serviceRegistry;
private final Executor redshiftDataExecutor;
@Inject
public ScheduleInvoker(SqsService sqsService,
@@ -70,17 +81,52 @@ public class ScheduleInvoker {
EventBridgeService eventBridgeService,
EcsService ecsService,
StepFunctionsService stepFunctionsService,
RedshiftDataService redshiftDataService,
ObjectMapper objectMapper,
EmulatorConfig config) {
EmulatorConfig config,
ServiceRegistry serviceRegistry) {
this(sqsService, lambdaService, snsService, eventBridgeService, ecsService, stepFunctionsService,
redshiftDataService, objectMapper, config, serviceRegistry, newRedshiftDataExecutor());
}
ScheduleInvoker(SqsService sqsService,
LambdaService lambdaService,
SnsService snsService,
EventBridgeService eventBridgeService,
EcsService ecsService,
StepFunctionsService stepFunctionsService,
RedshiftDataService redshiftDataService,
ObjectMapper objectMapper,
EmulatorConfig config,
ServiceRegistry serviceRegistry,
Executor redshiftDataExecutor) {
this.sqsService = sqsService;
this.lambdaService = lambdaService;
this.snsService = snsService;
this.eventBridgeService = eventBridgeService;
this.ecsService = ecsService;
this.stepFunctionsService = stepFunctionsService;
this.redshiftDataService = redshiftDataService;
this.objectMapper = objectMapper;
this.baseUrl = config.baseUrl();
this.defaultRegion = config.defaultRegion();
this.serviceRegistry = serviceRegistry;
this.redshiftDataExecutor = redshiftDataExecutor;
}
private static ExecutorService newRedshiftDataExecutor() {
return Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "scheduler-redshift-data");
t.setDaemon(true);
return t;
});
}
@PreDestroy
void shutdown() {
if (redshiftDataExecutor instanceof ExecutorService service) {
service.shutdownNow();
}
}
/**
@@ -107,7 +153,7 @@ public class ScheduleInvoker {
String input = contextualInput(schedule, scheduledAt, executionId, attemptNumber);
if (isUniversalTarget(arn)) {
invokeUniversalTarget(arn.substring(arn.indexOf(":aws-sdk:") + ":aws-sdk:".length()),
input, region);
input, region, schedule.getAccountId());
return universalTargetRequest(input);
}
@@ -401,9 +447,11 @@ public class ScheduleInvoker {
* Dispatches an EventBridge Scheduler universal target ({@code aws-sdk:<service>:<action>}),
* reading the call parameters from the target's {@code Input} payload. Supports the
* common {@code sns:publish} and {@code sqs:sendMessage} actions; other actions fail
* as unsupported.
* as unsupported. {@code scheduleAccountId} scopes the Redshift Data calls, whose cluster and
* statement storage is account-aware and the dispatcher thread carries no request account.
*/
private void invokeUniversalTarget(String serviceAction, String input, String region) {
private void invokeUniversalTarget(String serviceAction, String input, String region,
String scheduleAccountId) {
JsonNode params;
try {
params = objectMapper.readTree(input == null || input.isBlank() ? "{}" : input);
@@ -436,11 +484,44 @@ public class ScheduleInvoker {
messageAttributes, region);
LOG.debugv("Scheduler delivered to SQS (universal target): {0}", queueUrl);
}
case "redshiftdata:executeStatement" -> {
requireRedshiftData();
submitRedshiftData(scheduleAccountId, region, () -> redshiftDataService.submitStatement(params, region));
LOG.debugv("Scheduler submitted to the Redshift Data API (universal target): {0}", serviceAction);
}
case "redshiftdata:batchExecuteStatement" -> {
requireRedshiftData();
submitRedshiftData(scheduleAccountId, region, () -> redshiftDataService.submitBatch(params, region));
LOG.debugv("Scheduler submitted to the Redshift Data API (universal target): {0}", serviceAction);
}
default -> throw new UnsupportedOperationException(
"Scheduler: unsupported universal target action: " + serviceAction);
}
}
private void requireRedshiftData() {
if (!serviceRegistry.isServiceEnabled("redshift-data")) {
throw new AwsException("ServiceNotAvailableException", "Service redshift-data is not enabled.", 400);
}
}
/**
* The Data API is asynchronous: AWS returns once the statement is submitted. The request check
* runs here, so a rejected request still fails the occurrence and is retried, while the SQL runs
* on its own thread so a slow statement cannot hold up the single dispatcher thread. Both halves
* run as the schedule's account, which neither thread carries.
*/
private void submitRedshiftData(String scheduleAccountId, String region, Supplier<Runnable> submit) {
Runnable statement = RequestScopes.callAs(scheduleAccountId, region, submit);
redshiftDataExecutor.execute(() -> {
try {
RequestScopes.runAs(scheduleAccountId, region, statement);
} catch (RuntimeException e) {
LOG.warnv("Scheduled Redshift Data statement failed: {0}", e.getMessage());
}
});
}
private static Map<String, MessageAttributeValue> parseUniversalSqsMessageAttributes(JsonNode attrsNode) {
Map<String, MessageAttributeValue> attributes = new HashMap<>();
if (attrsNode == null || !attrsNode.isObject()) {
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
@@ -50,6 +51,7 @@ 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.redshiftdata.RedshiftDataJsonHandler;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.scheduler.SchedulerController;
@@ -252,6 +254,8 @@ public class AslExecutor {
private final SchedulerService schedulerService;
private final SchedulerController schedulerController;
private final RdsDataService rdsDataService;
private final RedshiftDataJsonHandler redshiftDataHandler;
private final ServiceRegistry serviceRegistry;
private final ObjectMapper objectMapper;
private final Configuration jsonPathConfiguration;
private final JsonataEvaluator jsonataEvaluator;
@@ -281,13 +285,14 @@ public class AslExecutor {
SchedulerController schedulerController, RdsDataService rdsDataService,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness) {
CustomResourceLiveness customResourceLiveness, RedshiftDataJsonHandler redshiftDataHandler,
ServiceRegistry serviceRegistry) {
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null);
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
@@ -301,8 +306,11 @@ public class AslExecutor {
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness,
Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) {
Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride,
RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
this.customResourceLiveness = customResourceLiveness;
this.redshiftDataHandler = redshiftDataHandler;
this.lambdaExecutor = lambdaExecutor;
this.targetResolver = targetResolver;
this.dynamoDb = dynamoDb;
@@ -340,6 +348,47 @@ public class AslExecutor {
}
}
// Kept for tests that do not exercise the Redshift Data API integration.
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler,
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
CloudFormationQueryHandler cloudFormationHandler,
Ec2Service ec2Service, S3Service s3Service,
EcsService ecsService, EcsJsonHandler ecsJsonHandler,
EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,
SchedulerController schedulerController, RdsDataService rdsDataService,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness) {
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null);
}
// Kept for tests that do not exercise the Redshift Data API integration.
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler,
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
CloudFormationQueryHandler cloudFormationHandler,
Ec2Service ec2Service, S3Service s3Service,
EcsService ecsService, EcsJsonHandler ecsJsonHandler,
EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,
SchedulerController schedulerController, RdsDataService rdsDataService,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness,
Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) {
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
clock, sleeper, maxWaitSecondsOverride, null, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler,
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
@@ -1208,6 +1257,12 @@ public class AslExecutor {
return invokeAwsSdkDynamoDb(camelCaseAction, input, region);
}
// AWS SDK service integrations: Redshift Data API (provisioned clusters and Serverless workgroups)
if (integration.isSdkService("redshiftdata") && integration.suffix().isEmpty()) {
String region = extractRegionFromArn(sm.getStateMachineArn());
return invokeAwsSdkRedshiftData(integration, input, region);
}
// AWS SDK service integration: RDS Data API ExecuteStatement
if (integration.isSdkService("rdsdata")) {
String region = extractRegionFromArn(sm.getStateMachineArn());
@@ -2285,6 +2340,49 @@ public class AslExecutor {
return objectMapper.createObjectNode();
}
/**
* The Data API is a JSON 1.1 service, so the Task input is already the PascalCase wire request and
* the response needs no re-casing. Only the timestamps differ: the wire carries epoch seconds where
* the {@code aws-sdk:} integration renders the SDK's ISO-8601 {@code Instant}.
*/
private JsonNode invokeAwsSdkRedshiftData(StatesIntegration integration, JsonNode input, String region) {
if (!serviceRegistry.isServiceEnabled("redshift-data")) {
throw new FailStateException(sdkExceptionName("RedshiftData", "ServiceNotAvailableException"),
"Service redshift-data is not enabled.");
}
if (input != null && !input.isObject()) {
throw new FailStateException(sdkExceptionName("RedshiftData", "ValidationException"),
"The task input must be a JSON object.");
}
JsonNode request = input != null ? input : objectMapper.createObjectNode();
Response response;
try {
response = redshiftDataHandler.handle(capitalizeFirst(integration.api()), request, region);
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("RedshiftData", e.getErrorCode()), e.getMessage());
}
if (!(response.getEntity() instanceof JsonNode body)) {
return objectMapper.createObjectNode();
}
JsonNode rendered = body.deepCopy();
renderRedshiftDataTimestamps(rendered);
return rendered;
}
private static void renderRedshiftDataTimestamps(JsonNode node) {
if (node instanceof ObjectNode object) {
for (String field : List.of("CreatedAt", "UpdatedAt")) {
JsonNode value = object.get(field);
if (value != null && value.isNumber()) {
object.put(field, sdkTimestamp(value.asDouble()));
}
}
object.elements().forEachRemaining(AslExecutor::renderRedshiftDataTimestamps);
} else if (node instanceof ArrayNode array) {
array.elements().forEachRemaining(AslExecutor::renderRedshiftDataTimestamps);
}
}
private JsonNode invokeAwsSdkRdsData(StatesIntegration integration, JsonNode input, String region) {
if (!"executeStatement".equals(integration.api())) {
throw new FailStateException("States.TaskFailed",