feat(redshift): add event subscriptions with SNS delivery (#6705)

* feat(redshift): add event subscriptions with SNS delivery

Add Create, Modify, Delete and DescribeEventSubscriptions, subscription tagging, and publication of matching events to the subscription's SNS topic, honouring the topic policy.

* fix(redshift): deliver events from a consistent subscription snapshot and reject nameless subscription ARNs

Delivery copied no state under the lock modifySubscription holds, so a concurrent
update could change the topic between matching and publishing. Match and publish
from a snapshot taken under that lock.

A tag ARN ending in eventsubscription: passed an empty name to
describeSubscriptions, which lists all subscriptions. Reject it up front.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-27 11:34:38 -04:00
1 parent c538fb5520
commit 3d30bbcf7a
15 files changed
+1744 -105

No files matched your search

@@ -1,14 +1,22 @@
package io.github.hectorvent.floci.services.redshift;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo;
import io.github.hectorvent.floci.services.redshift.model.EventSubscription;
import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent;
import io.github.hectorvent.floci.services.sns.SnsService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -16,18 +24,26 @@ import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiPredicate;
import java.util.regex.Pattern;
/**
* Records the events Floci raises for Redshift resources and serves DescribeEvents and
* DescribeEventCategories from that history.
* Records the events Floci raises for Redshift resources, serves DescribeEvents and the event
* subscription operations, and publishes matching events to the subscription's SNS topic.
*/
@ApplicationScoped
public class RedshiftEventService {
@@ -37,28 +53,47 @@ public class RedshiftEventService {
/** DescribeEvents reports the past 14 days at most. */
static final Duration RETENTION = Duration.ofDays(14);
private static final long DEFAULT_WINDOW_MINUTES = 60;
private static final int MAX_SUBSCRIPTIONS = 20;
private static final int MAX_TAGS = 50;
private static final int PAGE_MIN = 20;
private static final int PAGE_MAX = 100;
private static final int PRUNE_EVERY = 200;
private static final String SNS_SUBJECT = "Amazon Redshift Notification";
private static final Pattern SUBSCRIPTION_NAME = Pattern.compile("[A-Za-z](?:-?[A-Za-z0-9])*");
private static final DateTimeFormatter EVENT_TIME = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT).withZone(ZoneOffset.UTC);
private final AccountAwareStorageBackend<RedshiftEvent> events;
private final AccountAwareStorageBackend<EventSubscription> subscriptions;
private final SnsService snsService;
private final ServiceCallAuthorizer serviceCallAuthorizer;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final Clock clock;
private final AtomicLong sequence = new AtomicLong();
@Inject
public RedshiftEventService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory, regionResolver, Clock.systemUTC());
public RedshiftEventService(StorageFactory storageFactory, SnsService snsService,
ServiceCallAuthorizer serviceCallAuthorizer, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this(storageFactory, snsService, serviceCallAuthorizer, regionResolver, objectMapper, Clock.systemUTC());
}
RedshiftEventService(StorageFactory storageFactory, RegionResolver regionResolver, Clock clock) {
RedshiftEventService(StorageFactory storageFactory, SnsService snsService,
ServiceCallAuthorizer serviceCallAuthorizer, RegionResolver regionResolver,
ObjectMapper objectMapper, Clock clock) {
this.events = storageFactory.create("redshift", "redshift-events.json",
new TypeReference<Map<String, RedshiftEvent>>() { });
this.subscriptions = storageFactory.create("redshift", "redshift-event-subscriptions.json",
new TypeReference<Map<String, EventSubscription>>() { });
this.snsService = snsService;
this.serviceCallAuthorizer = serviceCallAuthorizer;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.clock = clock;
}
// ── Recording ──────────────────────────────────────────────────────────────────────────────────────────────────────────
// ── Recording and delivery ───────────────────────────────────────────────
/** Never fails the operation that raised the event: a lost event is logged, not surfaced. */
public void record(EventInfo info, String sourceIdentifier, String message) {
@@ -83,6 +118,7 @@ public class RedshiftEventService {
if (eventSequence % PRUNE_EVERY == 0) {
prune(now);
}
deliver(event, accountId, region);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not record Redshift event {0} for {1}", info.id(), sourceIdentifier);
}
@@ -97,6 +133,127 @@ public class RedshiftEventService {
}
}
private void deliver(RedshiftEvent event, String accountId, String region) {
for (Delivery delivery : matchingDeliveries(event, accountId, region)) {
publish(delivery, event, accountId, region);
}
}
/**
* Filters and topic are read under the lock {@link #modifySubscription} holds, so an event is never matched
* against one version of a subscription and published to the topic of another.
*/
private synchronized List<Delivery> matchingDeliveries(RedshiftEvent event, String accountId, String region) {
List<Delivery> matching = new ArrayList<>();
for (EventSubscription subscription : subscriptions.scanForAccount(accountId, key -> key.startsWith(region + "/"))) {
EventSubscription snapshot = snapshot(subscription);
if (matches(snapshot, event)) {
matching.add(new Delivery(subscription, snapshot));
}
}
return matching;
}
/** {@code stored} identifies the subscription a failure is recorded against; {@code snapshot} is what matched. */
private record Delivery(EventSubscription stored, EventSubscription snapshot) { }
private static EventSubscription snapshot(EventSubscription subscription) {
EventSubscription copy = new EventSubscription();
copy.setCustomerAwsId(subscription.getCustomerAwsId());
copy.setCustSubscriptionId(subscription.getCustSubscriptionId());
copy.setSnsTopicArn(subscription.getSnsTopicArn());
copy.setStatus(subscription.getStatus());
copy.setSubscriptionCreationTime(subscription.getSubscriptionCreationTime());
copy.setSourceType(subscription.getSourceType());
copy.setSourceIdsList(new ArrayList<>(subscription.getSourceIdsList()));
copy.setEventCategoriesList(new ArrayList<>(subscription.getEventCategoriesList()));
copy.setSeverity(subscription.getSeverity());
copy.setEnabled(subscription.isEnabled());
return copy;
}
private static boolean matches(EventSubscription subscription, RedshiftEvent event) {
if (!subscription.isEnabled() || !"active".equals(subscription.getStatus())) {
return false;
}
if (subscription.getSourceType() != null && !subscription.getSourceType().equals(event.getSourceType())) {
return false;
}
List<String> sourceIds = subscription.getSourceIdsList();
if (!sourceIds.isEmpty() && !sourceIds.contains(event.getSourceIdentifier())) {
return false;
}
List<String> categories = subscription.getEventCategoriesList();
if (!categories.isEmpty() && categories.stream().noneMatch(category ->
event.getEventCategories().stream().anyMatch(category::equalsIgnoreCase))) {
return false;
}
return subscription.getSeverity() == null || subscription.getSeverity().equals(event.getSeverity());
}
private void publish(Delivery delivery, RedshiftEvent event, String accountId, String region) {
EventSubscription subscription = delivery.snapshot();
String topicArn = subscription.getSnsTopicArn();
// A missing topic has no policy to consult, so it would read as a denial; name it for what it is.
if (!snsService.topicExists(topicArn, AwsArnUtils.parse(topicArn).region())) {
updateFailureStatus(delivery.stored(), topicArn, "topic-not-exist", accountId, region);
LOG.warnv("The topic {0} of the subscription does not exist; event {1} was not published",
topicArn, event.getEventId());
return;
}
String subscriptionArn = regionResolver.buildArn("redshift", region, accountId,
"eventsubscription:" + subscription.getCustSubscriptionId());
// The topic's policy decides alone, as for any service publishing on its own behalf.
if (serviceCallAuthorizer.authorize("redshift", "sns:Publish", topicArn, subscriptionArn, accountId)
!= Decision.ALLOW) {
updateFailureStatus(delivery.stored(), topicArn, "no-permission", accountId, region);
LOG.warnv("The policy of {0} does not let Redshift publish event {1}", topicArn, event.getEventId());
return;
}
try {
String topicRegion = AwsArnUtils.parse(topicArn).region();
RequestScopes.runAs(accountId, topicRegion,
() -> snsService.publish(topicArn, null, notification(event), SNS_SUBJECT, topicRegion));
} catch (AwsException e) {
if ("NotFound".equals(e.getErrorCode())) {
updateFailureStatus(delivery.stored(), topicArn, "topic-not-exist", accountId, region);
} else if (isAuthorizationFailure(e)) {
updateFailureStatus(delivery.stored(), topicArn, "no-permission", accountId, region);
}
LOG.warnv(e, "Could not publish Redshift event {0} to {1}", event.getEventId(), topicArn);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not publish Redshift event {0} to {1}", event.getEventId(), topicArn);
}
}
private synchronized void updateFailureStatus(EventSubscription attempted, String topicArn, String status,
String accountId, String region) {
String storageKey = key(region, attempted.getCustSubscriptionId());
subscriptions.getForAccount(accountId, storageKey)
.filter(current -> current == attempted && topicArn.equals(current.getSnsTopicArn()))
.ifPresent(current -> {
current.setStatus(status);
subscriptions.putForAccount(accountId, storageKey, current);
});
}
/** AWS does not document the notification body, so this carries the same facts DescribeEvents reports. */
private String notification(RedshiftEvent event) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("Event Source", event.getSourceType());
body.put("Event Time", EVENT_TIME.format(event.getDate()));
body.put("Source ID", event.getSourceIdentifier());
body.put("Event ID", event.getEventId());
body.put("Event Categories", event.getEventCategories());
body.put("Severity", event.getSeverity());
body.put("Event Message", event.getMessage());
try {
return objectMapper.writeValueAsString(body);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not serialize the Redshift event notification", e);
}
}
// ── DescribeEvents / DescribeEventCategories ─────────────────────────────
public PaginatedResult<RedshiftEvent> describeEvents(String sourceIdentifier, String sourceType, Instant startTime,
@@ -171,6 +328,192 @@ public class RedshiftEventService {
}
}
// ── Event subscriptions ──────────────────────────────────────────────────
/** {@code sourceExists} answers whether a source of the given type and identifier exists. */
public synchronized EventSubscription createSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled,
Map<String, String> tags,
BiPredicate<String, String> sourceExists) {
validateSubscriptionName(name);
if (subscriptions.get(key(name)).isPresent()) {
throw new AwsException("SubscriptionAlreadyExist", "Subscription " + name + " already exists.", 400);
}
if (subscriptions.scan(this::inRegion).size() >= MAX_SUBSCRIPTIONS) {
throw new AwsException("EventSubscriptionQuotaExceeded",
"The request would exceed the allowed number of event subscriptions for this account.", 400);
}
validateTags(tags);
validateFilters(sourceType, sourceIds, categories, severity, sourceExists);
requireTopic(snsTopicArn);
EventSubscription subscription = new EventSubscription();
subscription.setCustomerAwsId(regionResolver.getAccountId());
subscription.setCustSubscriptionId(name);
subscription.setSnsTopicArn(snsTopicArn);
subscription.setStatus("active");
subscription.setSubscriptionCreationTime(clock.instant().truncatedTo(ChronoUnit.MILLIS));
subscription.setSourceType(blankToNull(sourceType));
subscription.setSourceIdsList(sourceIds == null ? new ArrayList<>() : new ArrayList<>(sourceIds));
subscription.setEventCategoriesList(categories == null ? new ArrayList<>() : new ArrayList<>(categories));
subscription.setSeverity(blankToNull(severity) == null ? null : severity.toUpperCase(Locale.ROOT));
subscription.setEnabled(enabled == null || enabled);
subscription.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags));
subscriptions.put(key(name), subscription);
subscriptions.flush();
return subscription;
}
/** Applies only the members the request names. */
public synchronized EventSubscription modifySubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled,
BiPredicate<String, String> sourceExists) {
EventSubscription subscription = requireSubscription(name);
if (blankToNull(snsTopicArn) != null) {
requireTopic(snsTopicArn);
}
String effectiveType = blankToNull(sourceType) != null ? sourceType : subscription.getSourceType();
boolean changedType = !Objects.equals(effectiveType, subscription.getSourceType());
List<String> effectiveIds = sourceIds != null ? sourceIds
: changedType ? List.of() : subscription.getSourceIdsList();
validateFilters(effectiveType, effectiveIds, categories, severity,
sourceIds != null || changedType ? sourceExists : (type, id) -> true);
if (blankToNull(snsTopicArn) != null) {
subscription.setSnsTopicArn(snsTopicArn);
subscription.setStatus("active");
}
subscription.setSourceType(effectiveType);
subscription.setSourceIdsList(new ArrayList<>(effectiveIds));
if (categories != null) {
subscription.setEventCategoriesList(new ArrayList<>(categories));
}
if (blankToNull(severity) != null) {
subscription.setSeverity(severity.toUpperCase(Locale.ROOT));
}
if (enabled != null) {
subscription.setEnabled(enabled);
}
subscriptions.put(key(name), subscription);
subscriptions.flush();
return subscription;
}
public synchronized void deleteSubscription(String name) {
requireSubscription(name);
subscriptions.delete(key(name));
subscriptions.flush();
}
public PaginatedResult<EventSubscription> describeSubscriptions(String name, List<String> tagKeys,
List<String> tagValues, Integer maxRecords,
String marker) {
validatePageSize(maxRecords);
List<EventSubscription> matching;
if (blankToNull(name) != null) {
matching = List.of(requireSubscription(name));
} else {
boolean filterByTag = tagKeys != null && !tagKeys.isEmpty() || tagValues != null && !tagValues.isEmpty();
matching = subscriptions.scan(this::inRegion).stream()
.filter(subscription -> !filterByTag || hasAnyTag(subscription, tagKeys, tagValues))
.sorted(Comparator.comparing(EventSubscription::getCustSubscriptionId))
.toList();
}
return Pagination.paginate(matching, EventSubscription::getCustSubscriptionId, maxRecords, marker,
PAGE_MAX, PAGE_MAX, "InvalidParameterValue", "Marker");
}
private static boolean hasAnyTag(EventSubscription subscription, List<String> keys, List<String> values) {
return subscription.getTags().entrySet().stream().anyMatch(tag ->
(keys == null || keys.isEmpty() || keys.contains(tag.getKey()))
&& (values == null || values.isEmpty() || values.contains(tag.getValue())));
}
private EventSubscription requireSubscription(String name) {
if (blankToNull(name) == null) {
throw new AwsException("InvalidParameterValue", "SubscriptionName is required", 400);
}
return subscriptions.get(key(name)).orElseThrow(() -> new AwsException("SubscriptionNotFound",
"Event subscription " + name + " not found.", 404));
}
private static void validateSubscriptionName(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterValue", "SubscriptionName is required", 400);
}
if (name.length() > 255 || !SUBSCRIPTION_NAME.matcher(name).matches()) {
throw new AwsException("InvalidParameterValue", "SubscriptionName must contain from 1 to 255 "
+ "alphanumeric characters or hyphens, start with a letter, and neither end with a hyphen "
+ "nor contain two consecutive hyphens.", 400);
}
}
private void requireTopic(String snsTopicArn) {
if (blankToNull(snsTopicArn) == null) {
throw new AwsException("InvalidParameterValue", "SnsTopicArn is required", 400);
}
if (!AwsArnUtils.isArnFor(snsTopicArn, "sns")) {
throw new AwsException("SNSInvalidTopic", "SnsTopicArn is not a valid Amazon SNS topic ARN.", 400);
}
try {
Map<String, String> attributes = snsService.getTopicAttributes(snsTopicArn,
AwsArnUtils.parse(snsTopicArn).region());
if ("true".equals(attributes.get("FifoTopic"))) {
throw new AwsException("SNSInvalidTopic", "Redshift event subscriptions require a standard SNS topic.", 400);
}
} catch (AwsException e) {
if ("NotFound".equals(e.getErrorCode())) {
throw new AwsException("SNSTopicArnNotFound",
"An Amazon SNS topic with the ARN " + snsTopicArn + " does not exist.", 404);
}
if (isAuthorizationFailure(e)) {
throw new AwsException("SNSNoAuthorization", "Not authorized to access the SNS topic.", 400);
}
throw e;
}
}
private static void validateFilters(String sourceType, List<String> sourceIds, List<String> categories,
String severity, BiPredicate<String, String> sourceExists) {
boolean hasType = blankToNull(sourceType) != null;
if (hasType) {
requireSourceType(sourceType);
}
if (sourceIds != null && !sourceIds.isEmpty()) {
if (!hasType) {
throw new AwsException("InvalidParameterCombination",
"SourceType must be provided when SourceIds are supplied.", 400);
}
for (String sourceId : sourceIds) {
if (!sourceExists.test(sourceType, sourceId)) {
throw new AwsException("SourceNotFound", "Source " + sourceId + " of type " + sourceType
+ " could not be found.", 404);
}
}
}
if (categories != null) {
for (String category : categories) {
if (!RedshiftEventCatalog.CATEGORIES.contains(category.toLowerCase(Locale.ROOT))) {
throw new AwsException("SubscriptionCategoryNotFound",
"Event category " + category + " is not valid.", 404);
}
}
}
if (blankToNull(severity) != null
&& !RedshiftEventCatalog.SEVERITIES.contains(severity.toUpperCase(Locale.ROOT))) {
throw new AwsException("SubscriptionSeverityNotFound",
"Severity " + severity + " must be ERROR or INFO.", 404);
}
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
private String key(String name) {
return key(regionResolver.getRegion(), name);
}
private static String key(String region, String name) {
return region + "/" + name;
}
@@ -178,4 +521,47 @@ public class RedshiftEventService {
private boolean inRegion(String storedKey) {
return storedKey.startsWith(regionResolver.getRegion() + "/");
}
private static boolean isAuthorizationFailure(AwsException error) {
return Set.of("AuthorizationError", "AccessDenied", "AccessDeniedException", "Forbidden")
.contains(error.getErrorCode());
}
private static void validateTags(Map<String, String> tags) {
if (tags == null) {
return;
}
if (tags.size() > MAX_TAGS) {
throw new AwsException("TagLimitExceededFault", "You have exceeded the number of tags allowed.", 400);
}
for (Map.Entry<String, String> tag : tags.entrySet()) {
if (tag.getKey() == null || tag.getKey().isBlank() || tag.getKey().length() > 128
|| tag.getKey().toLowerCase(Locale.ROOT).startsWith("aws:")
|| tag.getValue() == null || tag.getValue().length() > 256) {
throw new AwsException("InvalidTagFault", "Invalid event subscription tag.", 400);
}
}
}
public synchronized void addSubscriptionTags(String name, Map<String, String> tags) {
Map<String, String> updated = new LinkedHashMap<>(requireSubscription(name).getTags());
updated.putAll(tags);
replaceSubscriptionTags(name, updated);
}
public synchronized void deleteSubscriptionTags(String name, Collection<String> keys) {
Map<String, String> updated = new LinkedHashMap<>(requireSubscription(name).getTags());
keys.forEach(updated::remove);
replaceSubscriptionTags(name, updated);
}
public synchronized void replaceSubscriptionTags(String name, Map<String, String> tags) {
EventSubscription subscription = requireSubscription(name);
validateTags(tags);
subscription.setTags(new LinkedHashMap<>(tags));
subscriptions.put(key(name), subscription);
subscriptions.flush();
}
}
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventIn
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
import io.github.hectorvent.floci.services.redshift.model.EventSubscription;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent;
@@ -688,6 +689,57 @@ public class RedshiftQueryHandler {
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "CreateEventSubscription" -> {
EventSubscription subscription = service.createEventSubscription(
params.getFirst("SubscriptionName"), params.getFirst("SnsTopicArn"),
params.getFirst("SourceType"), memberList(params, "SourceIds"),
memberList(params, "EventCategories"), params.getFirst("Severity"),
booleanParam(params, "Enabled"), parseTags(params));
return eventSubscriptionResponse(action, subscription);
}
case "ModifyEventSubscription" -> {
EventSubscription subscription = service.modifyEventSubscription(
params.getFirst("SubscriptionName"), params.getFirst("SnsTopicArn"),
params.getFirst("SourceType"), optionalEventList(params, "SourceIds"),
optionalEventList(params, "EventCategories"), params.getFirst("Severity"),
booleanParam(params, "Enabled"));
return eventSubscriptionResponse(action, subscription);
}
case "DeleteEventSubscription" -> {
service.deleteEventSubscription(params.getFirst("SubscriptionName"));
String xml = new XmlBuilder()
.start("DeleteEventSubscriptionResponse", AwsNamespaces.REDSHIFT)
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end("DeleteEventSubscriptionResponse")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "DescribeEventSubscriptions" -> {
PaginatedResult<EventSubscription> page = service.describeEventSubscriptions(
params.getFirst("SubscriptionName"), memberList(params, "TagKeys"),
memberList(params, "TagValues"), intParam(params, "MaxRecords"), params.getFirst("Marker"));
XmlBuilder xmlBuilder = new XmlBuilder()
.start("DescribeEventSubscriptionsResponse", AwsNamespaces.REDSHIFT)
.start("DescribeEventSubscriptionsResult");
if (page.nextToken() != null) {
xmlBuilder.elem("Marker", page.nextToken());
}
xmlBuilder.start("EventSubscriptionsList");
for (EventSubscription subscription : page.items()) {
xmlBuilder.raw(buildEventSubscriptionXml(subscription));
}
String xml = xmlBuilder
.end("EventSubscriptionsList")
.end("DescribeEventSubscriptionsResult")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end("DescribeEventSubscriptionsResponse")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "EnableSnapshotCopy" -> {
Cluster cluster = service.enableSnapshotCopy(requireParam(params, "ClusterIdentifier"),
requireParam(params, "DestinationRegion"),
@@ -1302,6 +1354,50 @@ public class RedshiftQueryHandler {
return builder.end("Subnets").end("ClusterSubnetGroup").build();
}
private Response eventSubscriptionResponse(String operation, EventSubscription subscription) {
String xml = new XmlBuilder()
.start(operation + "Response", AwsNamespaces.REDSHIFT)
.start(operation + "Result")
.raw(buildEventSubscriptionXml(subscription))
.end(operation + "Result")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end(operation + "Response")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
private String buildEventSubscriptionXml(EventSubscription subscription) {
XmlBuilder builder = new XmlBuilder()
.start("EventSubscription")
.elem("Severity", subscription.getSeverity())
.elem("CustSubscriptionId", subscription.getCustSubscriptionId());
if (subscription.getSourceType() != null) {
builder.elem("SourceType", subscription.getSourceType());
}
builder.elem("SnsTopicArn", subscription.getSnsTopicArn())
.start("SourceIdsList");
for (String sourceId : subscription.getSourceIdsList()) {
builder.elem("SourceId", sourceId);
}
builder.end("SourceIdsList").start("EventCategoriesList");
for (String category : subscription.getEventCategoriesList()) {
builder.elem("EventCategory", category);
}
builder.end("EventCategoriesList")
.elem("SubscriptionCreationTime", EVENT_TIMESTAMP.format(subscription.getSubscriptionCreationTime()))
.elem("Enabled", String.valueOf(subscription.isEnabled()))
.start("Tags");
for (Map.Entry<String, String> tag : subscription.getTags().entrySet()) {
builder.start("Tag").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("Tag");
}
return builder.end("Tags")
.elem("Status", subscription.getStatus())
.elem("CustomerAwsId", subscription.getCustomerAwsId())
.end("EventSubscription").build();
}
private String buildEventXml(RedshiftEvent event) {
XmlBuilder builder = new XmlBuilder()
.start("Event")
@@ -1319,6 +1415,22 @@ public class RedshiftQueryHandler {
.end("Event").build();
}
private static Boolean booleanParam(MultivaluedMap<String, String> params, String name) {
String raw = params.getFirst(name);
if (raw == null || raw.isBlank()) {
return null;
}
if (!"true".equalsIgnoreCase(raw) && !"false".equalsIgnoreCase(raw)) {
throw new AwsException("InvalidParameterValue", name + " must be true or false.", 400);
}
return Boolean.valueOf(raw);
}
private static List<String> optionalEventList(MultivaluedMap<String, String> params, String name) {
return params.keySet().stream().anyMatch(key -> key.equals(name) || key.startsWith(name + "."))
? memberList(params, name) : null;
}
/** ISO 8601 as the SDKs send it, with or without seconds, or epoch seconds. */
private static Instant timestampParam(MultivaluedMap<String, String> params, String name) {
String raw = params.getFirst(name);
@@ -1503,6 +1615,8 @@ public class RedshiftQueryHandler {
case "IamRoles", "AddIamRoles", "RemoveIamRoles" -> "IamRoleArn";
case "TagKeys" -> "TagKey";
case "TagValues" -> "TagValue";
case "SourceIds" -> "SourceId";
case "EventCategories" -> "EventCategory";
case "ScheduleDefinitions" -> "ScheduleDefinition";
case "DbGroups" -> "DbGroup";
default -> null;
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshift.model.EventSubscription;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent;
@@ -1895,6 +1896,17 @@ public class RedshiftService implements ManagedSecretRotator {
+ "' from snapshot '" + snapshotIdentifier + "' failed at " + eventTime() + ".");
}
/** Whether the named source exists; Floci does not model cluster security groups or scheduled actions. */
private boolean eventSourceExists(String sourceType, String sourceIdentifier) {
return switch (sourceType) {
case RedshiftEventCatalog.CLUSTER -> clusters.get(sourceIdentifier).isPresent();
case RedshiftEventCatalog.PARAMETER_GROUP -> DEFAULT_PARAMETER_GROUP_NAME.equals(sourceIdentifier)
|| parameterGroups.get(sourceIdentifier).isPresent();
case RedshiftEventCatalog.SNAPSHOT -> snapshots.get(sourceIdentifier).isPresent();
default -> false;
};
}
public PaginatedResult<RedshiftEvent> describeEvents(String sourceIdentifier, String sourceType,
Instant startTime, Instant endTime, Integer duration,
Integer maxRecords, String marker) {
@@ -1906,6 +1918,30 @@ public class RedshiftService implements ManagedSecretRotator {
return eventService().describeEventCategories(sourceType);
}
public EventSubscription createEventSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled, Map<String, String> tags) {
return eventService().createSubscription(name, snsTopicArn, sourceType, sourceIds, categories, severity,
enabled, tags, this::eventSourceExists);
}
public EventSubscription modifyEventSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled) {
return eventService().modifySubscription(name, snsTopicArn, sourceType, sourceIds, categories, severity,
enabled, this::eventSourceExists);
}
public void deleteEventSubscription(String name) {
eventService().deleteSubscription(name);
}
public PaginatedResult<EventSubscription> describeEventSubscriptions(String name, List<String> tagKeys,
List<String> tagValues, Integer maxRecords,
String marker) {
return eventService().describeSubscriptions(name, tagKeys, tagValues, maxRecords, marker);
}
// ── Cluster Subnet Group Operations ──────────────────────────────────────
public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId, List<String> subnetIds) {
@@ -2461,6 +2497,11 @@ public class RedshiftService implements ManagedSecretRotator {
}
public synchronized void createTags(String resourceName, Map<String, String> tags) {
String subscriptionName = eventSubscriptionTagName(resourceName);
if (subscriptionName != null) {
eventService().addSubscriptionTags(subscriptionName, tags);
return;
}
TagHandle handle = resolveTagHandle(resourceName);
Map<String, String> updated = new LinkedHashMap<>(handle.tags());
updated.putAll(tags);
@@ -2468,6 +2509,11 @@ public class RedshiftService implements ManagedSecretRotator {
}
public synchronized void deleteTags(String resourceName, Collection<String> tagKeys) {
String subscriptionName = eventSubscriptionTagName(resourceName);
if (subscriptionName != null) {
eventService().deleteSubscriptionTags(subscriptionName, tagKeys);
return;
}
TagHandle handle = resolveTagHandle(resourceName);
Map<String, String> updated = new LinkedHashMap<>(handle.tags());
tagKeys.forEach(updated::remove);
@@ -2517,6 +2563,13 @@ public class RedshiftService implements ManagedSecretRotator {
"snapshotschedule", s.getTags(), tagKeysFilter);
}
}
if (events != null && (resourceType == null || "eventsubscription".equalsIgnoreCase(resourceType))) {
for (EventSubscription subscription : events.describeSubscriptions(null, null, null, null, null).items()) {
addTaggedResources(result, regionResolver.buildArn("redshift", regionResolver.getRegion(),
"eventsubscription:" + subscription.getCustSubscriptionId()),
"eventsubscription", subscription.getTags(), tagKeysFilter);
}
}
return result;
}
@@ -2572,7 +2625,7 @@ public class RedshiftService implements ManagedSecretRotator {
* resolution, there is no bare-name fallback: Redshift tagging is new, so there is no
* existing caller to stay backward compatible with.
*/
private TagHandle resolveTagHandle(String resourceName) {
private AwsArnUtils.Arn requireTagArn(String resourceName) {
if (resourceName == null || resourceName.isBlank()) {
throw new AwsException("InvalidParameterValue", "ResourceName is required.", 400);
}
@@ -2598,6 +2651,17 @@ public class RedshiftService implements ManagedSecretRotator {
|| !regionResolver.getRegion().equals(arn.region())) {
throw new AwsException("ResourceNotFoundFault", "Resource " + resourceName + " not found", 404);
}
return arn;
}
private String eventSubscriptionTagName(String resourceName) {
String resource = requireTagArn(resourceName).resource();
String prefix = "eventsubscription:";
return resource.startsWith(prefix) ? resource.substring(prefix.length()) : null;
}
private TagHandle resolveTagHandle(String resourceName) {
AwsArnUtils.Arn arn = requireTagArn(resourceName);
String resource = arn.resource();
int sep = resource.indexOf(':');
if (sep < 0) {
@@ -2607,6 +2671,14 @@ public class RedshiftService implements ManagedSecretRotator {
String id = resource.substring(sep + 1);
return switch (type) {
case "eventsubscription" -> {
if (id.isBlank()) {
throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400);
}
EventSubscription subscription = eventService().describeSubscriptions(id, null, null, null, null)
.items().getFirst();
yield new TagHandle(subscription.getTags(), updated -> eventService().replaceSubscriptionTags(id, updated));
}
case "cluster" -> {
Cluster cluster = clusters.get(id)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + id + " not found", 404));
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.services.redshift.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** A Redshift event notification subscription, as DescribeEventSubscriptions reports it. */
@RegisterForReflection
public class EventSubscription {
private String customerAwsId;
private String custSubscriptionId;
private String snsTopicArn;
private String status;
private Instant subscriptionCreationTime;
private String sourceType;
private List<String> sourceIdsList = new ArrayList<>();
private List<String> eventCategoriesList = new ArrayList<>();
private String severity;
private boolean enabled;
private Map<String, String> tags = new LinkedHashMap<>();
public String getCustomerAwsId() { return customerAwsId; }
public void setCustomerAwsId(String customerAwsId) { this.customerAwsId = customerAwsId; }
public String getCustSubscriptionId() { return custSubscriptionId; }
public void setCustSubscriptionId(String custSubscriptionId) { this.custSubscriptionId = custSubscriptionId; }
public String getSnsTopicArn() { return snsTopicArn; }
public void setSnsTopicArn(String snsTopicArn) { this.snsTopicArn = snsTopicArn; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getSubscriptionCreationTime() { return subscriptionCreationTime; }
public void setSubscriptionCreationTime(Instant subscriptionCreationTime) {
this.subscriptionCreationTime = subscriptionCreationTime;
}
public String getSourceType() { return sourceType; }
public void setSourceType(String sourceType) { this.sourceType = sourceType; }
public List<String> getSourceIdsList() { return sourceIdsList; }
public void setSourceIdsList(List<String> sourceIdsList) { this.sourceIdsList = sourceIdsList; }
public List<String> getEventCategoriesList() { return eventCategoriesList; }
public void setEventCategoriesList(List<String> eventCategoriesList) {
this.eventCategoriesList = eventCategoriesList;
}
public String getSeverity() { return severity; }
public void setSeverity(String severity) { this.severity = severity; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}