feat(cloudformation): provision event bus v2 and subscriber (#7260)

This commit is contained in:
Ruslan Sovinskyy authored and GitHub committed 2026-11-03 17:27:11 -04:00
1 parent d9d2a1edd6
commit 4ba9a55a3a
14 files changed
+1260 -7

No files matched your search

@@ -107,6 +107,21 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::DeploymentStrategy", "GrowthFactor"));
}
@Test
void eventsV2CreateOnlyPropertiesMatchTheRegistrySchemas() {
assertEquals(Set.of("Name"), CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::EventsV2::EventBus"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::EventsV2::EventBus", "Description"));
String subscriber = "AWS::EventsV2::Subscriber";
assertEquals(Set.of("Name", "EventBusArn", "InvokeConfiguration/TargetArn", "Type", "StartingPosition",
"PointInTimeConfiguration"),
CfnCreateOnlyProperties.getCreateOnlyProperties(subscriber));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(subscriber, "EventBusArn"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(subscriber, "Type"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(subscriber, "InvokeConfiguration"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(subscriber, "SubscriberFilters"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(subscriber, "RetryPolicy"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
@@ -74,6 +74,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ElastiCac
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsArchiveCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.GuardDutyMalwareProtectionPlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamAccessKeyCfnProvisioner;
@@ -142,6 +143,7 @@ import io.github.hectorvent.floci.services.elasticache.ElastiCacheServerlessServ
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridgev2.EventBridgeV2Service;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.guardduty.GuardDutyService;
import io.github.hectorvent.floci.services.iam.IamService;
@@ -269,6 +271,7 @@ final class CfnProvisionerFixture {
private RedshiftService redshiftService;
private RedshiftServerlessService redshiftServerlessService;
private CloudMapService cloudMapService;
private EventBridgeV2Service eventBridgeV2Service;
private GuardDutyService guardDutyService;
private BedrockAgentCoreControlService bedrockAgentCoreControlService;
private BedrockAgentCoreMemoryService bedrockAgentCoreMemoryService;
@@ -532,6 +535,9 @@ final class CfnProvisionerFixture {
if (cloudMapService != null) {
discovered.add(new CloudMapCfnProvisioner(cloudMapService));
}
if (eventBridgeV2Service != null) {
discovered.add(new EventsV2CfnProvisioner(eventBridgeV2Service));
}
if (guardDutyService != null) {
discovered.add(new GuardDutyMalwareProtectionPlanCfnProvisioner(guardDutyService));
}
@@ -867,6 +873,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder eventBridgeV2(EventBridgeV2Service v) {
this.eventBridgeV2Service = v;
return this;
}
public Builder guardDuty(GuardDutyService v) {
this.guardDutyService = v;
return this;
@@ -129,7 +129,8 @@ class CfnSchemaCoverageTest {
* property of the type counts as read without a name appearing in the source. Explicit, one entry
* per helper: {@code camelisedProperties} (AppSync), {@code lowerKeys} over the resolved node
* (CodeBuild, CodePipeline), {@code jsonObjectToMap} over it (Cognito user pool), {@code
* toCamelCase} over it (Lambda web), {@code requestBody} (IoT domain configuration).
* toCamelCase} over it (Lambda web), {@code requestBody} (IoT domain configuration), {@code
* request} (EventBridge V2).
*/
private static final Set<String> WHOLESALE_CALLS = Set.of(
"camelisedProperties(props, ctx)",
@@ -137,7 +138,8 @@ class CfnSchemaCoverageTest {
"jsonObjectToMap(ctx.engine().resolveNode(props))",
"toCamelCase(ctx.engine().resolveNodeOmittingNoValue(props)",
"toCamelCase(resolved,",
"requestBody(props, ctx)");
"requestBody(props, ctx)",
"request(props, ctx)");
private static final String ALL_PROPERTIES = "*";
/** What the registry schemas declare for one resource type, see {@link #schemaSurface}. */
@@ -0,0 +1,297 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.eventbridgev2.EventBridgeV2Service;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client;
import software.amazon.awssdk.services.eventbridgev2.model.PutEventsRequestEntry;
import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.github.hectorvent.floci.testing.CfnStackWaits.awaitStackDeleted;
import static io.github.hectorvent.floci.testing.CfnStackWaits.awaitStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
/**
* A stack of an Amazon SQS queue, an {@code AWS::EventsV2::EventBus} and an {@code AWS::EventsV2::Subscriber} whose
* {@code FilterConfiguration} delivers only large orders to the queue, as {@code eventsv2.CfnSubscriber} synthesizes
* it. {@code Ref} of each is its ARN and every {@code Fn::GetAtt} attribute its schema declares resolves; an update
* of the filter changes the subscriber in place; the stack delete removes the subscriber and the bus.
*/
@QuarkusTest
class CloudFormationEventsV2SubscriberIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery";
private static final String LARGE = "{\"detail\":{\"total\":[{\"numeric\":[\">\",500]}]}}";
private static final String SMALL = "{\"detail\":{\"total\":[{\"numeric\":[\"<\",100]}]}}";
/** A target Floci does not deliver to, so creating a subscriber for it fails. */
private static final String NOT_A_QUEUE = "arn:aws:sns:us-east-1:000000000000:orders";
private final List<String> stacks = new ArrayList<>();
@InjectSpy
EventBridgeV2Service eventBridgeV2Service;
@BeforeAll
static void configureContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@AfterEach
void cleanUp() {
for (String stack : List.copyOf(stacks)) {
deleteStack(stack);
}
}
@Test
void aSubscriberFromATemplateDeliversTheEventsItsFilterMatches() throws Exception {
String suffix = suffix();
String stack = createStack(template("orders-" + suffix, LARGE));
awaitStatus(stack, "CREATE_COMPLETE");
String body = describeStack(stack);
String busArn = output(body, "BusRef");
assertTrue(busArn.matches("arn:aws:events:us-east-1:000000000000:event-busv2/orders-" + suffix
+ "/[a-z0-9]{25}"), busArn);
assertEquals(busArn, output(body, "BusArn"));
assertEquals("ACTIVE", output(body, "BusState"));
Instant.parse(output(body, "BusCreationTime"));
Instant.parse(output(body, "BusLastModifiedTime"));
String subscriberArn = output(body, "SubscriberRef");
assertTrue(subscriberArn.matches("arn:aws:events:us-east-1:000000000000:subscriber/large-orders/[a-z0-9]{25}"),
subscriberArn);
assertEquals(subscriberArn, output(body, "SubscriberArn"));
assertEquals("orders-" + suffix, output(body, "SubscriberBusName"));
Instant.parse(output(body, "SubscriberCreationTime"));
Instant.parse(output(body, "SubscriberLastModifiedTime"));
String queueUrl = output(body, "QueueUrl");
try (EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), "test", Region.US_EAST_1);
SqsClient sqs = AwsTestClients.create(SqsClient.builder(), "test", Region.US_EAST_1)) {
publish(events, busArn, 750, 40);
List<Message> messages = receive(sqs, queueUrl);
assertEquals(1, messages.size(), messages.toString());
assertEquals(750, MAPPER.readTree(messages.getFirst().body()).path("detail").path("total").asInt());
// A new pattern changes the subscriber in place.
updateStack(stack, template("orders-" + suffix, SMALL));
awaitStatus(stack, "UPDATE_COMPLETE");
body = describeStack(stack);
assertEquals(subscriberArn, output(body, "SubscriberRef"));
publish(events, busArn, 750, 40);
messages = receive(sqs, queueUrl);
assertEquals(1, messages.size(), messages.toString());
assertEquals(40, MAPPER.readTree(messages.getFirst().body()).path("detail").path("total").asInt());
deleteStack(stack);
assertThrows(ResourceNotFoundException.class, () -> publish(events, busArn, 750));
}
}
@Test
void aSameNameReplacementThatFailsToCreateRollsBackToTheOriginalSubscriber() throws Exception {
String suffix = suffix();
String stack = createStack(template("orders-" + suffix, LARGE));
awaitStatus(stack, "CREATE_COMPLETE");
String body = describeStack(stack);
String busArn = output(body, "BusRef");
String subscriberArn = output(body, "SubscriberRef");
String queueUrl = output(body, "QueueUrl");
updateStack(stack, template("orders-" + suffix, LARGE, "FIFO", NOT_A_QUEUE));
awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
try (EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), "test", Region.US_EAST_1);
SqsClient sqs = AwsTestClients.create(SqsClient.builder(), "test", Region.US_EAST_1)) {
assertEquals("UNORDERED", events.describeSubscriber(request -> request.subscriberArn(subscriberArn))
.typeAsString(), "the original subscriber is back under its own ARN");
publish(events, busArn, 750);
assertEquals(1, receive(sqs, queueUrl).size());
}
}
@Test
void aRollbackThatCannotRecreateTheSubscriberFailsAndContinueUpdateRollbackRetriesIt() throws Exception {
String suffix = suffix();
String stack = createStack(template("orders-" + suffix, LARGE));
awaitStatus(stack, "CREATE_COMPLETE");
String body = describeStack(stack);
String busArn = output(body, "BusRef");
String subscriberArn = output(body, "SubscriberRef");
String queueUrl = output(body, "QueueUrl");
AtomicBoolean restoresFail = new AtomicBoolean(true);
doAnswer(invocation -> {
if (restoresFail.get()) {
throw new AwsException("InternalException", "restore unavailable", 500);
}
return invocation.callRealMethod();
}).when(eventBridgeV2Service).restoreSubscriber(any(), any());
try (EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), "test", Region.US_EAST_1);
SqsClient sqs = AwsTestClients.create(SqsClient.builder(), "test", Region.US_EAST_1)) {
updateStack(stack, template("orders-" + suffix, LARGE, "FIFO", NOT_A_QUEUE));
awaitStatus(stack, "UPDATE_ROLLBACK_FAILED");
assertThrows(ResourceNotFoundException.class,
() -> events.describeSubscriber(request -> request.subscriberArn(subscriberArn)));
restoresFail.set(false);
cfn("ContinueUpdateRollback", stack).post("/").then().statusCode(200);
awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertEquals("UNORDERED", events.describeSubscriber(request -> request.subscriberArn(subscriberArn))
.typeAsString());
publish(events, busArn, 750);
assertEquals(1, receive(sqs, queueUrl).size());
}
}
@Test
void anInPlaceUpdateRollsBackWhenALaterResourceFails() throws Exception {
String suffix = suffix();
String stack = createStack(template("orders-" + suffix, LARGE));
awaitStatus(stack, "CREATE_COMPLETE");
String body = describeStack(stack);
String busArn = output(body, "BusRef");
String subscriberArn = output(body, "SubscriberRef");
String queueUrl = output(body, "QueueUrl");
// The bus and the subscriber change in place, then a subscriber the update adds fails to create.
ObjectNode failing = (ObjectNode) MAPPER.readTree(template("orders-" + suffix, SMALL));
((ObjectNode) failing.path("Resources").path("Bus").path("Properties")).put("Description", "changed");
ObjectNode broken = MAPPER.valueToTree(Map.of("Type", "AWS::EventsV2::Subscriber",
"DependsOn", List.of("Subscriber"), "Properties", Map.of("Name", "broken",
"EventBusArn", Map.of("Fn::GetAtt", List.of("Bus", "EventBusArn")),
"InvokeConfiguration", Map.of("TargetArn", NOT_A_QUEUE, "RoleArn", ROLE))));
((ObjectNode) failing.path("Resources")).set("Broken", broken);
updateStack(stack, MAPPER.writeValueAsString(failing));
awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
try (EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), "test", Region.US_EAST_1);
SqsClient sqs = AwsTestClients.create(SqsClient.builder(), "test", Region.US_EAST_1)) {
assertNull(events.describeEventBus(request -> request.eventBusArn(busArn)).description(),
"the bus is back to the settings it had");
assertEquals(LARGE, events.describeSubscriber(request -> request.subscriberArn(subscriberArn))
.filterConfiguration().filters().getFirst().pattern(), "the subscriber is back to its filter");
publish(events, busArn, 750, 40);
List<Message> messages = receive(sqs, queueUrl);
assertEquals(1, messages.size(), messages.toString());
assertEquals(750, MAPPER.readTree(messages.getFirst().body()).path("detail").path("total").asInt());
}
}
private static void publish(EventBridgeV2Client events, String busArn, int... totals) {
events.putEvents(request -> request.eventBusArn(busArn).entries(Arrays.stream(totals)
.mapToObj(total -> PutEventsRequestEntry.builder()
.source("com.shop").detailType("Order Placed").detail("{\"total\":" + total + "}").build())
.toList()));
}
private static List<Message> receive(SqsClient sqs, String queueUrl) {
List<Message> messages = sqs.receiveMessage(request -> request.queueUrl(queueUrl).maxNumberOfMessages(10)
.waitTimeSeconds(1)).messages();
for (Message message : messages) {
sqs.deleteMessage(request -> request.queueUrl(queueUrl).receiptHandle(message.receiptHandle()));
}
return messages;
}
private static String template(String busName, String pattern) throws Exception {
return template(busName, pattern, "UNORDERED", Map.of("Fn::GetAtt", List.of("Queue", "Arn")));
}
private static String template(String busName, String pattern, String type, Object targetArn) throws Exception {
Map<String, Object> subscriber = new LinkedHashMap<>();
subscriber.put("Name", "large-orders");
subscriber.put("EventBusArn", Map.of("Fn::GetAtt", List.of("Bus", "EventBusArn")));
subscriber.put("Type", type);
subscriber.put("InvokeConfiguration", Map.of("TargetArn", targetArn, "RoleArn", ROLE));
subscriber.put("FilterConfiguration", Map.of("Filters", List.of(Map.of("Scope", "DATA", "Pattern", pattern))));
subscriber.put("RetryPolicy", Map.of("MaxRetryAttempts", "3"));
Map<String, Object> resources = new LinkedHashMap<>();
resources.put("Queue", Map.of("Type", "AWS::SQS::Queue"));
resources.put("Bus", Map.of("Type", "AWS::EventsV2::EventBus", "Properties", Map.of("Name", busName,
"StorageConfiguration", Map.of("RetentionPeriodInDays", 7),
"Tags", List.of(Map.of("Key", "team", "Value", "orders")))));
resources.put("Subscriber", Map.of("Type", "AWS::EventsV2::Subscriber", "Properties", subscriber));
Map<String, Object> outputs = new LinkedHashMap<>();
outputs.put("QueueUrl", value(Map.of("Ref", "Queue")));
outputs.put("BusRef", value(Map.of("Ref", "Bus")));
for (String attribute : List.of("EventBusArn", "State", "CreationTime", "LastModifiedTime")) {
outputs.put("Bus" + attribute.replace("EventBus", ""), value(getAtt("Bus", attribute)));
}
outputs.put("SubscriberRef", value(Map.of("Ref", "Subscriber")));
for (String attribute : List.of("SubscriberArn", "BusName", "CreationTime", "LastModifiedTime")) {
outputs.put(attribute.startsWith("Subscriber") ? attribute : "Subscriber" + attribute,
value(getAtt("Subscriber", attribute)));
}
return MAPPER.writeValueAsString(Map.of("Resources", resources, "Outputs", outputs));
}
private static Map<String, Object> value(Object value) {
return Map.of("Value", value);
}
private static Map<String, Object> getAtt(String resource, String attribute) {
return Map.of("Fn::GetAtt", List.of(resource, attribute));
}
private String createStack(String template) {
String stack = "cfn-eventsv2-" + suffix();
cfn("CreateStack", stack).formParam("TemplateBody", template).post("/").then().statusCode(200);
stacks.add(stack);
return stack;
}
private static void updateStack(String stack, String template) {
cfn("UpdateStack", stack).formParam("TemplateBody", template).post("/").then().statusCode(200);
}
private void deleteStack(String stack) {
cfn("DeleteStack", stack).post("/").then().statusCode(200);
awaitStackDeleted(stack);
stacks.remove(stack);
}
private static String describeStack(String stack) {
return cfn("DescribeStacks", stack).post("/").then().statusCode(200).extract().asString();
}
private static String output(String body, String key) {
String value = XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue").get(key);
assertFalse(value == null || value.isBlank(), key + " in " + body);
return value;
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
}
@@ -0,0 +1,420 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.eventbridgev2.EventBridgeV2Service;
import io.github.hectorvent.floci.services.eventbridgev2.model.EventBusV2;
import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The EventBridge V2 provisioner in isolation, over a mocked service. */
class EventsV2CfnProvisionerTest {
private static final String REGION = "us-east-1";
private static final String BUS = "arn:aws:events:us-east-1:000000000000:event-busv2/orders/abcdefghijklmnopqrstuvwxy";
private static final String SUBSCRIBER =
"arn:aws:events:us-east-1:000000000000:subscriber/large/abcdefghijklmnopqrstuvwxy";
private static final String REPLACEMENT =
"arn:aws:events:us-east-1:000000000000:subscriber/large/zyxwvutsrqponmlkjihgfedcb";
private static final Instant NOW = Instant.parse("2026-10-28T12:00:00Z");
private static final String TARGET = "arn:aws:sqs:us-east-1:000000000000:q";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final EventBridgeV2Service service = mock(EventBridgeV2Service.class);
private final EventsV2CfnProvisioner provisioner = new EventsV2CfnProvisioner(service);
@Test
void aBusIsCreatedFromItsPropertiesAndSetsRefAndEveryAttribute() throws Exception {
when(service.createEventBus(any(), eq(REGION))).thenReturn(bus("orders"));
StackResource r = resource(EventsV2CfnProvisioner.EVENT_BUS);
provisioner.provision(r, json("{\"Name\":\"orders\",\"StorageConfiguration\":{\"RetentionPeriodInDays\":\"30\"},"
+ "\"Tags\":[{\"Key\":\"team\",\"Value\":\"orders\"}]}"), ctx(null));
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(service).createEventBus(request.capture(), eq(REGION));
assertEquals(30, request.getValue().path("StorageConfiguration").path("RetentionPeriodInDays").intValue(),
"an integer given as a string is the integer the API takes");
assertEquals("orders", request.getValue().path("Tags").path("team").asText(), "tags are the API's map");
assertEquals(BUS, r.getPhysicalId());
assertEquals(BUS, r.getAttributes().get("EventBusArn"));
assertEquals("ACTIVE", r.getAttributes().get("State"));
assertEquals(NOW.toString(), r.getAttributes().get("CreationTime"));
assertEquals(NOW.toString(), r.getAttributes().get("LastModifiedTime"));
}
@Test
void anUpdateKeepingTheBusNameChangesItInPlace() throws Exception {
when(service.findEventBus(BUS, REGION)).thenReturn(Optional.of(bus("orders")));
when(service.replaceEventBusSettings(eq(BUS), any(), eq(REGION))).thenReturn(bus("orders"));
provisioner.provision(resource(EventsV2CfnProvisioner.EVENT_BUS),
json("{\"Name\":\"orders\",\"Description\":\"new\"}"), ctx(BUS));
verify(service).replaceEventBusSettings(eq(BUS), any(), eq(REGION));
verify(service, never()).createEventBus(any(), anyString());
}
@Test
void rollingBackAnInPlaceBusUpdatePutsBackTheSettingsItHadBefore() throws Exception {
EventBusV2 before = bus("orders");
before.setDescription("old");
when(service.findEventBus(BUS, REGION)).thenReturn(Optional.of(before));
when(service.replaceEventBusSettings(eq(BUS), any(), eq(REGION))).thenAnswer(inv -> {
before.setDescription("new");
return before;
});
when(service.restoreEventBus(any(), eq(REGION))).thenAnswer(inv -> inv.getArgument(0));
StackResource r = resource(EventsV2CfnProvisioner.EVENT_BUS);
provisioner.provision(r, json("{\"Name\":\"orders\",\"Description\":\"new\"}"), ctx(BUS));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<EventBusV2> restored = ArgumentCaptor.forClass(EventBusV2.class);
verify(service).restoreEventBus(restored.capture(), eq(REGION));
assertEquals("old", restored.getValue().getDescription(), "the snapshot is taken before the change");
assertEquals(BUS, r.getPhysicalId());
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.UPDATED_PRIOR_ATTR));
}
@Test
void aBusWithoutANameIsAValidationError() {
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource(EventsV2CfnProvisioner.EVENT_BUS), json("{}"), ctx(null)));
assertEquals("ValidationError", e.getErrorCode());
}
@Test
void aSubscriberIsCreatedAndSetsRefAndEveryAttribute() throws Exception {
when(service.createSubscriber(any(), eq(REGION))).thenReturn(subscriber("large", "LATEST"));
StackResource r = resource(EventsV2CfnProvisioner.SUBSCRIBER);
provisioner.provision(r, json(subscriberProperties("")), ctx(null));
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(service).createSubscriber(request.capture(), eq(REGION));
assertEquals("DATA", request.getValue().path("FilterConfiguration").path("Filters").path(0).path("Scope").asText());
assertEquals(SUBSCRIBER, r.getPhysicalId());
assertEquals(SUBSCRIBER, r.getAttributes().get("SubscriberArn"));
assertEquals("orders", r.getAttributes().get("BusName"));
assertEquals(NOW.toString(), r.getAttributes().get("CreationTime"));
assertEquals(NOW.toString(), r.getAttributes().get("LastModifiedTime"));
}
@Test
void anUpdateKeepingTheSubscribersIdentityChangesItInPlace() throws Exception {
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(subscriber("large", "LATEST")));
when(service.replaceSubscriberSettings(eq(SUBSCRIBER), any(), eq(REGION)))
.thenReturn(subscriber("large", "LATEST"));
provisioner.provision(resource(EventsV2CfnProvisioner.SUBSCRIBER),
json(subscriberProperties(",\"ResumePosition\":\"LATEST\"")), ctx(SUBSCRIBER));
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(service).replaceSubscriberSettings(eq(SUBSCRIBER), request.capture(), eq(REGION));
assertFalse(request.getValue().has("ResumePosition"), "ResumePosition is not a subscriber setting");
verify(service, never()).createSubscriber(any(), anyString());
}
@Test
void anUpdateChangingTheSubscribersNameCreatesItAndLeavesTheOldOneToTheCleanup() throws Exception {
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(subscriber("large", "LATEST")));
when(service.createSubscriber(any(), eq(REGION))).thenReturn(subscriber("renamed", "LATEST"));
provisioner.provision(resource(EventsV2CfnProvisioner.SUBSCRIBER),
json(subscriberProperties("").replace("\"large\"", "\"renamed\"")), ctx(SUBSCRIBER));
verify(service).createSubscriber(any(), eq(REGION));
verify(service, never()).deleteSubscriber(anyString(), anyString());
}
/** The target is create-only in the type's schema, so a new one replaces the subscriber. */
@Test
void anUpdateChangingTheSubscribersTargetReplacesIt() throws Exception {
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(subscriber("large", "LATEST")));
when(service.createSubscriber(any(), eq(REGION))).thenReturn(subscriber("large", "LATEST"));
provisioner.provision(resource(EventsV2CfnProvisioner.SUBSCRIBER),
json(subscriberProperties("").replace(TARGET, TARGET + "-other")), ctx(SUBSCRIBER));
verify(service, never()).replaceSubscriberSettings(anyString(), any(), anyString());
verify(service).deleteSubscriber(SUBSCRIBER, REGION);
verify(service).createSubscriber(any(), eq(REGION));
}
@Test
void anUpdateReplacingTheSubscriberUnderItsOwnNameDeletesItBeforeCreatingTheReplacement() throws Exception {
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(subscriber("large", "LATEST")));
when(service.createSubscriber(any(), eq(REGION))).thenReturn(subscriber("large", "LATEST"));
provisioner.provision(resource(EventsV2CfnProvisioner.SUBSCRIBER),
json(subscriberProperties(",\"Type\":\"FIFO\"")), ctx(SUBSCRIBER));
InOrder order = inOrder(service);
order.verify(service).deleteSubscriber(SUBSCRIBER, REGION);
order.verify(service).createSubscriber(any(), eq(REGION));
}
@Test
void rollingBackASameNameReplacementDeletesTheReplacementAndRecreatesThePriorSubscriber() throws Exception {
StackResource r = replacedUnderItsOwnName();
when(service.restoreSubscriber(any(), eq(REGION))).thenAnswer(inv -> inv.getArgument(0));
assertTrue(provisioner.rollbackUpdate(r));
InOrder order = inOrder(service);
order.verify(service).deleteSubscriber(REPLACEMENT, REGION);
ArgumentCaptor<SubscriberV2> restored = ArgumentCaptor.forClass(SubscriberV2.class);
order.verify(service).restoreSubscriber(restored.capture(), eq(REGION));
assertEquals(SUBSCRIBER, restored.getValue().getArn());
assertEquals("UNORDERED", restored.getValue().getType());
assertEquals(NOW, restored.getValue().getCreationTime());
assertEquals(SUBSCRIBER, r.getPhysicalId());
assertEquals(SUBSCRIBER, r.getAttributes().get("SubscriberArn"));
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.DELETED_PRIOR_ATTR));
}
@Test
void aRollbackThatCannotRecreateThePriorSubscriberFailsAndKeepsItsSnapshot() throws Exception {
StackResource r = replacedUnderItsOwnName();
when(service.restoreSubscriber(any(), eq(REGION)))
.thenThrow(new AwsException("ResourceNotFoundException", "bus gone", 404));
AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("ResourceNotFoundException", e.getErrorCode());
assertTrue(r.getAttributes().containsKey(EventsV2CfnProvisioner.DELETED_PRIOR_ATTR),
"the snapshot stays for a retried rollback");
}
@Test
void aFailedRestoreKeepsTheFailedStateAndIsRetriedBeforeTheNextUpdate() throws Exception {
StackResource r = replacedUnderItsOwnName();
when(service.restoreSubscriber(any(), eq(REGION)))
.thenThrow(new AwsException("InternalException", "restore unavailable", 500));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
r.setStatus("UPDATE_FAILED");
assertTrue(provisioner.retainsFailedUpdateState(r), "the engine must not swap in the pre-update copy");
assertTrue(provisioner.requiresUpdateRecovery(r));
SubscriberV2 prior = subscriber("large", "LATEST");
reset(service);
when(service.restoreSubscriber(any(), eq(REGION))).thenAnswer(inv -> inv.getArgument(0));
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(prior));
when(service.replaceSubscriberSettings(eq(SUBSCRIBER), any(), eq(REGION))).thenReturn(prior);
provisioner.provision(r, json(subscriberProperties("")), ctx(SUBSCRIBER));
InOrder order = inOrder(service);
order.verify(service).restoreSubscriber(any(), eq(REGION));
order.verify(service).replaceSubscriberSettings(eq(SUBSCRIBER), any(), eq(REGION));
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.DELETED_PRIOR_ATTR));
}
@Test
void rollingBackAnInPlaceSubscriberUpdatePutsBackTheSettingsItHadBefore() throws Exception {
StackResource r = updatedInPlace();
when(service.restoreSubscriber(any(), eq(REGION))).thenAnswer(inv -> inv.getArgument(0));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<SubscriberV2> restored = ArgumentCaptor.forClass(SubscriberV2.class);
verify(service).restoreSubscriber(restored.capture(), eq(REGION));
assertEquals("old", restored.getValue().getDescription());
assertEquals(SUBSCRIBER, r.getPhysicalId());
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.UPDATED_PRIOR_ATTR));
verify(service, never()).deleteSubscriber(anyString(), anyString());
}
@Test
void anInPlaceRestoreThatFailsKeepsItsSnapshotForTheNextAttempt() throws Exception {
StackResource r = updatedInPlace();
when(service.restoreSubscriber(any(), eq(REGION)))
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertTrue(r.getAttributes().containsKey(EventsV2CfnProvisioner.UPDATED_PRIOR_ATTR));
}
@Test
void committingAnInPlaceUpdateDropsTheSnapshot() throws Exception {
StackResource r = updatedInPlace();
provisioner.completeUpdate(r);
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.UPDATED_PRIOR_ATTR));
}
@Test
void aRollbackOfAnUpdateThatChangedNothingSucceeds() {
assertTrue(provisioner.rollbackUpdate(resource(EventsV2CfnProvisioner.SUBSCRIBER)));
}
/** A subscriber whose description an update changed in place from {@code old}. */
private StackResource updatedInPlace() throws Exception {
SubscriberV2 before = subscriber("large", "LATEST");
before.setDescription("old");
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(before));
when(service.replaceSubscriberSettings(eq(SUBSCRIBER), any(), eq(REGION))).thenAnswer(inv -> {
before.setDescription("new");
return before;
});
StackResource r = resource(EventsV2CfnProvisioner.SUBSCRIBER);
provisioner.provision(r, json(subscriberProperties(",\"Description\":\"new\"")), ctx(SUBSCRIBER));
return r;
}
@Test
void committingASameNameReplacementDropsTheSnapshot() throws Exception {
StackResource r = replacedUnderItsOwnName();
provisioner.completeUpdate(r);
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.DELETED_PRIOR_ATTR));
}
@Test
void aSameNameReplacementThatFailsToCreateRecreatesThePriorSubscriber() throws Exception {
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(subscriber("large", "LATEST")));
when(service.createSubscriber(any(), eq(REGION)))
.thenThrow(new AwsException("InvalidInputException", "bad target", 400));
when(service.restoreSubscriber(any(), eq(REGION))).thenAnswer(inv -> inv.getArgument(0));
StackResource r = resource(EventsV2CfnProvisioner.SUBSCRIBER);
r.setPhysicalId(SUBSCRIBER);
JsonNode properties = json(subscriberProperties(",\"Type\":\"FIFO\""));
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, properties, ctx(SUBSCRIBER)));
assertEquals("InvalidInputException", e.getErrorCode());
ArgumentCaptor<SubscriberV2> restored = ArgumentCaptor.forClass(SubscriberV2.class);
verify(service).restoreSubscriber(restored.capture(), eq(REGION));
assertEquals(SUBSCRIBER, restored.getValue().getArn());
assertEquals(SUBSCRIBER, r.getPhysicalId());
assertFalse(r.getAttributes().containsKey(EventsV2CfnProvisioner.DELETED_PRIOR_ATTR));
}
/** A subscriber resource whose update replaced it under its own name, the prior one deleted first. */
private StackResource replacedUnderItsOwnName() throws Exception {
when(service.findSubscriber(SUBSCRIBER, REGION)).thenReturn(Optional.of(subscriber("large", "LATEST")));
SubscriberV2 replacement = subscriber("large", "LATEST");
replacement.setArn(REPLACEMENT);
replacement.setType("FIFO");
when(service.createSubscriber(any(), eq(REGION))).thenReturn(replacement);
StackResource r = resource(EventsV2CfnProvisioner.SUBSCRIBER);
r.setPhysicalId(SUBSCRIBER);
provisioner.provision(r, json(subscriberProperties(",\"Type\":\"FIFO\"")), ctx(SUBSCRIBER));
assertEquals(REPLACEMENT, r.getPhysicalId());
assertTrue(r.getAttributes().containsKey(EventsV2CfnProvisioner.DELETED_PRIOR_ATTR));
return r;
}
@Test
void aPointInTimeGivenAsAStringIsTheEpochSecondsTheApiTakes() throws Exception {
when(service.createSubscriber(any(), eq(REGION))).thenReturn(subscriber("large", "POINT_IN_TIME"));
provisioner.provision(resource(EventsV2CfnProvisioner.SUBSCRIBER), json(subscriberProperties(
",\"StartingPosition\":\"POINT_IN_TIME\",\"PointInTimeConfiguration\":{\"PointType\":\"TIMESTAMP\","
+ "\"StartingPoint\":\"1767225600\",\"EndPoint\":1767312000}")), ctx(null));
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(service).createSubscriber(request.capture(), eq(REGION));
JsonNode pointInTime = request.getValue().path("PointInTimeConfiguration");
assertTrue(pointInTime.path("StartingPoint").isIntegralNumber(), pointInTime.toString());
assertEquals(1767225600L, pointInTime.path("StartingPoint").longValue());
assertEquals(1767312000L, pointInTime.path("EndPoint").longValue());
}
@Test
void servesNothingWhileTheEventBridgeV2ServiceIsDisabled() {
assertFalse(provisioner.serviceDisabled());
when(service.isDisabled()).thenReturn(true);
assertTrue(provisioner.serviceDisabled());
assertEquals("floci.services.eventbridgev2.enabled", provisioner.serviceEnabledFlag());
}
@Test
void deleteToleratesAResourceAlreadyGoneAndPropagatesAnyOtherFailure() {
doThrow(new AwsException("ResourceNotFoundException", "gone", 404))
.when(service).deleteSubscriber(SUBSCRIBER, REGION);
provisioner.delete(EventsV2CfnProvisioner.SUBSCRIBER, SUBSCRIBER, REGION);
doThrow(new AwsException("ResourceInUseException", "has subscribers", 409))
.when(service).deleteEventBus(BUS, REGION);
AwsException e = assertThrows(AwsException.class,
() -> provisioner.delete(EventsV2CfnProvisioner.EVENT_BUS, BUS, REGION));
assertEquals("ResourceInUseException", e.getErrorCode());
}
private String subscriberProperties(String extra) {
return "{\"Name\":\"large\",\"EventBusArn\":\"" + BUS + "\",\"InvokeConfiguration\":{\"TargetArn\":"
+ "\"" + TARGET + "\",\"RoleArn\":\"arn:aws:iam::000000000000:role/r\"},"
+ "\"FilterConfiguration\":{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":\"{}\"}]}" + extra + "}";
}
private static EventBusV2 bus(String name) {
EventBusV2 bus = new EventBusV2();
bus.setName(name);
bus.setArn(BUS);
bus.setState("ACTIVE");
bus.setCreationTime(NOW);
bus.setLastModifiedTime(NOW);
return bus;
}
private static SubscriberV2 subscriber(String name, String startingPosition) {
SubscriberV2 subscriber = new SubscriberV2();
subscriber.setName(name);
subscriber.setArn(SUBSCRIBER);
subscriber.setEventBusArn(BUS);
subscriber.setType("UNORDERED");
subscriber.setStartingPosition(startingPosition);
subscriber.setInvokeConfiguration(MAPPER.createObjectNode().put("TargetArn", TARGET));
subscriber.setCreationTime(NOW);
subscriber.setLastModifiedTime(NOW);
return subscriber;
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
return new ProvisionContext(engine, REGION, "000000000000", "stack", priorPhysicalId);
}
private static StackResource resource(String type) {
StackResource r = new StackResource();
r.setLogicalId("Resource");
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private JsonNode json(String value) throws Exception {
return MAPPER.readTree(value);
}
}
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -47,6 +49,7 @@ class EventBridgeV2ServiceTest {
private static final String ACCOUNT = "000000000000";
private static final Instant NOW = Instant.parse("2026-10-28T12:00:00.123Z");
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final ObjectMapper SNAPSHOTS = JsonMapper.builder().addModule(new JavaTimeModule()).build();
private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:orders";
private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery";
@@ -58,7 +61,7 @@ class EventBridgeV2ServiceTest {
delivery = mock(EventBridgeV2Delivery.class);
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), new RegionResolver(REGION, ACCOUNT), delivery,
Clock.fixed(NOW, ZoneOffset.UTC));
Clock.fixed(NOW, ZoneOffset.UTC), true);
}
@Test
@@ -332,6 +335,82 @@ class EventBridgeV2ServiceTest {
assertTrue(service.findEventBus(bus, REGION).isEmpty());
}
@Test
void restoreSubscriberPutsADeletedSubscriberBackUnderItsOwnArn() {
String bus = bus("orders");
SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus, ",\"Description\":\"d\"")),
REGION);
service.deleteSubscriber(created.getArn(), REGION);
service.restoreSubscriber(created, REGION);
SubscriberV2 restored = service.findSubscriber(created.getArn(), REGION).orElseThrow();
assertEquals("d", restored.getDescription());
assertEquals(created.getCreationTime(), restored.getCreationTime());
assertEquals(created.getArn(), service.restoreSubscriber(created, REGION).getArn(), "a repeat is a no-op");
}
@Test
void restoreSubscriberPutsBackSettingsAnUpdateChangedInPlace() throws Exception {
String bus = bus("orders");
SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus, ",\"Description\":\"old\"")),
REGION);
SubscriberV2 before = snapshot(created, SubscriberV2.class);
service.replaceSubscriberSettings(created.getArn(), json(subscriberRequest("s", bus,
",\"Description\":\"new\"")), REGION);
service.restoreSubscriber(before, REGION);
assertEquals("old", service.findSubscriber(created.getArn(), REGION).orElseThrow().getDescription());
}
@Test
void restoreEventBusPutsBackSettingsAnUpdateChangedInPlace() throws Exception {
String bus = service.createEventBus(json("{\"Name\":\"orders\",\"Description\":\"old\","
+ "\"Tags\":{\"team\":\"a\"}}"), REGION).getArn();
EventBusV2 before = snapshot(service.findEventBus(bus, REGION).orElseThrow(), EventBusV2.class);
service.replaceEventBusSettings(bus, json("{\"Name\":\"orders\",\"Description\":\"new\"}"), REGION);
service.restoreEventBus(before, REGION);
EventBusV2 restored = service.findEventBus(bus, REGION).orElseThrow();
assertEquals("old", restored.getDescription());
assertEquals(Map.of("team", "a"), restored.getTags());
}
@Test
void restoreEventBusKeepsTheSequenceNumbersPublishedSinceTheSnapshot() throws Exception {
String bus = bus("orders");
EventBusV2 before = snapshot(service.findEventBus(bus, REGION).orElseThrow(), EventBusV2.class);
String event = "{\"EventBusArn\":\"" + bus + "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}]}";
assertEquals("1", service.putEvents(json(event), REGION).getFirst().sequenceNumber());
service.restoreEventBus(before, REGION);
assertEquals("2", service.putEvents(json(event), REGION).getFirst().sequenceNumber());
}
@Test
void restoreEventBus_busGone_resourceNotFound() throws Exception {
String bus = bus("orders");
EventBusV2 before = snapshot(service.findEventBus(bus, REGION).orElseThrow(), EventBusV2.class);
service.deleteEventBus(bus, REGION);
AwsException e = assertThrows(AwsException.class, () -> service.restoreEventBus(before, REGION));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void restoreSubscriber_nameTakenByAnotherSubscriber_resourceAlreadyExists() {
String bus = bus("orders");
SubscriberV2 deleted = service.createSubscriber(json(subscriberRequest("s", bus, "")), REGION);
service.deleteSubscriber(deleted.getArn(), REGION);
service.createSubscriber(json(subscriberRequest("s", bus, "")), REGION);
AwsException e = assertThrows(AwsException.class, () -> service.restoreSubscriber(deleted, REGION));
assertEquals("ResourceAlreadyExistsException", e.getErrorCode());
}
@Test
void deleteSubscriber_unknown_resourceNotFound() {
AwsException e = assertThrows(AwsException.class, () -> service.deleteSubscriber(
@@ -631,6 +710,11 @@ class EventBridgeV2ServiceTest {
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
/** A copy of what the service stores, as a CloudFormation update snapshots it before changing it. */
private static <T> T snapshot(T resource, Class<T> type) throws Exception {
return SNAPSHOTS.readValue(SNAPSHOTS.writeValueAsString(resource), type);
}
private String bus(String name) {
return service.createEventBus(json("{\"Name\":\"" + name + "\"}"), REGION).getArn();
}