mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision event bus v2 and subscriber (#7260)
This commit is contained in:
1 parent
d9d2a1edd6
commit
4ba9a55a3a
14 files changed
+1260
-7
No files matched your search
@@ -214,6 +214,7 @@ cross-resource references.
|
||||
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolIdentityProvider` (Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template's and the replacement would need the same address), `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) |
|
||||
| EventBridge V2 | `EventBus`, `Subscriber` (delivers only to Amazon SQS queues; `Transformer` RAW or WITH_METADATA; a target parameter takes a literal or a `$events` path) |
|
||||
| EventBridge Scheduler | `Schedule`, `ScheduleGroup` |
|
||||
| Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported), `User` (management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user) |
|
||||
| Backup | `BackupVault` |
|
||||
|
||||
@@ -106,6 +106,30 @@ Where the two APIs share an operation name, the API serving the request decides
|
||||
checked, not the members the request gives. An EventBridge request that adds a V2 bus's
|
||||
`EventBusArn` is still checked on the EventBridge bus it acts on.
|
||||
|
||||
## CloudFormation
|
||||
|
||||
`AWS::EventsV2::EventBus` and `AWS::EventsV2::Subscriber` are provisioned from their properties.
|
||||
`Ref` returns the ARN of each.
|
||||
|
||||
| Type | `Fn::GetAtt` |
|
||||
| --- | --- |
|
||||
| `AWS::EventsV2::EventBus` | `EventBusArn`, `State`, `CreationTime`, `LastModifiedTime` |
|
||||
| `AWS::EventsV2::Subscriber` | `SubscriberArn`, `BusName`, `CreationTime`, `LastModifiedTime` |
|
||||
|
||||
An update that keeps a bus's `Name` changes it in place. An update that keeps a subscriber's `Name`,
|
||||
`EventBusArn`, `InvokeConfiguration.TargetArn`, `Type`, `StartingPosition` and `PointInTimeConfiguration`
|
||||
changes the rest in place.
|
||||
Changing any of them replaces the subscriber. With a new `Name`, the new subscriber is created and the
|
||||
old one deleted once the update completes. Under the same `Name`, the old subscriber is deleted first and
|
||||
then created again, the `delete_then_create` replacement its schema declares. If that update rolls back,
|
||||
or the new subscriber cannot be created, the old subscriber is recreated with its original ARN and
|
||||
settings; a rollback that cannot recreate it fails rather than reporting success. An update rolled back after
|
||||
changing a bus or subscriber in place puts back the settings it had.
|
||||
|
||||
With `aws-cdk-lib` 2.272 to 2.273, `CfnSubscriber` lacks its `invokeConfiguration` prop
|
||||
([aws/aws-cdk#38996](https://github.com/aws/aws-cdk/issues/38996)); set it with
|
||||
`addPropertyOverride("InvokeConfiguration", {...})`.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
import com.fasterxml.jackson.databind.node.BigIntegerNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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 jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Provisions EventBridge V2's {@code AWS::EventsV2::EventBus} and {@code AWS::EventsV2::Subscriber}. A template's
|
||||
* properties are the service's request members, so the resolved properties are the request.
|
||||
*
|
||||
* <p>Both are named by their ARN, which {@code Ref} returns. An update that keeps a bus's {@code Name} changes its
|
||||
* description, encryption, storage and tags in place; one that changes it creates a new bus and leaves the old one
|
||||
* to the {@link ReplacementCleanup} record. An update that keeps a subscriber's name, bus, target, type, starting
|
||||
* position and point in time changes the rest in place; one that changes any of them replaces it. A replacement that keeps
|
||||
* the subscriber's name deletes it before creating the new one, the {@code delete_then_create} replacement its schema
|
||||
* declares, after snapshotting it ({@link #DELETED_PRIOR_ATTR}) so a rollback, or the create failing, recreates it
|
||||
* under its own ARN. An in-place update of either snapshots it first ({@link #UPDATED_PRIOR_ATTR}) so a rollback
|
||||
* puts its settings back.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EventsV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
static final String EVENT_BUS = "AWS::EventsV2::EventBus";
|
||||
static final String SUBSCRIBER = "AWS::EventsV2::Subscriber";
|
||||
|
||||
/**
|
||||
* The subscriber a same-name replacement deleted, as JSON, kept until the update commits or rolls back so a
|
||||
* rollback can recreate it under its own ARN.
|
||||
*/
|
||||
static final String DELETED_PRIOR_ATTR = "__FlociEventsV2DeletedSubscriber";
|
||||
|
||||
/**
|
||||
* The bus or subscriber an in-place update changed, as JSON from before the change, kept until the update commits
|
||||
* or rolls back so a rollback can put its settings back.
|
||||
*/
|
||||
static final String UPDATED_PRIOR_ATTR = "__FlociEventsV2UpdatedPrior";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final ObjectMapper SNAPSHOT_MAPPER = JsonMapper.builder()
|
||||
.addModule(new JavaTimeModule())
|
||||
.build();
|
||||
private static final Pattern WHOLE_NUMBER = Pattern.compile("-?\\d+");
|
||||
/** The integer members a template may give as a string, as a parameter reference resolves to one. */
|
||||
private static final Map<String, List<String>> INTEGER_MEMBERS = Map.of(
|
||||
"StorageConfiguration", List.of("RetentionPeriodInDays"),
|
||||
"BatchConfiguration", List.of("MaxBatchSize", "MaxBatchWindowInSeconds"),
|
||||
"RetryPolicy", List.of("MaxRetryAttempts", "MaxEventAgeInSeconds"),
|
||||
"PointInTimeConfiguration", List.of("StartingPoint", "EndPoint"));
|
||||
|
||||
private final EventBridgeV2Service service;
|
||||
|
||||
@Inject
|
||||
public EventsV2CfnProvisioner(EventBridgeV2Service service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(EVENT_BUS, SUBSCRIBER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean serviceDisabled() {
|
||||
return service.isDisabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serviceEnabledFlag() {
|
||||
return "floci.services.eventbridgev2.enabled";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case EVENT_BUS -> provisionEventBus(r, props, ctx);
|
||||
case SUBSCRIBER -> provisionSubscriber(r, props, ctx);
|
||||
default -> throw new IllegalStateException("EventsV2CfnProvisioner cannot handle " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionEventBus(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
// A snapshot describes the update in flight; one an earlier update left behind is stale.
|
||||
r.getAttributes().remove(UPDATED_PRIOR_ATTR);
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
ObjectNode request = request(props, ctx);
|
||||
String name = requireName(request, EVENT_BUS);
|
||||
Optional<EventBusV2> prior = ctx.isUpdate()
|
||||
? service.findEventBus(ctx.priorPhysicalId(), ctx.region()) : Optional.empty();
|
||||
EventBusV2 bus;
|
||||
if (prior.isPresent() && prior.get().getName().equals(name)) {
|
||||
r.getAttributes().put(UPDATED_PRIOR_ATTR, writeSnapshot(prior.get()));
|
||||
bus = service.replaceEventBusSettings(ctx.priorPhysicalId(), request, ctx.region());
|
||||
} else {
|
||||
bus = service.createEventBus(request, ctx.region());
|
||||
}
|
||||
publishBusAttributes(r, bus);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private static void publishBusAttributes(StackResource r, EventBusV2 bus) {
|
||||
r.setPhysicalId(bus.getArn());
|
||||
r.getAttributes().put("EventBusArn", bus.getArn());
|
||||
r.getAttributes().put("State", bus.getState());
|
||||
r.getAttributes().put("CreationTime", bus.getCreationTime().toString());
|
||||
r.getAttributes().put("LastModifiedTime", bus.getLastModifiedTime().toString());
|
||||
}
|
||||
|
||||
private void provisionSubscriber(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
if (requiresUpdateRecovery(r)) {
|
||||
restoreDeletedPrior(r);
|
||||
}
|
||||
r.getAttributes().remove(DELETED_PRIOR_ATTR);
|
||||
r.getAttributes().remove(UPDATED_PRIOR_ATTR);
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
ObjectNode request = request(props, ctx);
|
||||
request.remove("ResumePosition");
|
||||
requireName(request, SUBSCRIBER);
|
||||
Optional<SubscriberV2> prior = ctx.isUpdate()
|
||||
? service.findSubscriber(ctx.priorPhysicalId(), ctx.region()) : Optional.empty();
|
||||
SubscriberV2 subscriber;
|
||||
if (prior.isPresent() && sameIdentity(prior.get(), request)) {
|
||||
r.getAttributes().put(UPDATED_PRIOR_ATTR, writeSnapshot(prior.get()));
|
||||
subscriber = service.replaceSubscriberSettings(ctx.priorPhysicalId(), request, ctx.region());
|
||||
} else {
|
||||
if (prior.isPresent() && prior.get().getName().equals(request.path("Name").asText())) {
|
||||
r.getAttributes().put(DELETED_PRIOR_ATTR, writeSnapshot(prior.get()));
|
||||
service.deleteSubscriber(prior.get().getArn(), ctx.region());
|
||||
}
|
||||
try {
|
||||
subscriber = service.createSubscriber(request, ctx.region());
|
||||
} catch (RuntimeException createFailure) {
|
||||
if (r.getAttributes().containsKey(DELETED_PRIOR_ATTR)) {
|
||||
try {
|
||||
restoreDeletedPrior(r);
|
||||
} catch (RuntimeException restoreFailure) {
|
||||
// The snapshot stays on the failed resource, which retainsFailedUpdateState keeps for
|
||||
// the rollback walker, so rollbackUpdate retries the restore and reports it if it fails.
|
||||
createFailure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
throw createFailure;
|
||||
}
|
||||
}
|
||||
publishSubscriberAttributes(r, subscriber);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private static void publishSubscriberAttributes(StackResource r, SubscriberV2 subscriber) {
|
||||
r.setPhysicalId(subscriber.getArn());
|
||||
r.getAttributes().put("SubscriberArn", subscriber.getArn());
|
||||
r.getAttributes().put("BusName", EventBridgeV2Service.busName(subscriber.getEventBusArn()));
|
||||
r.getAttributes().put("CreationTime", subscriber.getCreationTime().toString());
|
||||
r.getAttributes().put("LastModifiedTime", subscriber.getLastModifiedTime().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts back the subscriber a same-name replacement deleted, from the snapshot taken before the delete, and points
|
||||
* the resource at it again. The snapshot is spent only once the restore succeeded, so a restore that throws is
|
||||
* reported, and retried by a later rollback, rather than claimed.
|
||||
*/
|
||||
private void restoreDeletedPrior(StackResource r) {
|
||||
SubscriberV2 snapshot = readSnapshot(r, r.getAttributes().get(DELETED_PRIOR_ATTR), SubscriberV2.class);
|
||||
SubscriberV2 restored = service.restoreSubscriber(snapshot,
|
||||
AwsArnUtils.parse(snapshot.getArn()).region());
|
||||
publishSubscriberAttributes(r, restored);
|
||||
r.getAttributes().remove(DELETED_PRIOR_ATTR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts back the settings an in-place update changed, from the snapshot taken before it. The snapshot is spent only
|
||||
* once the restore succeeded, so a restore that throws leaves it for the next attempt.
|
||||
*/
|
||||
private void restoreUpdatedPrior(StackResource r) {
|
||||
String raw = r.getAttributes().get(UPDATED_PRIOR_ATTR);
|
||||
if (EVENT_BUS.equals(r.getResourceType())) {
|
||||
EventBusV2 snapshot = readSnapshot(r, raw, EventBusV2.class);
|
||||
publishBusAttributes(r, service.restoreEventBus(snapshot, AwsArnUtils.parse(snapshot.getArn()).region()));
|
||||
} else {
|
||||
SubscriberV2 snapshot = readSnapshot(r, raw, SubscriberV2.class);
|
||||
publishSubscriberAttributes(r, service.restoreSubscriber(snapshot, AwsArnUtils.parse(snapshot.getArn()).region()));
|
||||
}
|
||||
r.getAttributes().remove(UPDATED_PRIOR_ATTR);
|
||||
}
|
||||
|
||||
private static String writeSnapshot(Object resource) {
|
||||
try {
|
||||
return SNAPSHOT_MAPPER.writeValueAsString(resource);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Cannot snapshot EventBridge V2 resource " + resource, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> T readSnapshot(StackResource r, String snapshot, Class<T> type) {
|
||||
try {
|
||||
return SNAPSHOT_MAPPER.readValue(snapshot, type);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Unreadable EventBridge V2 snapshot on " + r.getLogicalId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the template keeps every property whose change replaces the subscriber. */
|
||||
private static boolean sameIdentity(SubscriberV2 prior, JsonNode request) {
|
||||
return prior.getName().equals(request.path("Name").asText())
|
||||
&& prior.getEventBusArn().equals(request.path("EventBusArn").asText())
|
||||
&& Objects.equals(prior.getInvokeConfiguration().path("TargetArn"),
|
||||
request.path("InvokeConfiguration").path("TargetArn"))
|
||||
&& prior.getType().equals(request.path("Type").asText("UNORDERED"))
|
||||
&& prior.getStartingPosition().equals(request.path("StartingPosition").asText("LATEST"))
|
||||
&& Objects.equals(EventBridgeV2Service.normalizedPointInTime(prior.getPointInTimeConfiguration()),
|
||||
EventBridgeV2Service.normalizedPointInTime(request.get("PointInTimeConfiguration")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resolved properties as a request: tags as the map the API takes, and integers given as strings as
|
||||
* integers.
|
||||
*/
|
||||
private static ObjectNode request(JsonNode props, ProvisionContext ctx) {
|
||||
JsonNode resolved = props == null ? null : ctx.engine().resolveNodeOmittingNoValue(props);
|
||||
ObjectNode request = resolved != null && resolved.isObject()
|
||||
? ((ObjectNode) resolved).deepCopy() : MAPPER.createObjectNode();
|
||||
request.remove("Tags");
|
||||
if (props != null && props.has("Tags")) {
|
||||
ObjectNode tags = request.putObject("Tags");
|
||||
ctx.resolveTags(props, "Tags").forEach(tags::put);
|
||||
}
|
||||
INTEGER_MEMBERS.forEach((structure, members) -> {
|
||||
if (request.get(structure) instanceof ObjectNode node) {
|
||||
for (String member : members) {
|
||||
JsonNode value = node.get(member);
|
||||
if (value != null && value.isTextual() && WHOLE_NUMBER.matcher(value.textValue()).matches()) {
|
||||
node.set(member, BigIntegerNode.valueOf(new BigInteger(value.textValue())));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return request;
|
||||
}
|
||||
|
||||
private static String requireName(JsonNode request, String resourceType) {
|
||||
String name = request.path("Name").asText("");
|
||||
if (name.isBlank()) {
|
||||
throw new AwsException("ValidationError", resourceType + " requires Name", 400);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (physicalId == null || physicalId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
if (EVENT_BUS.equals(resourceType)) {
|
||||
CfnDeletes.safeDelete("EventBridge V2 event bus", physicalId,
|
||||
() -> service.deleteEventBus(physicalId, region), "ResourceNotFoundException");
|
||||
} else if (SUBSCRIBER.equals(resourceType)) {
|
||||
CfnDeletes.safeDelete("EventBridge V2 subscriber", physicalId,
|
||||
() -> service.deleteSubscriber(physicalId, region), "ResourceNotFoundException");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed update that still owes the subscriber it deleted keeps its own state, snapshot included, rather than
|
||||
* being swapped for the pre-update copy and marked restored: the rollback walker then calls
|
||||
* {@link #rollbackUpdate}, which recreates the subscriber or reports that it could not.
|
||||
*/
|
||||
@Override
|
||||
public boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return resource.getAttributes().containsKey(DELETED_PRIOR_ATTR);
|
||||
}
|
||||
|
||||
/** A rollback that could not recreate the deleted subscriber is retried before the next update goes ahead. */
|
||||
@Override
|
||||
public boolean requiresUpdateRecovery(StackResource resource) {
|
||||
return "UPDATE_FAILED".equals(resource.getStatus())
|
||||
&& resource.getAttributes().containsKey(DELETED_PRIOR_ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(DELETED_PRIOR_ATTR);
|
||||
resource.getAttributes().remove(UPDATED_PRIOR_ATTR);
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(DELETED_PRIOR_ATTR);
|
||||
resource.getAttributes().remove(UPDATED_PRIOR_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls back a replacement through its cleanup record and an in-place update from the snapshot taken before it.
|
||||
* A same-name replacement deleted the prior subscriber before creating its own, so once the cleanup record has
|
||||
* deleted the replacement, the prior one is recreated from its snapshot. A restore that fails throws rather than
|
||||
* reporting a rollback that never happened. With none of these on the resource, the provision failed before it
|
||||
* changed anything, so there is nothing to undo.
|
||||
*/
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
ReplacementCleanup.rollback(resource, this::delete);
|
||||
if (resource.getAttributes().containsKey(DELETED_PRIOR_ATTR)) {
|
||||
restoreDeletedPrior(resource);
|
||||
} else if (resource.getAttributes().containsKey(UPDATED_PRIOR_ATTR)) {
|
||||
restoreUpdatedPrior(resource);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+45
-4
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsJsonTimestamp;
|
||||
@@ -82,27 +83,34 @@ public class EventBridgeV2Service implements Resettable {
|
||||
private final RegionResolver regionResolver;
|
||||
private final EventBridgeV2Delivery delivery;
|
||||
private final Clock clock;
|
||||
private final boolean enabled;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final ConcurrentMap<String, OrderedDeliveries> deliveriesByBus = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
EventBridgeV2Delivery delivery) {
|
||||
EventBridgeV2Delivery delivery, EmulatorConfig config) {
|
||||
this(storageFactory.create("eventbridgev2", "eventbridgev2-buses.json",
|
||||
new TypeReference<Map<String, EventBusV2>>() {}),
|
||||
storageFactory.create("eventbridgev2", "eventbridgev2-subscribers.json",
|
||||
new TypeReference<Map<String, SubscriberV2>>() {}),
|
||||
regionResolver, delivery, Clock.systemUTC());
|
||||
regionResolver, delivery, Clock.systemUTC(), config.services().eventbridgev2().enabled());
|
||||
}
|
||||
|
||||
EventBridgeV2Service(AccountAwareStorageBackend<EventBusV2> buses,
|
||||
AccountAwareStorageBackend<SubscriberV2> subscribers, RegionResolver regionResolver,
|
||||
EventBridgeV2Delivery delivery, Clock clock) {
|
||||
EventBridgeV2Delivery delivery, Clock clock, boolean enabled) {
|
||||
this.buses = buses;
|
||||
this.subscribers = subscribers;
|
||||
this.regionResolver = regionResolver;
|
||||
this.delivery = delivery;
|
||||
this.clock = clock;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
/** Whether {@code floci.services.eventbridgev2.enabled} turns the service off. */
|
||||
public boolean isDisabled() {
|
||||
return !enabled;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Event buses ────────────────────────────
|
||||
@@ -172,6 +180,22 @@ public class EventBridgeV2Service implements Resettable {
|
||||
return bus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts back the settings {@code snapshot} records for a bus, as a CloudFormation rollback does for an update that
|
||||
* changed them in place. The bus keeps its sequence number, so events published since the snapshot keep theirs
|
||||
* and later ones never repeat them. The restore fails when the bus is no longer the one {@code snapshot} records.
|
||||
*/
|
||||
public synchronized EventBusV2 restoreEventBus(EventBusV2 snapshot, String region) {
|
||||
EventBusV2 bus = requireEventBus(snapshot.getArn(), region);
|
||||
bus.setDescription(snapshot.getDescription());
|
||||
bus.setKmsKeyIdentifier(snapshot.getKmsKeyIdentifier());
|
||||
bus.setRetentionPeriodInDays(snapshot.getRetentionPeriodInDays());
|
||||
bus.setTags(snapshot.getTags());
|
||||
bus.setLastModifiedTime(snapshot.getLastModifiedTime());
|
||||
buses.put(storageKey(region, bus.getName()), bus);
|
||||
return bus;
|
||||
}
|
||||
|
||||
/** The bus {@code EventBusArn} names. */
|
||||
public EventBusV2 describeEventBus(JsonNode request, String region) {
|
||||
return requireEventBus(requireText(request, "EventBusArn"), region);
|
||||
@@ -347,6 +371,23 @@ public class EventBridgeV2Service implements Resettable {
|
||||
request, "subscriber");
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a subscriber back exactly as {@code snapshot} records it, under its own ARN, as a CloudFormation rollback
|
||||
* does for one its update deleted or changed in place. A subscriber under that ARN is overwritten; the restore
|
||||
* fails when its bus is gone or another subscriber holds its name on the bus.
|
||||
*/
|
||||
public synchronized SubscriberV2 restoreSubscriber(SubscriberV2 snapshot, String region) {
|
||||
EventBusV2 bus = requireEventBus(snapshot.getEventBusArn(), region);
|
||||
String key = subscriberKey(region, bus.getName(), snapshot.getName());
|
||||
Optional<SubscriberV2> existing = subscribers.get(key);
|
||||
if (existing.isPresent() && !existing.get().getArn().equals(snapshot.getArn())) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"Subscriber " + snapshot.getName() + " already exists on event bus " + bus.getName() + ".", 409);
|
||||
}
|
||||
subscribers.put(key, snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Deletes the subscriber {@code SubscriberArn} names. */
|
||||
public void deleteSubscriber(JsonNode request, String region) {
|
||||
deleteSubscriber(requireText(request, "SubscriberArn"), region);
|
||||
@@ -651,7 +692,7 @@ public class EventBridgeV2Service implements Resettable {
|
||||
* A copy of the point-in-time configuration with its {@code StartingPoint} and {@code EndPoint} as epoch
|
||||
* seconds at millisecond precision, the form a response encodes as timestamps; null when there is none.
|
||||
*/
|
||||
private static JsonNode normalizedPointInTime(JsonNode configuration) {
|
||||
public static JsonNode normalizedPointInTime(JsonNode configuration) {
|
||||
if (configuration == null || configuration.isNull()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -483,6 +483,17 @@
|
||||
"AWS::Events::Rule": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::EventsV2::EventBus": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::EventsV2::Subscriber": [
|
||||
"Name",
|
||||
"EventBusArn",
|
||||
"InvokeConfiguration/TargetArn",
|
||||
"Type",
|
||||
"StartingPosition",
|
||||
"PointInTimeConfiguration"
|
||||
],
|
||||
"AWS::GuardDuty::MalwareProtectionPlan": [],
|
||||
"AWS::IAM::AccessKey": [
|
||||
"UserName",
|
||||
|
||||
+15
@@ -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"));
|
||||
|
||||
+11
@@ -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;
|
||||
|
||||
+4
-2
@@ -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}. */
|
||||
|
||||
+297
@@ -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);
|
||||
}
|
||||
}
|
||||
+420
@@ -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);
|
||||
}
|
||||
}
|
||||
+85
-1
@@ -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();
|
||||
}
|
||||
|
||||
@@ -116,6 +116,8 @@ AWS::Events::Archive Arn ArchiveName,Description,EventPattern,KmsKeyIdentifier,R
|
||||
AWS::Events::EventBus Arn DeadLetterConfig,Description,EventSourceName,KmsKeyIdentifier,LogConfig,Name,Policy,Tags
|
||||
AWS::Events::EventBusPolicy EventBusName,Statement,StatementId
|
||||
AWS::Events::Rule Arn,RuleName Description,EventBusName,EventPattern,Name,RoleArn,ScheduleExpression,State,Tags,Targets
|
||||
AWS::EventsV2::EventBus CreationTime,EventBusArn,LastModifiedTime,State Description,EncryptionConfiguration,Name,StorageConfiguration,Tags
|
||||
AWS::EventsV2::Subscriber BusName,CreationTime,LastModifiedTime,SubscriberArn BatchConfiguration,Description,EventBusArn,FilterConfiguration,InvokeConfiguration,LogConfiguration,Name,OnFailureConfiguration,PointInTimeConfiguration,ResumePosition,RetryPolicy,StartingPosition,State,Tags,Transformer,Type
|
||||
AWS::GuardDuty::MalwareProtectionPlan Arn,CreatedAt,MalwareProtectionPlanId,Status,StatusReasons Actions,ProtectedResource,Role,Tags
|
||||
AWS::IAM::AccessKey Id,SecretAccessKey Serial,Status,UserName
|
||||
AWS::IAM::InstanceProfile Arn InstanceProfileName,Path,Roles
|
||||
|
||||
|
@@ -117,6 +117,8 @@ AWS::Events::Archive EventsArchiveCfnProvisioner
|
||||
AWS::Events::EventBus EventsCfnProvisioner
|
||||
AWS::Events::EventBusPolicy EventsCfnProvisioner
|
||||
AWS::Events::Rule EventsCfnProvisioner
|
||||
AWS::EventsV2::EventBus EventsV2CfnProvisioner
|
||||
AWS::EventsV2::Subscriber EventsV2CfnProvisioner
|
||||
AWS::GuardDuty::MalwareProtectionPlan GuardDutyMalwareProtectionPlanCfnProvisioner
|
||||
AWS::IAM::AccessKey IamAccessKeyCfnProvisioner
|
||||
AWS::IAM::InstanceProfile IamInstanceProfileCfnProvisioner
|
||||
|
||||
|
@@ -47,6 +47,7 @@ order:
|
||||
- AWS::Cognito
|
||||
- AWS::CertificateManager
|
||||
- AWS::Events
|
||||
- AWS::EventsV2
|
||||
- AWS::Scheduler
|
||||
- AWS::Transfer
|
||||
- AWS::Backup
|
||||
@@ -116,6 +117,7 @@ type_order:
|
||||
AWS::Batch: [ComputeEnvironment, JobQueue, JobDefinition]
|
||||
AWS::Cognito: [UserPool, UserPoolClient]
|
||||
AWS::Events: [Rule, EventBus, EventBusPolicy]
|
||||
AWS::EventsV2: [EventBus, Subscriber]
|
||||
AWS::CloudFormation: [CustomResource]
|
||||
AWS::BedrockAgentCore: [Runtime, RuntimeEndpoint, Memory]
|
||||
|
||||
@@ -148,6 +150,7 @@ service_labels:
|
||||
AWS::EKS: EKS
|
||||
AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2
|
||||
AWS::Events: EventBridge
|
||||
AWS::EventsV2: EventBridge V2
|
||||
AWS::GuardDuty: GuardDuty
|
||||
AWS::IAM: IAM
|
||||
AWS::IoT: IoT Core
|
||||
@@ -217,6 +220,7 @@ notes:
|
||||
AWS::SES::EmailIdentity: 'BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS''s region- and identity-specific zone assignment'
|
||||
AWS::SES::ReceiptRule: 'stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery'
|
||||
AWS::Events::Archive: '`KmsKeyIdentifier` is ignored'
|
||||
AWS::EventsV2::Subscriber: 'delivers only to Amazon SQS queues; `Transformer` RAW or WITH_METADATA; a target parameter takes a literal or a `$events` path'
|
||||
AWS::AppConfig::Environment: '`Tags` and `DeletionProtectionCheck` are accepted and not stored'
|
||||
AWS::AppConfig::ConfigurationProfile: '`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored'
|
||||
AWS::AppConfig::DeploymentStrategy: '`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document'
|
||||
|
||||
Reference in new issue
Block a user