feat(eventbridge): support native Redshift Data API targets (#6900)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-31 05:30:15 -04:00
1 parent add127bf7c
commit 6d32605370
11 files changed
+664 -7

No files matched your search

+34
View File
@@ -152,6 +152,40 @@ the state machine from the account and region in its ARN.
State machine aliases and versions are not supported as EventBridge targets.
## Redshift Data API Targets
A matching rule can submit one SQL statement to the Redshift Data API for a provisioned cluster, or
multiple statements as one batch. A Redshift Serverless workgroup ARN is also supported. Configure
the database and SQL in `RedshiftDataParameters`; `WithEvent` publishes the statement's terminal
status event through Redshift Data API's existing EventBridge integration.
```bash
aws events put-targets \
--rule refresh-warehouse \
--targets '[{
"Id": "refresh-redshift",
"Arn": "arn:aws:redshift:us-east-1:000000000000:cluster:warehouse",
"RoleArn": "arn:aws:iam::000000000000:role/EventBridgeRedshiftRole",
"RedshiftDataParameters": {
"Database": "dev",
"DbUser": "admin",
"Sql": "refresh materialized view daily_totals",
"StatementName": "refresh-warehouse"
}
}]' \
--endpoint-url $AWS_ENDPOINT_URL
```
`Sqls` selects `BatchExecuteStatement`; otherwise the target submits `Sql` with
`ExecuteStatement`. `SecretManagerArn` maps to the Data API's `SecretArn`. The target's ARN provides
the region used for execution; statements run in the rule's account. The stored `RoleArn` is passed
as the Data API principal; Floci does not assume the role or evaluate its IAM policies.
String parameters, including entries in `Sqls`, can be complete JSONPath references such as
`$.detail.database`, `$.detail.query` or `$.detail.queries[0]`. Paths resolve against the original event, before
`Input`, `InputPath` or `InputTransformer`; embedded paths inside SQL text are left unchanged.
Dispatch is rejected when the `redshift-data` service is disabled.
## Target Roles
`PutTargets` stores each target's optional `RoleArn`, and `ListTargetsByRule`
+3 -1
View File
@@ -212,7 +212,9 @@ use source `aws.redshift-data` and detail type `Redshift Data Statement Status C
`redshiftQueryId`, `state`, `rows` and `expireAt` in epoch seconds. Query ids match
`DescribeStatement`; Floci derives them from statement ids rather than backend query ids.
`resources` contains the cluster ARN, or the workgroup ARN for Floci's Serverless support.
EventBridge rules can route these events to SQS, Lambda or other supported targets.
EventBridge rules can route these events to SQS, Lambda or other supported targets. Rules can also
submit SQL to a Redshift cluster or Serverless workgroup through native Redshift Data API targets;
see [EventBridge Redshift Data API targets](eventbridge.md#redshift-data-api-targets).
## Spectrum relational queries
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParameters;
import io.github.hectorvent.floci.services.eventbridge.model.Replay;
import io.github.hectorvent.floci.services.eventbridge.model.ReplayState;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
@@ -276,6 +277,11 @@ public class EventBridgeHandler {
if (!ecsParamsNode.isMissingNode() && ecsParamsNode.isObject()) {
target.setEcsParameters(objectMapper.convertValue(ecsParamsNode, EcsParameters.class));
}
JsonNode redshiftParamsNode = t.path("RedshiftDataParameters");
if (!redshiftParamsNode.isMissingNode() && redshiftParamsNode.isObject()) {
target.setRedshiftDataParameters(
objectMapper.convertValue(redshiftParamsNode, RedshiftDataParameters.class));
}
JsonNode retryPolicyNode = t.path("RetryPolicy");
if (retryPolicyNode.isObject()) {
target.setRetryPolicy(objectMapper.convertValue(retryPolicyNode, Target.RetryPolicy.class));
@@ -352,6 +358,9 @@ public class EventBridgeHandler {
if (t.getEcsParameters() != null) {
node.set("EcsParameters", objectMapper.valueToTree(t.getEcsParameters()));
}
if (t.getRedshiftDataParameters() != null) {
node.set("RedshiftDataParameters", objectMapper.valueToTree(t.getRedshiftDataParameters()));
}
if (t.getRetryPolicy() != null) {
node.set("RetryPolicy", objectMapper.valueToTree(t.getRetryPolicy()));
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.core.JsonProcessingException;
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.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
@@ -21,11 +23,13 @@ import io.github.hectorvent.floci.services.eventbridge.model.Connection;
import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParameters;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
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.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
@@ -52,6 +56,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@ApplicationScoped
public class EventBridgeInvoker {
@@ -61,6 +66,8 @@ public class EventBridgeInvoker {
// AWS can't route an event from a sender bus on to a third bus; the second hop is dropped.
private static final int MAX_BUS_TO_BUS_DEPTH = 1;
private static final int MAX_IDLE_RATE_WINDOWS = 256;
private static final Pattern DYNAMIC_PARAMETER_PATH =
Pattern.compile("\\$(?:\\.[\\w*/-]+|\\[\\d+\\])+");
// Headers the JDK HttpClient manages itself; setting them by hand throws IllegalArgumentException.
private static final Set<String> RESTRICTED_HEADERS =
Set.of("connection", "content-length", "expect", "host", "transfer-encoding", "upgrade");
@@ -75,6 +82,8 @@ public class EventBridgeInvoker {
private final EcsService ecsService;
private final EcsJsonHandler ecsJsonHandler;
private final StepFunctionsService stepFunctionsService;
private final RedshiftDataService redshiftDataService;
private final ServiceRegistry serviceRegistry;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final String baseUrl;
@@ -91,11 +100,14 @@ public class EventBridgeInvoker {
EcsService ecsService,
EcsJsonHandler ecsJsonHandler,
StepFunctionsService stepFunctionsService,
RedshiftDataService redshiftDataService,
ServiceRegistry serviceRegistry,
RegionResolver regionResolver,
ObjectMapper objectMapper,
EmulatorConfig config) {
this(lambdaService, sqsService, snsService, batchService, firehoseService, eventBridgeService,
ecsService, ecsJsonHandler, stepFunctionsService, regionResolver, objectMapper, config,
ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, serviceRegistry,
regionResolver, objectMapper, config,
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
@@ -108,6 +120,8 @@ public class EventBridgeInvoker {
EcsService ecsService,
EcsJsonHandler ecsJsonHandler,
StepFunctionsService stepFunctionsService,
RedshiftDataService redshiftDataService,
ServiceRegistry serviceRegistry,
RegionResolver regionResolver,
ObjectMapper objectMapper,
EmulatorConfig config,
@@ -121,6 +135,8 @@ public class EventBridgeInvoker {
this.ecsService = ecsService;
this.ecsJsonHandler = ecsJsonHandler;
this.stepFunctionsService = stepFunctionsService;
this.redshiftDataService = redshiftDataService;
this.serviceRegistry = serviceRegistry;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.baseUrl = config.baseUrl();
@@ -134,7 +150,23 @@ public class EventBridgeInvoker {
EmulatorConfig config) {
this(lambdaService, sqsService, snsService,
null /* batch */, null /* firehose */, null /* eventBridge */, null /* ecs */,
null /* ecsJsonHandler */, null /* stepFunctions */, null /* regionResolver */, objectMapper, config);
null /* ecsJsonHandler */, null /* stepFunctions */, null /* redshiftData */, null /* registry */,
null /* regionResolver */,
objectMapper, config);
}
EventBridgeInvoker(LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
RedshiftDataService redshiftDataService,
ServiceRegistry serviceRegistry,
ObjectMapper objectMapper,
EmulatorConfig config) {
this(lambdaService, sqsService, snsService,
null /* batch */, null /* firehose */, null /* eventBridge */, null /* ecs */,
null /* ecsJsonHandler */, null /* stepFunctions */, redshiftDataService, serviceRegistry,
null /* regionResolver */,
objectMapper, config);
}
public void invokeTarget(Target target, String eventJson, String region) {
@@ -207,6 +239,9 @@ public class EventBridgeInvoker {
firehoseService.putRecord(streamArn.accountId(), streamArn.region(), streamName, record);
}
LOG.debugv("EventBridge delivered to Firehose: {0}", arn);
} else if (AwsArnUtils.isArnFor(arn, "redshift")
|| AwsArnUtils.isArnFor(arn, "redshift-serverless")) {
deliverToRedshiftData(target, arn, eventJson);
} else if (isStateMachineArn(arn)) {
String targetRegion = extractRegionFromArn(arn, region);
String targetAccount = AwsArnUtils.parse(arn).accountId();
@@ -300,6 +335,77 @@ public class EventBridgeInvoker {
}
}
private void deliverToRedshiftData(Target target, String targetArn, String eventJson) {
if (serviceRegistry != null && !serviceRegistry.isServiceEnabled("redshift-data")) {
throw new AwsException("ServiceNotAvailableException", "Service redshift-data is not enabled.", 400);
}
RedshiftDataParameters parameters = target.getRedshiftDataParameters();
if (redshiftDataService == null || parameters == null) {
LOG.warnv("EventBridge Redshift target missing Redshift Data service or parameters: {0}", targetArn);
return;
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(targetArn);
String fallbackRegion = regionResolver == null ? null : regionResolver.getRegion();
String targetRegion = extractRegionFromArn(targetArn, fallbackRegion);
ObjectNode request = objectMapper.createObjectNode();
String resource = arn.resource();
if ("redshift".equals(arn.service()) && resource.startsWith("cluster:")) {
request.put("ClusterIdentifier", resource.substring("cluster:".length()));
} else if ("redshift-serverless".equals(arn.service()) && resource.startsWith("workgroup/")) {
request.put("WorkgroupName", targetArn);
} else {
LOG.warnv("EventBridge Redshift target has an unsupported resource ARN: {0}", targetArn);
return;
}
putIfPresent(request, "Database", resolveRedshiftParameter(parameters.getDatabase(), eventJson));
putIfPresent(request, "DbUser", resolveRedshiftParameter(parameters.getDbUser(), eventJson));
putIfPresent(request, "SecretArn", resolveRedshiftParameter(parameters.getSecretManagerArn(), eventJson));
putIfPresent(request, "Sql", resolveRedshiftParameter(parameters.getSql(), eventJson));
putIfPresent(request, "StatementName", resolveRedshiftParameter(parameters.getStatementName(), eventJson));
if (parameters.getSqls() != null) {
ArrayNode sqls = request.putArray("Sqls");
for (String sql : parameters.getSqls()) {
sqls.add(resolveRedshiftParameter(sql, eventJson));
}
}
if (parameters.getWithEvent() != null) {
request.put("WithEvent", parameters.getWithEvent());
}
String ruleAccount = regionResolver != null && regionResolver.getAccountId() != null
? regionResolver.getAccountId()
: arn.accountId();
if (parameters.getSqls() != null) {
RequestScopes.callAs(ruleAccount, targetRegion,
() -> redshiftDataService.batchExecuteStatement(request, targetRegion, target.getRoleArn()));
} else {
RequestScopes.callAs(ruleAccount, targetRegion,
() -> redshiftDataService.executeStatement(request, targetRegion, target.getRoleArn()));
}
LOG.debugv("EventBridge submitted SQL to Redshift Data API: {0}", targetArn);
}
private String resolveRedshiftParameter(String value, String eventJson) {
if (value == null || !DYNAMIC_PARAMETER_PATH.matcher(value).matches()) {
return value;
}
JsonNode node = extractNode(value, eventJson);
if (node.isMissingNode()) {
throw new AwsException("ValidationException", "Cannot resolve Redshift target path: " + value, 400);
}
if (node.isNull()) {
throw new AwsException("ValidationException", "Redshift target path resolved to null: " + value, 400);
}
return node.isTextual() ? node.asText() : node.toString();
}
private static void putIfPresent(ObjectNode request, String field, String value) {
if (value != null) {
request.put(field, value);
}
}
/**
* AWS maps an ECS target's (input-transformed) payload 1-to-1 onto the RunTask
* {@code TaskOverride} structure. Floci's override model only carries
@@ -93,9 +93,14 @@ public class TargetDispatcher implements Resettable {
public void dispatch(String ruleArn, Target target, String eventJson, String region,
Supplier<List<Target>> currentTargets) {
Instant now = clock.instant();
Delivery delivery = new Delivery(ruleArn, target.getId(), eventJson, region, currentTargets,
generation.get(), now, 0, null, null, now);
try {
attempt(new Delivery(ruleArn, target.getId(), eventJson, region, currentTargets, generation.get(), now, 0,
null, null, now), target, now);
if (AwsArnUtils.isArn(ruleArn)) {
RequestScopes.runAs(AwsArnUtils.parse(ruleArn).accountId(), () -> attempt(delivery, target, now));
} else {
attempt(delivery, target, now);
}
} catch (RuntimeException e) {
LOG.warnv("EventBridge rule {0} could not dispatch to target {1}: {2}",
ruleArn, target.getId(), e.getMessage());
@@ -114,7 +119,11 @@ public class TargetDispatcher implements Resettable {
return;
}
try {
RequestScopes.runAs(AwsArnUtils.parse(delivery.ruleArn()).accountId(), () -> retry(delivery, now));
if (AwsArnUtils.isArn(delivery.ruleArn())) {
RequestScopes.runAs(AwsArnUtils.parse(delivery.ruleArn()).accountId(), () -> retry(delivery, now));
} else {
retry(delivery, now);
}
} catch (RuntimeException e) {
LOG.warnv("EventBridge retry for rule {0} target {1} failed: {2}",
delivery.ruleArn(), delivery.targetId(), e.getMessage());
@@ -179,7 +188,10 @@ public class TargetDispatcher implements Resettable {
return "INTERNAL_ERROR";
}
String code = aws.getErrorCode() != null ? aws.getErrorCode() : "";
if (aws.getHttpStatus() == 429 || code.contains("Throttl") || code.contains("TooManyRequests")) {
if (aws.getHttpStatus() == 429
|| code.contains("Throttl")
|| code.contains("TooManyRequests")
|| "ActiveStatementsExceededException".equals(code)) {
return "THROTTLING";
}
if (aws.getHttpStatus() >= 500) {
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.eventbridge.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RedshiftDataParameters {
private String database;
private String dbUser;
private String secretManagerArn;
private String sql;
private List<String> sqls;
private String statementName;
private Boolean withEvent;
@JsonProperty("Database")
public String getDatabase() { return database; }
@JsonProperty("Database")
public void setDatabase(String database) { this.database = database; }
@JsonProperty("DbUser")
public String getDbUser() { return dbUser; }
@JsonProperty("DbUser")
public void setDbUser(String dbUser) { this.dbUser = dbUser; }
@JsonProperty("SecretManagerArn")
public String getSecretManagerArn() { return secretManagerArn; }
@JsonProperty("SecretManagerArn")
public void setSecretManagerArn(String secretManagerArn) { this.secretManagerArn = secretManagerArn; }
@JsonProperty("Sql")
public String getSql() { return sql; }
@JsonProperty("Sql")
public void setSql(String sql) { this.sql = sql; }
@JsonProperty("Sqls")
public List<String> getSqls() { return sqls; }
@JsonProperty("Sqls")
public void setSqls(List<String> sqls) { this.sqls = sqls; }
@JsonProperty("StatementName")
public String getStatementName() { return statementName; }
@JsonProperty("StatementName")
public void setStatementName(String statementName) { this.statementName = statementName; }
@JsonProperty("WithEvent")
public Boolean getWithEvent() { return withEvent; }
@JsonProperty("WithEvent")
public void setWithEvent(Boolean withEvent) { this.withEvent = withEvent; }
}
@@ -18,6 +18,7 @@ public class Target {
private SqsParameters sqsParameters;
private BatchParameters batchParameters;
private EcsParameters ecsParameters;
private RedshiftDataParameters redshiftDataParameters;
private RetryPolicy retryPolicy;
private DeadLetterConfig deadLetterConfig;
private HttpParameters httpParameters;
@@ -58,6 +59,11 @@ public class Target {
public EcsParameters getEcsParameters() { return ecsParameters; }
public void setEcsParameters(EcsParameters ecsParameters) { this.ecsParameters = ecsParameters; }
public RedshiftDataParameters getRedshiftDataParameters() { return redshiftDataParameters; }
public void setRedshiftDataParameters(RedshiftDataParameters redshiftDataParameters) {
this.redshiftDataParameters = redshiftDataParameters;
}
public RetryPolicy getRetryPolicy() { return retryPolicy; }
public void setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; }
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsService;
@@ -21,6 +22,7 @@ import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
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.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
@@ -67,6 +69,8 @@ class EventBridgeInvokerTest {
EmulatorConfig emulatorConfig =
mock(EmulatorConfig.class,
Mockito.RETURNS_DEEP_STUBS);
RedshiftDataService redshiftDataService = mock(RedshiftDataService.class);
ServiceRegistry serviceRegistry = mock(ServiceRegistry.class);
invoker = new EventBridgeInvoker(
lambdaService,
sqsService,
@@ -78,6 +82,8 @@ class EventBridgeInvokerTest {
new EcsJsonHandler(ecsService, new ObjectMapper(),
new HostVolumePolicy(emulatorConfig)),
stepFunctionsService,
redshiftDataService,
serviceRegistry,
regionResolver,
new ObjectMapper(),
emulatorConfig
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParameters;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@QuarkusTest
class EventBridgeRedshiftDataAccountIntegrationTest {
@Inject
RuleScheduler scheduler;
@Inject
RegionResolver regionResolver;
@InjectMock
RedshiftDataService redshiftDataService;
@ParameterizedTest
@ValueSource(booleans = {false, true})
void scheduledSqlUsesRuleAccountWithoutAnHttpRequest(boolean batch) {
String previousAccount = regionResolver.getAccountId();
AtomicReference<String> executionAccount = new AtomicReference<>();
if (batch) {
when(redshiftDataService.batchExecuteStatement(any(), any(), any())).thenAnswer(invocation -> {
executionAccount.set(regionResolver.getAccountId());
return JsonNodeFactory.instance.objectNode();
});
} else {
when(redshiftDataService.executeStatement(any(), any(), any())).thenAnswer(invocation -> {
executionAccount.set(regionResolver.getAccountId());
return JsonNodeFactory.instance.objectNode();
});
}
Rule rule = new Rule();
rule.setName("scheduled-redshift-account");
rule.setArn("arn:aws:events:us-east-1:111122223333:rule/scheduled-redshift-account");
rule.setAccountId("111122223333");
rule.setState(RuleState.ENABLED);
Target target = new Target("sql", "arn:aws:redshift:us-east-1:999999999999:cluster:warehouse", null, null);
target.setRoleArn("arn:aws:iam::111122223333:role/EventBridgeRedshiftRole");
RedshiftDataParameters parameters = new RedshiftDataParameters();
parameters.setDatabase("dev");
if (batch) {
parameters.setSqls(List.of("select 1"));
} else {
parameters.setSql("select 1");
}
target.setRedshiftDataParameters(parameters);
try {
scheduler.startScheduler(rule.getArn(), "rate(1 minute)",
() -> new RuleScheduler.ScheduleData(rule, List.of(target)));
assertEquals("111122223333", executionAccount.get());
assertEquals(previousAccount, regionResolver.getAccountId());
} finally {
scheduler.stopScheduler(rule.getArn());
}
}
}
@@ -0,0 +1,279 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParameters;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.MockMakers;
import org.mockito.MockedStatic;
import java.util.List;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
class EventBridgeRedshiftDataTargetTest {
private static final String CLUSTER_ARN = "arn:aws:redshift:us-east-1:123456789012:cluster:warehouse";
private static final String WORKGROUP_ARN =
"arn:aws:redshift-serverless:us-west-2:123456789012:workgroup/warehouse";
private static final String ROLE_ARN = "arn:aws:iam::123456789012:role/EventBridgeRedshiftRole";
private static final String EVENT = "{\"id\":\"event-1\"}";
private RedshiftDataService redshiftDataService;
private ServiceRegistry serviceRegistry;
private EventBridgeInvoker invoker;
@BeforeEach
void setUp() {
redshiftDataService = mock(RedshiftDataService.class);
serviceRegistry = mock(ServiceRegistry.class);
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.baseUrl()).thenReturn("http://localhost:4566");
invoker = new EventBridgeInvoker(mock(LambdaService.class), mock(SqsService.class), mock(SnsService.class),
redshiftDataService, serviceRegistry, new ObjectMapper(), config);
}
@Test
void disabledDataApiRejectsSingleAndBatchDispatch() {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(false);
for (boolean batch : List.of(false, true)) {
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("dev");
if (batch) {
parameters.setSqls(List.of("select 1"));
} else {
parameters.setSql("select 1");
}
target.setRedshiftDataParameters(parameters);
AwsException failure = assertThrows(AwsException.class,
() -> invoker.invokeTarget(target, EVENT, "us-east-1"));
assertEquals("ServiceNotAvailableException", failure.getErrorCode());
}
verifyNoInteractions(redshiftDataService);
}
@Test
void resolvesParametersFromOriginalEventDespiteInputOverride() {
Target target = target(CLUSTER_ARN);
target.setInput("{\"detail\":{\"database\":\"wrong\"}}");
RedshiftDataParameters parameters = parameters("$.detail.database");
parameters.setDbUser("$.detail.user");
parameters.setSecretManagerArn("$.detail.secret");
parameters.setStatementName("$.detail.name");
parameters.setSql("$.detail.queries[0]");
target.setRedshiftDataParameters(parameters);
String event = """
{"detail":{"database":"dev","user":"admin","secret":"secret-arn",
"name":"event-statement","queries":["select 42"]}}
""";
invoker.invokeTarget(target, event, "us-east-1");
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(redshiftDataService).executeStatement(request.capture(), eq("us-east-1"), eq(ROLE_ARN));
assertEquals("dev", request.getValue().path("Database").asText());
assertEquals("admin", request.getValue().path("DbUser").asText());
assertEquals("secret-arn", request.getValue().path("SecretArn").asText());
assertEquals("event-statement", request.getValue().path("StatementName").asText());
assertEquals("select 42", request.getValue().path("Sql").asText());
assertEquals("$.detail.database", parameters.getDatabase());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void resolvesSqlPathContainingSlash(boolean batch) {
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("dev");
if (batch) {
parameters.setSqls(List.of("$.detail.sql/query"));
} else {
parameters.setSql("$.detail.sql/query");
}
target.setRedshiftDataParameters(parameters);
invoker.invokeTarget(target, "{\"detail\":{\"sql/query\":\"select 1\"}}", "us-east-1");
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
if (batch) {
verify(redshiftDataService).batchExecuteStatement(request.capture(), eq("us-east-1"), eq(ROLE_ARN));
assertEquals("select 1", request.getValue().path("Sqls").get(0).asText());
} else {
verify(redshiftDataService).executeStatement(request.capture(), eq("us-east-1"), eq(ROLE_ARN));
assertEquals("select 1", request.getValue().path("Sql").asText());
}
}
@Test
void resolvesBatchSqlPathsAndPreservesStaticSql() {
Target target = target(WORKGROUP_ARN);
RedshiftDataParameters parameters = parameters("dev");
parameters.setSqls(List.of("$.detail.queries[0]", "$.detail.queries[1]", "select '$.detail.literal'"));
target.setRedshiftDataParameters(parameters);
invoker.invokeTarget(target, "{\"detail\":{\"queries\":[\"select 42\",\"select 43\"]}}", "us-west-2");
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(redshiftDataService).batchExecuteStatement(request.capture(), eq("us-west-2"), eq(ROLE_ARN));
assertEquals("select 42", request.getValue().path("Sqls").get(0).asText());
assertEquals("select 43", request.getValue().path("Sqls").get(1).asText());
assertEquals("select '$.detail.literal'", request.getValue().path("Sqls").get(2).asText());
}
@Test
void invokesExecuteStatementForClusterTarget() throws Exception {
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("dev");
parameters.setDbUser("event_user");
parameters.setSql("select 1");
parameters.setWithEvent(true);
target.setRedshiftDataParameters(parameters);
invoker.invokeTarget(target, EVENT, "eu-west-1");
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(redshiftDataService).executeStatement(request.capture(), eq("us-east-1"), eq(ROLE_ARN));
assertEquals("warehouse", request.getValue().path("ClusterIdentifier").asText());
assertEquals("dev", request.getValue().path("Database").asText());
assertEquals("event_user", request.getValue().path("DbUser").asText());
assertEquals("select 1", request.getValue().path("Sql").asText());
assertEquals("event-rule", request.getValue().path("StatementName").asText());
assertEquals(true, request.getValue().path("WithEvent").asBoolean());
}
@Test
void invokesBatchExecuteStatementForServerlessWorkgroupTarget() throws Exception {
Target target = target(WORKGROUP_ARN);
RedshiftDataParameters parameters = parameters("dev");
parameters.setSecretManagerArn("arn:aws:secretsmanager:us-west-2:123456789012:secret:redshift");
parameters.setSqls(List.of("select 1", "select 2"));
target.setRedshiftDataParameters(parameters);
invoker.invokeTarget(target, EVENT, "us-east-1");
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(redshiftDataService).batchExecuteStatement(request.capture(), eq("us-west-2"), eq(ROLE_ARN));
assertEquals(WORKGROUP_ARN, request.getValue().path("WorkgroupName").asText());
assertEquals("dev", request.getValue().path("Database").asText());
assertEquals(parameters.getSecretManagerArn(), request.getValue().path("SecretArn").asText());
assertEquals(2, request.getValue().path("Sqls").size());
}
@Test
void readsRedshiftDataParametersUsingAwsMemberNames() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
RedshiftDataParameters parameters = objectMapper.convertValue(
objectMapper.readTree("{\"Database\":\"dev\",\"SecretManagerArn\":\"secret\",\"Sql\":\"select 1\"}"),
RedshiftDataParameters.class);
assertEquals("dev", parameters.getDatabase());
assertEquals("secret", parameters.getSecretManagerArn());
assertEquals("select 1", parameters.getSql());
JsonNode response = objectMapper.valueToTree(parameters);
assertEquals("dev", response.path("Database").asText());
assertEquals("secret", response.path("SecretManagerArn").asText());
}
@Test
void doesNotThrowWhenServiceRegistryIsNull() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.baseUrl()).thenReturn("http://localhost:4566");
EventBridgeInvoker bareInvoker = new EventBridgeInvoker(mock(LambdaService.class), mock(SqsService.class),
mock(SnsService.class), redshiftDataService, null, new ObjectMapper(), config);
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("dev");
parameters.setSql("select 1");
target.setRedshiftDataParameters(parameters);
bareInvoker.invokeTarget(target, EVENT, "us-east-1");
verify(redshiftDataService).executeStatement(any(), eq("us-east-1"), eq(ROLE_ARN));
}
@Test
void runsInRulesAccountRatherThanTargetArnAccount() {
RegionResolver resolver = mock(RegionResolver.class);
when(resolver.getAccountId()).thenReturn("999999999999");
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.baseUrl()).thenReturn("http://localhost:4566");
EventBridgeInvoker scopedInvoker = new EventBridgeInvoker(
mock(LambdaService.class), mock(SqsService.class), mock(SnsService.class),
null, null, null, null, null, null,
redshiftDataService, serviceRegistry, resolver, new ObjectMapper(), config);
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("dev");
parameters.setSql("select 1");
target.setRedshiftDataParameters(parameters);
try (MockedStatic<RequestScopes> scopes =
mockStatic(RequestScopes.class, withSettings().mockMaker(MockMakers.INLINE))) {
scopes.when(() -> RequestScopes.callAs(eq("999999999999"), eq("us-east-1"), any(Supplier.class)))
.thenAnswer(invocation -> invocation.<Supplier<?>>getArgument(2).get());
scopedInvoker.invokeTarget(target, EVENT, "us-east-1");
scopes.verify(() -> RequestScopes.callAs(eq("999999999999"), eq("us-east-1"), any(Supplier.class)));
}
}
@Test
void missingPathThrowsValidationException() {
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("$.detail.nonexistent");
parameters.setSql("select 1");
target.setRedshiftDataParameters(parameters);
AwsException failure = assertThrows(AwsException.class,
() -> invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1"));
assertEquals("ValidationException", failure.getErrorCode());
}
@Test
void nullPathThrowsValidationException() {
Target target = target(CLUSTER_ARN);
RedshiftDataParameters parameters = parameters("$.detail.nullDatabase");
parameters.setSql("select 1");
target.setRedshiftDataParameters(parameters);
AwsException failure = assertThrows(AwsException.class,
() -> invoker.invokeTarget(target, "{\"detail\":{\"nullDatabase\":null}}", "us-east-1"));
assertEquals("ValidationException", failure.getErrorCode());
}
private static Target target(String arn) {
Target target = new Target("target-1", arn, null, null);
target.setRoleArn(ROLE_ARN);
return target;
}
private static RedshiftDataParameters parameters(String database) {
RedshiftDataParameters parameters = new RedshiftDataParameters();
parameters.setDatabase(database);
parameters.setStatementName("event-rule");
return parameters;
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -14,6 +15,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.MockMakers;
import org.mockito.MockedStatic;
import java.time.Clock;
import java.time.Instant;
@@ -85,6 +88,27 @@ class TargetDispatcherTest {
verifyNoDeadLetter();
}
@Test
void activeStatementsExceededIsRetriedAfterBackoffUntilAccepted() {
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
.thenThrow(new AwsException("ActiveStatementsExceededException", "Too many active statements", 400))
.thenReturn(null);
Target target = sqsTarget(null, DLQ_ARN);
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
tickAt(T0.plusMillis(999));
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
tickAt(T0.plusSeconds(1));
verify(sqsService, times(2)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
tickAt(T0.plusSeconds(3600));
verify(sqsService, times(2)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
verifyNoDeadLetter();
}
@Test
void queuedRetryWakesItselfUpOnTheExecutor() {
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
@@ -385,6 +409,51 @@ class TargetDispatcherTest {
verifyNoDeadLetter();
}
@Test
void dispatchEstablishesRuleAccountScopeBeforeFirstAttempt() {
Target target = sqsTarget(null, null);
try (MockedStatic<RequestScopes> scopes =
mockStatic(RequestScopes.class, withSettings().mockMaker(MockMakers.INLINE))) {
scopes.when(() -> RequestScopes.runAs(eq("123456789012"), any(Runnable.class)))
.thenAnswer(invocation -> {
invocation.<Runnable>getArgument(1).run();
return null;
});
dispatcher.dispatch("arn:aws:events:us-east-1:123456789012:rule/orders", target, EVENT, REGION,
() -> List.of(target));
scopes.verify(() -> RequestScopes.runAs(eq("123456789012"), any(Runnable.class)));
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
}
}
@Test
void retryEstablishesRuleAccountScope() {
Target target = sqsTarget(null, null);
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
.thenThrow(unavailable())
.thenReturn(null);
dispatcher.dispatch("arn:aws:events:us-east-1:123456789012:rule/orders", target, EVENT, REGION,
() -> List.of(target));
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
try (MockedStatic<RequestScopes> scopes =
mockStatic(RequestScopes.class, withSettings().mockMaker(MockMakers.INLINE))) {
scopes.when(() -> RequestScopes.runAs(eq("123456789012"), any(Runnable.class)))
.thenAnswer(invocation -> {
invocation.<Runnable>getArgument(1).run();
return null;
});
tickAt(T0.plusSeconds(1));
scopes.verify(() -> RequestScopes.runAs(eq("123456789012"), any(Runnable.class)));
verify(sqsService, times(2)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
}
}
private void tickAt(Instant now) {
clockNow.set(now);
dispatcher.tick();