feat(redshift): send zero-ETL integration events to EventBridge (#6822)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-28 22:41:04 -04:00
1 parent a682400d45
commit c0d1767ec0
8 files changed
+625 -18

No files matched your search

@@ -0,0 +1,140 @@
package io.github.hectorvent.floci.services.redshift;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The {@code aws.redshift} events AWS sends to the default EventBridge bus as a zero-ETL integration
* changes state. The detail types, event IDs, severities and messages come from the Redshift
* Management Guide's "Zero-ETL integration event notifications" table; only the events Floci's
* DynamoDB integration can raise are implemented. AWS publishes no JSON example, so the field names of
* the detail are Floci's own representation of the table's columns.
* {@link RedshiftService} queues an event while it holds its monitor and publishes the queue once it
* does not, so a rule's target that calls Redshift never waits on the call that made the change, and
* events go out in the order their changes were made.
*/
@ApplicationScoped
class RedshiftIntegrationEventPublisher {
private static final Logger LOG = Logger.getLogger(RedshiftIntegrationEventPublisher.class);
static final String SOURCE = "aws.redshift";
/** The implemented rows of the AWS table: category doubles as the detail type's suffix. */
enum IntegrationEvent {
CREATED_ACTIVE("0000", "Monitoring", "INFO",
"Your zero-ETL Integration %s has been created and became ACTIVE at %s."),
DELETED("0001", "Monitoring", "INFO", "Your zero-ETL Integration %s has been deleted at %s."),
DELETION_INITIATED("0002", "Monitoring", "INFO",
"Your zero-ETL Integration %s has initiated deletion at %s."),
SYNCHRONIZING("0003", "Monitoring", "INFO",
"Your zero-ETL Integration %s is synchronizing transactional data to the Amazon Redshift data warehouse."),
FAILED("0007", "Monitoring", "ERROR",
"Unable to load data due to an internal error. Delete and recreate the integration. "
+ "If the error persists, contact AWS Support."),
ACTIVE("0013", "Monitoring", "INFO", "Your zero-ETL Integration %s is now ACTIVE.");
private final String number;
private final String category;
private final String severity;
private final String message;
IntegrationEvent(String number, String category, String severity, String message) {
this.number = number;
this.category = category;
this.severity = severity;
this.message = message;
}
String eventId() {
return "REDSHIFT-INTEGRATION-EVENT-" + number;
}
String detailType() {
return "Redshift Integration " + category;
}
String render(String integrationName, String time) {
return switch (this) {
case CREATED_ACTIVE, DELETED, DELETION_INITIATED -> message.formatted(integrationName, time);
case SYNCHRONIZING, ACTIVE -> message.formatted(integrationName);
case FAILED -> message;
};
}
}
private record Queued(String detailType, String detail, String resourceArn, String region, String accountId) { }
private final EventBridgeService eventBridgeService;
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
private final ServiceRegistry registry;
private final Queue<Queued> queued = new ConcurrentLinkedQueue<>();
private final AtomicBoolean publishing = new AtomicBoolean();
@Inject
RedshiftIntegrationEventPublisher(EventBridgeService eventBridgeService, ObjectMapper objectMapper,
RegionResolver regionResolver, ServiceRegistry registry) {
this.eventBridgeService = eventBridgeService;
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
this.registry = registry;
}
/** Queues {@code event} for {@code integration}'s Region, in the calling account. */
void queue(IntegrationEvent event, Integration integration, String region, Instant at) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("eventId", event.eventId());
detail.put("severity", event.severity);
detail.put("category", event.category);
detail.put("message", event.render(integration.getIntegrationName(), RedshiftService.eventTime(at)));
detail.put("integrationArn", integration.getIntegrationArn());
queued.add(new Queued(event.detailType(), detail.toString(), integration.getIntegrationArn(), region,
accountId(integration)));
}
// The consumer thread has no request account, so the integration's own account wins.
private String accountId(Integration integration) {
return integration.getAccountId() != null ? integration.getAccountId() : regionResolver.getAccountId();
}
/**
* Publishes the queued events in order. One call publishes at a time: a call made while an event
* is delivered leaves its events queued behind the rest and returns, and the call already
* publishing sends them after.
*/
void publishQueued() {
while (!queued.isEmpty() && publishing.compareAndSet(false, true)) {
try {
Queued next;
while ((next = queued.poll()) != null) {
publish(next);
}
} finally {
publishing.set(false);
}
}
}
private void publish(Queued event) {
if (!registry.isServiceEnabled("events")) {
LOG.debugv("EventBridge is disabled; dropping the {0} event for {1}", event.detailType(),
event.resourceArn());
return;
}
RequestScopes.runAs(event.accountId(), event.region(), () -> eventBridgeService.publishServiceEvent(
SOURCE, event.detailType(), event.detail(), event.resourceArn(), event.region()));
}
}
@@ -103,6 +103,7 @@ public class RedshiftService implements ManagedSecretRotator {
private final DynamoDbStreamReader streamReader;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final RedshiftEventService events;
private final RedshiftIntegrationEventPublisher integrationEvents;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
@@ -155,11 +156,15 @@ public class RedshiftService implements ManagedSecretRotator {
return mutation.get();
}
private static final DateTimeFormatter EVENT_MESSAGE_TIME =
static final DateTimeFormatter EVENT_MESSAGE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneOffset.UTC);
static String eventTime(Instant at) {
return EVENT_MESSAGE_TIME.format(at) + " UTC";
}
private static String eventTime() {
return EVENT_MESSAGE_TIME.format(Instant.now()) + " UTC";
return eventTime(Instant.now());
}
private void emitEvent(EventInfo info, String sourceIdentifier, String message) {
@@ -181,7 +186,7 @@ public class RedshiftService implements ManagedSecretRotator {
RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
RedshiftEventService events) {
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents) {
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
@@ -202,6 +207,18 @@ public class RedshiftService implements ManagedSecretRotator {
this.streamReader = streamReader;
this.auditLogPublisher = auditLogPublisher;
this.events = events;
this.integrationEvents = integrationEvents;
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager,
DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
RedshiftEventService events) {
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events,
null);
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
@@ -511,10 +528,20 @@ public class RedshiftService implements ManagedSecretRotator {
// Metadata only: no data is replicated from the source. The shape and the lower case status
// were captured from a live integration in us-west-2.
public synchronized Integration createIntegration(String integrationName, String sourceArn, String targetArn,
String kmsKeyId, String description,
Map<String, String> additionalEncryptionContext,
Map<String, String> tags, String region) {
public Integration createIntegration(String integrationName, String sourceArn, String targetArn,
String kmsKeyId, String description,
Map<String, String> additionalEncryptionContext,
Map<String, String> tags, String region) {
Integration integration = createIntegrationLocked(integrationName, sourceArn, targetArn, kmsKeyId,
description, additionalEncryptionContext, tags, region);
publishIntegrationEvents();
return integration;
}
private synchronized Integration createIntegrationLocked(String integrationName, String sourceArn,
String targetArn, String kmsKeyId, String description,
Map<String, String> additionalEncryptionContext,
Map<String, String> tags, String region) {
if (integrationName == null || integrationName.isBlank()) {
throw new AwsException("InvalidParameterValue", "IntegrationName is required.", 400);
}
@@ -591,6 +618,7 @@ public class RedshiftService implements ManagedSecretRotator {
integration.setTags(tags);
integrations.put(integrationId, integration);
LOG.infov("Created Redshift zero-ETL integration: {0}", integration.getIntegrationArn());
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.SYNCHRONIZING, integration);
return integration;
}
@@ -666,15 +694,23 @@ public class RedshiftService implements ManagedSecretRotator {
.toList();
}
public synchronized void updateIntegrationRuntime(String accountId, String integrationArn,
Map<String, String> shardSequenceNumbers,
boolean successful, String error) {
public void updateIntegrationRuntime(String accountId, String integrationArn,
Map<String, String> shardSequenceNumbers,
boolean successful, String error) {
updateIntegrationRuntimeLocked(accountId, integrationArn, shardSequenceNumbers, successful, error);
publishIntegrationEvents();
}
private synchronized void updateIntegrationRuntimeLocked(String accountId, String integrationArn,
Map<String, String> shardSequenceNumbers,
boolean successful, String error) {
for (String key : integrations.keysForAccount(accountId)) {
Optional<Integration> stored = integrations.getForAccount(accountId, key);
if (stored.isEmpty() || !integrationArn.equals(stored.get().getIntegrationArn())) {
continue;
}
Integration integration = stored.get();
String previousStatus = integration.getStatus();
if (successful) {
integration.setShardSequenceNumbers(shardSequenceNumbers);
integration.setRetryCount(0);
@@ -686,26 +722,41 @@ public class RedshiftService implements ManagedSecretRotator {
integration.setStatus("failed");
}
integrations.putForAccount(accountId, key, integration);
queueStatusChange(integration, previousStatus);
return;
}
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
}
public synchronized void updateIntegrationBackfillProgress(String accountId, String integrationArn,
String backfillLastEvaluatedKey,
boolean backfillCompleted) {
public void updateIntegrationBackfillProgress(String accountId, String integrationArn,
String backfillLastEvaluatedKey, boolean backfillCompleted) {
updateIntegrationBackfillProgressLocked(accountId, integrationArn, backfillLastEvaluatedKey,
backfillCompleted);
publishIntegrationEvents();
}
private synchronized void updateIntegrationBackfillProgressLocked(String accountId, String integrationArn,
String backfillLastEvaluatedKey,
boolean backfillCompleted) {
for (String key : integrations.keysForAccount(accountId)) {
Optional<Integration> stored = integrations.getForAccount(accountId, key);
if (stored.isEmpty() || !integrationArn.equals(stored.get().getIntegrationArn())) {
continue;
}
Integration integration = stored.get();
String previousStatus = integration.getStatus();
boolean backfillJustCompleted = !integration.isBackfillCompleted() && backfillCompleted;
integration.setBackfillLastEvaluatedKey(backfillLastEvaluatedKey);
integration.setBackfillCompleted(backfillCompleted);
integration.setRetryCount(0);
integration.setLastError(null);
integration.setStatus(backfillCompleted ? "active" : "syncing");
integrations.putForAccount(accountId, key, integration);
if (backfillJustCompleted) {
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.CREATED_ACTIVE, integration);
} else {
queueStatusChange(integration, previousStatus);
}
return;
}
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
@@ -752,7 +803,13 @@ public class RedshiftService implements ManagedSecretRotator {
return maxRecords;
}
public synchronized Integration deleteIntegration(String integrationArn) {
public Integration deleteIntegration(String integrationArn) {
Integration deleted = deleteIntegrationLocked(integrationArn);
publishIntegrationEvents();
return deleted;
}
private synchronized Integration deleteIntegrationLocked(String integrationArn) {
if (integrationArn == null || integrationArn.isBlank()) {
throw new AwsException("InvalidParameterValue", "IntegrationArn is required.", 400);
}
@@ -761,12 +818,47 @@ public class RedshiftService implements ManagedSecretRotator {
if (stored.isPresent() && integrationArn.equals(stored.get().getIntegrationArn())) {
integrations.delete(key);
LOG.infov("Deleted Redshift zero-ETL integration: {0}", integrationArn);
// Deletion is immediate here, so both the start and the end of it are reported.
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.DELETION_INITIATED,
stored.get());
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.DELETED, stored.get());
return stored.get();
}
}
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
}
private void queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent event,
Integration integration) {
if (integrationEvents != null) {
integrationEvents.queue(event, integration, AwsArnUtils.parse(integration.getIntegrationArn()).region(),
Instant.now());
}
}
/** Queues the event for a move into syncing, active or failed; any other change is silent. */
private void queueStatusChange(Integration integration, String previousStatus) {
String status = integration.getStatus();
if (status == null || status.equals(previousStatus)) {
return;
}
switch (status) {
case "syncing" -> queueIntegrationEvent(
RedshiftIntegrationEventPublisher.IntegrationEvent.SYNCHRONIZING, integration);
case "active" -> queueIntegrationEvent(
RedshiftIntegrationEventPublisher.IntegrationEvent.ACTIVE, integration);
case "failed" -> queueIntegrationEvent(
RedshiftIntegrationEventPublisher.IntegrationEvent.FAILED, integration);
default -> { }
}
}
private void publishIntegrationEvents() {
if (integrationEvents != null) {
integrationEvents.publishQueued();
}
}
public List<Cluster> describeClusters(String identifier) {
if (identifier != null) {
Optional<Cluster> cluster = clusters.get(identifier);
@@ -29,7 +29,7 @@ class RedshiftDataEventPublisher {
void publish(RedshiftDataStatementStore.StoredStatement statement) {
try {
if (!registry.isServiceEnabled("eventbridge")) {
if (!registry.isServiceEnabled("events")) {
LOG.warnv("EventBridge disabled for statement {0}, account {1}, region {2}",
statement.id, statement.accountId, statement.region);
return;