feat(eventbridge): run ECS tasks from classic rule targets (#3484)

PutTargets now parses EcsParameters on an ECS cluster ARN target and
the invoker calls ecs:RunTask when the rule fires, mirroring how the
Scheduler already delivers to ECS. An InputTransformer shaped as a
TaskOverride is parsed into containerOverrides and passed through, per
AWS's documented ECS target behavior.

* Fix #2558

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-12 14:00:19 -04:00
1 parent 6507f32aea
commit cfe9f84ffe
8 files changed
+697 -3

No files matched your search

@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.ArchiveState;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
import io.github.hectorvent.floci.services.eventbridge.model.Connection;
import io.github.hectorvent.floci.services.eventbridge.model.ConnectionState;
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.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.Replay;
@@ -237,6 +238,10 @@ public class EventBridgeHandler {
if (!batchParamsNode.isMissingNode() && batchParamsNode.isObject()) {
target.setBatchParameters(objectMapper.convertValue(batchParamsNode, BatchParameters.class));
}
JsonNode ecsParamsNode = t.path("EcsParameters");
if (!ecsParamsNode.isMissingNode() && ecsParamsNode.isObject()) {
target.setEcsParameters(objectMapper.convertValue(ecsParamsNode, EcsParameters.class));
}
targets.add(target);
}
}
@@ -297,6 +302,9 @@ public class EventBridgeHandler {
if (t.getBatchParameters() != null) {
node.set("BatchParameters", objectMapper.valueToTree(t.getBatchParameters()));
}
if (t.getEcsParameters() != null) {
node.set("EcsParameters", objectMapper.valueToTree(t.getEcsParameters()));
}
targetsArray.add(node);
}
return Response.ok(response).build();
@@ -7,6 +7,11 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
@@ -40,6 +45,8 @@ public class EventBridgeInvoker {
private final BatchService batchService;
private final FirehoseService firehoseService;
private final EventBridgeService eventBridgeService;
private final EcsService ecsService;
private final EcsJsonHandler ecsJsonHandler;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final String baseUrl;
@@ -51,6 +58,8 @@ public class EventBridgeInvoker {
BatchService batchService,
FirehoseService firehoseService,
EventBridgeService eventBridgeService,
EcsService ecsService,
EcsJsonHandler ecsJsonHandler,
RegionResolver regionResolver,
ObjectMapper objectMapper,
EmulatorConfig config) {
@@ -60,6 +69,8 @@ public class EventBridgeInvoker {
this.batchService = batchService;
this.firehoseService = firehoseService;
this.eventBridgeService = eventBridgeService;
this.ecsService = ecsService;
this.ecsJsonHandler = ecsJsonHandler;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.baseUrl = config.baseUrl();
@@ -71,8 +82,8 @@ public class EventBridgeInvoker {
ObjectMapper objectMapper,
EmulatorConfig config) {
this(lambdaService, sqsService, snsService,
null /* batch */, null /* firehose */, null /* eventBridge */, null /* regionResolver */,
objectMapper, config);
null /* batch */, null /* firehose */, null /* eventBridge */, null /* ecs */,
null /* ecsJsonHandler */, null /* regionResolver */, objectMapper, config);
}
public void invokeTarget(Target target, String eventJson, String region) {
@@ -87,7 +98,7 @@ public class EventBridgeInvoker {
} else {
payload = eventJson;
}
try {
if (arn.contains(":lambda:") || arn.contains(":function:")) {
lambdaService.invokeArn(arn, payload.getBytes(), InvocationType.Event);
@@ -117,6 +128,17 @@ public class EventBridgeInvoker {
targetRegion
);
LOG.debugv("EventBridge delivered to Batch: {0}", arn);
} else if (arn.contains(":ecs:") && arn.contains(":cluster/")) {
if (ecsService == null || target.getEcsParameters() == null) {
LOG.warnv("EventBridge ECS target missing ECS service or EcsParameters: {0}", arn);
return;
}
String targetRegion = extractRegionFromArn(arn, region);
boolean inputOverridden = target.getInput() != null
|| target.getInputPath() != null
|| target.getInputTransformer() != null;
deliverToEcsRunTask(target, payload, inputOverridden, targetRegion);
LOG.debugv("EventBridge delivered to ECS RunTask: {0}", arn);
} else if (arn.contains(":firehose:") && arn.contains(":deliverystream/")) {
if (firehoseService == null) {
LOG.warnv("EventBridge Firehose target missing Firehose service: {0}", arn);
@@ -218,6 +240,68 @@ public class EventBridgeInvoker {
}
}
/**
* AWS maps an ECS target's (input-transformed) payload 1-to-1 onto the RunTask
* {@code TaskOverride} structure. Floci's override model only carries
* {@code containerOverrides}, so that member is parsed out and passed through; a
* payload that isn't the input-transformed shape (no Input/InputPath/InputTransformer
* configured) or isn't parseable as JSON launches the task without overrides, matching
* the documented no-override case rather than failing the whole delivery.
*/
private void deliverToEcsRunTask(Target target, String payload, boolean inputOverridden, String region) {
EcsParameters ecs = target.getEcsParameters();
List<ContainerOverride> containerOverrides = List.of();
if (inputOverridden) {
try {
containerOverrides = ecsJsonHandler.parseContainerOverrides(
objectMapper.readTree(payload).path("containerOverrides"));
} catch (Exception e) {
LOG.warnv("EventBridge ECS target {0} InputTransformer output is not a valid TaskOverride, "
+ "launching without container overrides: {1}", target.getArn(), e.getMessage());
}
}
ecsService.runTask(
target.getArn(),
ecs.getTaskDefinitionArn(),
ecs.getTaskCount() != null ? ecs.getTaskCount() : 1,
parseLaunchType(ecs.getLaunchType()),
null,
ecs.getGroup() != null ? ecs.getGroup() : "eventbridge",
containerOverrides,
ecsNetworkConfiguration(ecs.getNetworkConfiguration()),
region);
}
private static LaunchType parseLaunchType(String launchType) {
if (launchType == null || launchType.isBlank()) {
return null;
}
try {
return LaunchType.valueOf(launchType);
} catch (IllegalArgumentException e) {
LOG.warnv("EventBridge: unsupported ECS LaunchType: {0}", launchType);
return null;
}
}
private static io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration ecsNetworkConfiguration(
io.github.hectorvent.floci.services.eventbridge.model.NetworkConfiguration source) {
if (source == null || source.getAwsvpcConfiguration() == null) {
return null;
}
io.github.hectorvent.floci.services.eventbridge.model.AwsVpcConfiguration sourceVpc = source.getAwsvpcConfiguration();
io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration targetVpc =
new io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration();
targetVpc.setSubnets(sourceVpc.getSubnets());
targetVpc.setSecurityGroups(sourceVpc.getSecurityGroups());
targetVpc.setAssignPublicIp(sourceVpc.getAssignPublicIp());
io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration target =
new io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration();
target.setAwsvpcConfiguration(targetVpc);
return target;
}
String applyInputPath(String inputPath, String eventJson) {
if (inputPath == null || "$".equals(inputPath)) {
return eventJson;
@@ -0,0 +1,51 @@
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_EMPTY)
public class AwsVpcConfiguration {
private List<String> subnets;
private List<String> securityGroups;
private String assignPublicIp;
public AwsVpcConfiguration() {
}
@JsonProperty("Subnets")
public List<String> getSubnets() {
return subnets;
}
@JsonProperty("Subnets")
public void setSubnets(List<String> subnets) {
this.subnets = subnets;
}
@JsonProperty("SecurityGroups")
public List<String> getSecurityGroups() {
return securityGroups;
}
@JsonProperty("SecurityGroups")
public void setSecurityGroups(List<String> securityGroups) {
this.securityGroups = securityGroups;
}
@JsonProperty("AssignPublicIp")
public String getAssignPublicIp() {
return assignPublicIp;
}
@JsonProperty("AssignPublicIp")
public void setAssignPublicIp(String assignPublicIp) {
this.assignPublicIp = assignPublicIp;
}
}
@@ -0,0 +1,176 @@
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 com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* The {@code EcsParameters} block of an EventBridge rule target whose {@code Arn} points at
* an ECS cluster, mirroring the shape EventBridge's {@code PutTargets} accepts and
* {@code ListTargetsByRule} returns.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class EcsParameters {
private String taskDefinitionArn;
private Integer taskCount;
private String launchType;
private String group;
private NetworkConfiguration networkConfiguration;
private String platformVersion;
private String propagateTags;
private String referenceId;
private Boolean enableECSManagedTags;
private Boolean enableExecuteCommand;
private JsonNode capacityProviderStrategy;
private JsonNode placementConstraints;
private JsonNode placementStrategy;
private JsonNode tags;
public EcsParameters() {
}
@JsonProperty("TaskDefinitionArn")
public String getTaskDefinitionArn() {
return taskDefinitionArn;
}
@JsonProperty("TaskDefinitionArn")
public void setTaskDefinitionArn(String taskDefinitionArn) {
this.taskDefinitionArn = taskDefinitionArn;
}
@JsonProperty("TaskCount")
public Integer getTaskCount() {
return taskCount;
}
@JsonProperty("TaskCount")
public void setTaskCount(Integer taskCount) {
this.taskCount = taskCount;
}
@JsonProperty("LaunchType")
public String getLaunchType() {
return launchType;
}
@JsonProperty("LaunchType")
public void setLaunchType(String launchType) {
this.launchType = launchType;
}
@JsonProperty("Group")
public String getGroup() {
return group;
}
@JsonProperty("Group")
public void setGroup(String group) {
this.group = group;
}
@JsonProperty("NetworkConfiguration")
public NetworkConfiguration getNetworkConfiguration() {
return networkConfiguration;
}
@JsonProperty("NetworkConfiguration")
public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) {
this.networkConfiguration = networkConfiguration;
}
@JsonProperty("PlatformVersion")
public String getPlatformVersion() {
return platformVersion;
}
@JsonProperty("PlatformVersion")
public void setPlatformVersion(String platformVersion) {
this.platformVersion = platformVersion;
}
@JsonProperty("PropagateTags")
public String getPropagateTags() {
return propagateTags;
}
@JsonProperty("PropagateTags")
public void setPropagateTags(String propagateTags) {
this.propagateTags = propagateTags;
}
@JsonProperty("ReferenceId")
public String getReferenceId() {
return referenceId;
}
@JsonProperty("ReferenceId")
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@JsonProperty("EnableECSManagedTags")
public Boolean getEnableECSManagedTags() {
return enableECSManagedTags;
}
@JsonProperty("EnableECSManagedTags")
public void setEnableECSManagedTags(Boolean enableECSManagedTags) {
this.enableECSManagedTags = enableECSManagedTags;
}
@JsonProperty("EnableExecuteCommand")
public Boolean getEnableExecuteCommand() {
return enableExecuteCommand;
}
@JsonProperty("EnableExecuteCommand")
public void setEnableExecuteCommand(Boolean enableExecuteCommand) {
this.enableExecuteCommand = enableExecuteCommand;
}
@JsonProperty("CapacityProviderStrategy")
public JsonNode getCapacityProviderStrategy() {
return capacityProviderStrategy;
}
@JsonProperty("CapacityProviderStrategy")
public void setCapacityProviderStrategy(JsonNode capacityProviderStrategy) {
this.capacityProviderStrategy = capacityProviderStrategy;
}
@JsonProperty("PlacementConstraints")
public JsonNode getPlacementConstraints() {
return placementConstraints;
}
@JsonProperty("PlacementConstraints")
public void setPlacementConstraints(JsonNode placementConstraints) {
this.placementConstraints = placementConstraints;
}
@JsonProperty("PlacementStrategy")
public JsonNode getPlacementStrategy() {
return placementStrategy;
}
@JsonProperty("PlacementStrategy")
public void setPlacementStrategy(JsonNode placementStrategy) {
this.placementStrategy = placementStrategy;
}
@JsonProperty("Tags")
public JsonNode getTags() {
return tags;
}
@JsonProperty("Tags")
public void setTags(JsonNode tags) {
this.tags = tags;
}
}
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.services.eventbridge.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class NetworkConfiguration {
private AwsVpcConfiguration awsvpcConfiguration;
public NetworkConfiguration() {
}
public AwsVpcConfiguration getAwsvpcConfiguration() {
return awsvpcConfiguration;
}
public void setAwsvpcConfiguration(AwsVpcConfiguration awsvpcConfiguration) {
this.awsvpcConfiguration = awsvpcConfiguration;
}
}
@@ -14,6 +14,7 @@ public class Target {
private InputTransformer inputTransformer;
private SqsParameters sqsParameters;
private BatchParameters batchParameters;
private EcsParameters ecsParameters;
public Target() {}
@@ -44,4 +45,7 @@ public class Target {
public BatchParameters getBatchParameters() { return batchParameters; }
public void setBatchParameters(BatchParameters batchParameters) { this.batchParameters = batchParameters; }
public EcsParameters getEcsParameters() { return ecsParameters; }
public void setEcsParameters(EcsParameters ecsParameters) { this.ecsParameters = ecsParameters; }
}
@@ -0,0 +1,206 @@
package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
/**
* Verifies that a classic EventBridge rule target pointing at an ECS cluster (with
* {@code EcsParameters}, the shape Terraform's {@code aws_cloudwatch_event_target}
* {@code ecs_target} block or {@code aws events put-targets} produces) round-trips
* through PutTargets/ListTargetsByRule and actually calls ECS RunTask when the rule fires.
*/
@QuarkusTest
class EventBridgeEcsRunTaskIntegrationTest {
private static final String EVENT_BRIDGE_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ECS_TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113.";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void putEventsEcsClusterTargetRunsTaskWithEcsParameters() {
String suffix = Long.toString(System.nanoTime(), 36);
String clusterName = "eb-ecs-cluster-" + suffix;
String family = "eb-ecs-family-" + suffix;
String ruleName = "eb-ecs-rule-" + suffix;
String source = "local.ecstest";
String detailType = "EcsTestTrigger";
String clusterArn = createCluster(clusterName);
String taskDefinitionArn = registerTaskDefinition(family);
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.PutRule")
.body("""
{"Name":"%s","EventPattern":"{\\"source\\":[\\"%s\\"],\\"detail-type\\":[\\"%s\\"]}"}
""".formatted(ruleName, source, detailType))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.PutTargets")
.body("""
{
"Rule": "%s",
"Targets": [{
"Id": "ecs-target",
"Arn": "%s",
"EcsParameters": {
"TaskDefinitionArn": "%s",
"TaskCount": 1,
"LaunchType": "FARGATE",
"Group": "eb-ecs-group-%s",
"NetworkConfiguration": {
"awsvpcConfiguration": {
"Subnets": ["subnet-1", "subnet-2"],
"SecurityGroups": ["sg-1"],
"AssignPublicIp": "ENABLED"
}
}
}
}]
}
""".formatted(ruleName, clusterArn, taskDefinitionArn, suffix))
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedEntryCount", equalTo(0));
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.ListTargetsByRule")
.body("""
{"Rule": "%s"}
""".formatted(ruleName))
.when()
.post("/")
.then()
.statusCode(200)
.body("Targets[0].Arn", equalTo(clusterArn))
.body("Targets[0].EcsParameters.TaskDefinitionArn", equalTo(taskDefinitionArn))
.body("Targets[0].EcsParameters.TaskCount", equalTo(1))
.body("Targets[0].EcsParameters.LaunchType", equalTo("FARGATE"))
.body("Targets[0].EcsParameters.Group", equalTo("eb-ecs-group-" + suffix))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets",
hasItem("subnet-1"))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.SecurityGroups",
hasItem("sg-1"))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.AssignPublicIp",
equalTo("ENABLED"));
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.PutEvents")
.body("""
{
"Entries": [{
"Source": "%s",
"DetailType": "%s",
"Detail": "{}"
}]
}
""".formatted(source, detailType))
.when()
.post("/")
.then()
.statusCode(200);
ecs("ListTasks")
.body("""
{"cluster": "%s"}
""".formatted(clusterName))
.when()
.post("/")
.then()
.statusCode(200)
.body("taskArns", hasSize(1));
String taskArn = ecs("ListTasks")
.body("""
{"cluster": "%s"}
""".formatted(clusterName))
.when()
.post("/")
.then()
.extract().path("taskArns[0]");
ecs("DescribeTasks")
.body("""
{
"cluster": "%s",
"tasks": ["%s"]
}
""".formatted(clusterName, taskArn))
.when()
.post("/")
.then()
.statusCode(200)
.body("tasks[0].taskDefinitionArn", equalTo(taskDefinitionArn))
.body("tasks[0].launchType", equalTo("FARGATE"))
.body("tasks[0].startedBy", equalTo("eb-ecs-group-" + suffix))
.body("tasks[0].lastStatus", notNullValue());
}
private static String createCluster(String clusterName) {
return ecs("CreateCluster")
.body("""
{"clusterName": "%s"}
""".formatted(clusterName))
.when()
.post("/")
.then()
.statusCode(200)
.body("cluster.clusterArn", containsString(clusterName))
.extract().path("cluster.clusterArn");
}
private static String registerTaskDefinition(String family) {
return ecs("RegisterTaskDefinition")
.body("""
{
"family": "%s",
"containerDefinitions": [
{
"name": "app",
"image": "nginx:latest",
"cpu": 256,
"memory": 512,
"essential": true
}
],
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"networkMode": "awsvpc"
}
""".formatted(family))
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("taskDefinition.taskDefinitionArn");
}
private static io.restassured.specification.RequestSpecification ecs(String action) {
return given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", ECS_TARGET_PREFIX + action);
}
}
@@ -4,8 +4,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.eventbridge.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.NetworkConfiguration;
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;
@@ -34,6 +39,7 @@ class EventBridgeInvokerTest {
private BatchService batchService;
private FirehoseService firehoseService;
private EventBridgeService eventBridgeService;
private EcsService ecsService;
private RegionResolver regionResolver;
@BeforeEach
@@ -44,6 +50,7 @@ class EventBridgeInvokerTest {
batchService = mock(BatchService.class);
firehoseService = mock(FirehoseService.class);
eventBridgeService = mock(EventBridgeService.class);
ecsService = mock(EcsService.class);
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(eventBridgeService.putEvents(anyList(), anyString(), any()))
@@ -55,6 +62,8 @@ class EventBridgeInvokerTest {
batchService,
firehoseService,
eventBridgeService,
ecsService,
new io.github.hectorvent.floci.services.ecs.EcsJsonHandler(ecsService, new ObjectMapper()),
regionResolver,
new ObjectMapper(),
mock(io.github.hectorvent.floci.config.EmulatorConfig.class)
@@ -157,6 +166,138 @@ class EventBridgeInvokerTest {
);
}
@Test
void invokeTarget_ecsClusterTarget_runsTaskWithEcsParameters() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:3");
ecsParameters.setTaskCount(2);
ecsParameters.setLaunchType("FARGATE");
ecsParameters.setGroup("my-group");
AwsVpcConfiguration awsVpcConfiguration = new AwsVpcConfiguration();
awsVpcConfiguration.setSubnets(List.of("subnet-1", "subnet-2"));
awsVpcConfiguration.setSecurityGroups(List.of("sg-1"));
awsVpcConfiguration.setAssignPublicIp("ENABLED");
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
networkConfiguration.setAwsvpcConfiguration(awsVpcConfiguration);
ecsParameters.setNetworkConfiguration(networkConfiguration);
target.setEcsParameters(ecsParameters);
invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1");
ArgumentCaptor<io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration> networkCaptor =
ArgumentCaptor.forClass(io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration.class);
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:3"),
eq(2),
eq(LaunchType.FARGATE),
isNull(),
eq("my-group"),
eq(List.of()),
networkCaptor.capture(),
eq("us-west-2")
);
assertEquals(List.of("subnet-1", "subnet-2"),
networkCaptor.getValue().getAwsvpcConfiguration().getSubnets());
assertEquals(List.of("sg-1"),
networkCaptor.getValue().getAwsvpcConfiguration().getSecurityGroups());
assertEquals("ENABLED", networkCaptor.getValue().getAwsvpcConfiguration().getAssignPublicIp());
}
@Test
void invokeTarget_ecsClusterTarget_defaultsTaskCountAndGroupWhenAbsent() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1");
target.setEcsParameters(ecsParameters);
invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1");
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1"),
eq(1),
isNull(),
isNull(),
eq("eventbridge"),
eq(List.of()),
isNull(),
eq("us-west-2")
);
}
@Test
void invokeTarget_ecsClusterTargetWithInputTransformer_passesThroughContainerOverrides() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1");
target.setEcsParameters(ecsParameters);
target.setInputTransformer(new InputTransformer(
Map.of("orderId", "$.detail.orderId"),
"{\"containerOverrides\":[{\"name\":\"app\",\"command\":[\"process\",\"<orderId>\"],"
+ "\"environment\":[{\"name\":\"ORDER_ID\",\"value\":\"<orderId>\"}]}]}"));
invoker.invokeTarget(target, "{\"detail\":{\"orderId\":\"o-42\"}}", "us-east-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<io.github.hectorvent.floci.services.ecs.model.ContainerOverride>> overridesCaptor =
ArgumentCaptor.forClass(List.class);
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1"),
eq(1),
isNull(),
isNull(),
eq("eventbridge"),
overridesCaptor.capture(),
isNull(),
eq("us-west-2")
);
io.github.hectorvent.floci.services.ecs.model.ContainerOverride override = overridesCaptor.getValue().get(0);
assertEquals("app", override.getName());
assertEquals(List.of("process", "o-42"), override.getCommand());
assertEquals("ORDER_ID", override.getEnvironment().get(0).name());
assertEquals("o-42", override.getEnvironment().get(0).value());
}
@Test
void invokeTarget_ecsClusterTargetWithMalformedTransformedOutput_launchesWithoutOverrides() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
EcsParameters ecsParameters = new EcsParameters();
ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1");
target.setEcsParameters(ecsParameters);
target.setInput("not-json");
assertDoesNotThrow(() -> invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1"));
verify(ecsService).runTask(
eq("arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster"),
eq("arn:aws:ecs:us-west-2:000000000000:task-definition/my-task:1"),
eq(1),
isNull(),
isNull(),
eq("eventbridge"),
eq(List.of()),
isNull(),
eq("us-west-2")
);
}
@Test
void invokeTarget_ecsClusterTargetWithoutEcsParameters_skipsWithoutThrowing() {
Target target = new Target("id1",
"arn:aws:ecs:us-west-2:000000000000:cluster/my-cluster", null, null);
assertDoesNotThrow(() -> invoker.invokeTarget(target, "{\"detail\":{}}", "us-east-1"));
verify(ecsService, never()).runTask(any(), any(), anyInt(), any(), any(), any(), anyList(), any(), any());
}
@Test
void invokeTarget_firehoseTarget_putsEventJsonAsRecordData() {
Target target = new Target("id1",