mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
c538fb5520
commit
3d30bbcf7a
15 files changed
+1744
-105
No files matched your search
+423
-9
@@ -1,16 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
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.model.EventSubscription;
|
||||
import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -19,26 +28,64 @@ import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.BiPredicate;
|
||||
|
||||
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.ArgumentCaptor.forClass;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftEventServiceTest {
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:redshift-events";
|
||||
private static final BiPredicate<String, String> ALL_SOURCES_EXIST = (type, id) -> true;
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private SnsService sns;
|
||||
private ServiceCallAuthorizer authorizer;
|
||||
private MutableClock clock;
|
||||
private RedshiftEventService service;
|
||||
private StorageFactory factory;
|
||||
|
||||
@Test
|
||||
void explicitRecordingUsesTheOwnersHistory() {
|
||||
@ParameterizedTest
|
||||
@CsvSource({"success,active", "NotFound,topic-not-exist", "AuthorizationError,no-permission"})
|
||||
void explicitRecordingUsesTheOwnersHistorySubscriptionsAndFailureStatus(String failure, String expectedStatus) {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
String owner = "565656565656";
|
||||
String region = "us-west-2";
|
||||
String ownerTopic = "arn:aws:sns:us-west-2:565656565656:snapshots";
|
||||
AccountAwareStorageBackend<EventSubscription> subscriptionStore = factory.create("redshift",
|
||||
"redshift-event-subscriptions.json", new TypeReference<Map<String, EventSubscription>>() { });
|
||||
EventSubscription watcher = new EventSubscription();
|
||||
watcher.setCustSubscriptionId("watcher");
|
||||
watcher.setCustomerAwsId(owner);
|
||||
watcher.setSnsTopicArn(ownerTopic);
|
||||
watcher.setStatus("active");
|
||||
watcher.setEnabled(true);
|
||||
subscriptionStore.putForAccount(owner, region + "/watcher", watcher);
|
||||
if (!"success".equals(failure)) {
|
||||
doThrow(new AwsException(failure, "delivery failed", 400)).when(sns)
|
||||
.publish(eq(ownerTopic), any(), anyString(), anyString(), eq(region));
|
||||
}
|
||||
|
||||
service.recordForAccount(owner, region, RedshiftEventCatalog.SNAPSHOT_COMPLETED, "owner-snapshot", "completed");
|
||||
|
||||
@@ -46,6 +93,55 @@ class RedshiftEventServiceTest {
|
||||
new TypeReference<Map<String, RedshiftEvent>>() { });
|
||||
assertEquals(1, history.scanForAccount(owner, key -> key.startsWith(region + "/")).size());
|
||||
assertTrue(service.describeEvents(null, null, null, null, null, null, null).items().isEmpty());
|
||||
assertEquals(expectedStatus, subscriptionStore.getForAccount(owner, region + "/watcher").orElseThrow().getStatus());
|
||||
assertEquals("active", service.describeSubscriptions("watcher", null, null, null, null).items().getFirst().getStatus());
|
||||
verify(sns).publish(eq(ownerTopic), any(), anyString(), anyString(), eq(region));
|
||||
verify(sns, never()).publish(eq(TOPIC), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"NotFound,deleted", "NotFound,recreated", "NotFound,retargeted",
|
||||
"AuthorizationError,deleted", "AuthorizationError,recreated", "AuthorizationError,retargeted"})
|
||||
void failedNotificationDoesNotOverwriteConcurrentSubscriptionChange(String errorCode, String change) throws Exception {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
String replacementTopic = "arn:aws:sns:us-east-1:000000000000:replacement";
|
||||
CountDownLatch publishing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
publishing.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS), "SNS publish was not released");
|
||||
throw new AwsException(errorCode, "Topic delivery failed", 400);
|
||||
}).when(sns).publish(eq(TOPIC), any(), anyString(), anyString(), anyString());
|
||||
|
||||
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
|
||||
Future<?> recording = executor.submit(() ->
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created"));
|
||||
try {
|
||||
assertTrue(publishing.await(5, TimeUnit.SECONDS), "SNS publish did not start");
|
||||
switch (change) {
|
||||
case "deleted" -> service.deleteSubscription("watcher");
|
||||
case "recreated" -> {
|
||||
service.deleteSubscription("watcher");
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
}
|
||||
case "retargeted" -> service.modifySubscription("watcher", replacementTopic,
|
||||
null, null, null, null, null, ALL_SOURCES_EXIST);
|
||||
default -> throw new IllegalArgumentException(change);
|
||||
}
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
recording.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
List<EventSubscription> remaining = service.describeSubscriptions(null, null, null, null, null).items();
|
||||
if ("deleted".equals(change)) {
|
||||
assertTrue(remaining.isEmpty(), "A late SNS failure must not recreate a deleted subscription");
|
||||
} else {
|
||||
assertEquals(1, remaining.size());
|
||||
assertEquals("active", remaining.getFirst().getStatus());
|
||||
assertEquals("retargeted".equals(change) ? replacementTopic : TOPIC, remaining.getFirst().getSnsTopicArn());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,7 +163,7 @@ class RedshiftEventServiceTest {
|
||||
AtomicReference<String> region = new AtomicReference<>("us-east-1");
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getRegion()).thenAnswer(invocation -> region.get());
|
||||
RedshiftEventService alternating = new RedshiftEventService(factory, resolver, clock);
|
||||
RedshiftEventService alternating = new RedshiftEventService(factory, sns, authorizer, resolver, objectMapper, clock);
|
||||
for (int index = 0; index < 200; index++) {
|
||||
region.set(index % 2 == 0 ? "us-east-1" : "us-west-2");
|
||||
alternating.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
@@ -87,8 +183,14 @@ class RedshiftEventServiceTest {
|
||||
when(config.storage().persistentPath()).thenReturn("target/test-data");
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
factory = new StorageFactory(config, access);
|
||||
sns = mock(SnsService.class);
|
||||
clock = new MutableClock(Instant.parse("2026-10-26T12:00:00Z"));
|
||||
service = new RedshiftEventService(factory, new RegionResolver("us-east-1", "000000000000"), clock);
|
||||
when(sns.topicExists(anyString(), anyString())).thenReturn(true);
|
||||
authorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
service = new RedshiftEventService(factory, sns, authorizer, new RegionResolver("us-east-1", "000000000000"),
|
||||
objectMapper, clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -175,19 +277,331 @@ class RedshiftEventServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventHistoryIsRegional() {
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
RedshiftEventService west = new RedshiftEventService(factory,
|
||||
new RegionResolver("us-west-2", "000000000000"), clock);
|
||||
void createSubscriptionDefaultsToActiveEnabledWithoutSeverityFilter() {
|
||||
EventSubscription subscription = create("all-events", null, List.of(), List.of(), null);
|
||||
|
||||
assertTrue(west.describeEvents(null, null, null, null, null, null, null).items().isEmpty());
|
||||
assertEquals("active", subscription.getStatus());
|
||||
assertTrue(subscription.isEnabled());
|
||||
assertNull(subscription.getSeverity());
|
||||
assertEquals("000000000000", subscription.getCustomerAwsId());
|
||||
assertEquals(clock.instant(), subscription.getSubscriptionCreationTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriptionValidatesItsArguments() {
|
||||
assertEquals("InvalidParameterValue", code(() -> create("1-starts-with-digit", null, List.of(), List.of(), null)));
|
||||
assertEquals("InvalidParameterValue", code(() -> create("ends-with-hyphen-", null, List.of(), List.of(), null)));
|
||||
assertEquals("InvalidParameterValue", code(() -> create("double--hyphen", null, List.of(), List.of(), null)));
|
||||
assertEquals("InvalidParameterCombination", code(() -> create("ids-only", null, List.of("warehouse"), List.of(), null)));
|
||||
assertEquals("InvalidParameterValue", code(() -> create("bad-type", "database", List.of(), List.of(), null)));
|
||||
assertEquals("SubscriptionCategoryNotFound", code(() -> create("bad-category", null, List.of(), List.of("billing"), null)));
|
||||
assertEquals("SubscriptionSeverityNotFound", code(() -> create("bad-severity", null, List.of(), List.of(), "WARN")));
|
||||
assertEquals("SNSInvalidTopic", code(() -> service.createSubscription("not-a-topic", "arn:aws:sqs:us-east-1:0:q",
|
||||
null, List.of(), List.of(), null, null, Map.of(), ALL_SOURCES_EXIST)));
|
||||
verifyNoInteractions(sns);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriptionRejectsMissingTopicsAndSources() {
|
||||
doThrow(new AwsException("NotFound", "Topic does not exist.", 404)).when(sns).getTopicAttributes(anyString(), anyString());
|
||||
assertEquals("SNSTopicArnNotFound", code(() -> create("no-topic", null, List.of(), List.of(), null)));
|
||||
|
||||
setUp();
|
||||
assertEquals("SourceNotFound", code(() -> service.createSubscription("no-source", TOPIC, "cluster",
|
||||
List.of("missing"), List.of(), null, null, Map.of(), (type, id) -> false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriptionRejectsDuplicatesAndTheTwentyFirst() {
|
||||
create("first", null, List.of(), List.of(), null);
|
||||
assertEquals("SubscriptionAlreadyExist", code(() -> create("first", null, List.of(), List.of(), null)));
|
||||
|
||||
for (int i = 2; i <= 20; i++) {
|
||||
create("subscription-" + i, null, List.of(), List.of(), null);
|
||||
}
|
||||
assertEquals("EventSubscriptionQuotaExceeded", code(() -> create("one-too-many", null, List.of(), List.of(), null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifySubscriptionChangesOnlyTheNamedMembers() {
|
||||
create("watcher", "cluster", List.of("warehouse"), List.of("management"), "ERROR");
|
||||
|
||||
EventSubscription modified = service.modifySubscription("watcher", null, null, null, null, null, false,
|
||||
ALL_SOURCES_EXIST);
|
||||
|
||||
assertFalse(modified.isEnabled());
|
||||
assertEquals("cluster", modified.getSourceType());
|
||||
assertEquals(List.of("warehouse"), modified.getSourceIdsList());
|
||||
assertEquals(List.of("management"), modified.getEventCategoriesList());
|
||||
assertEquals("ERROR", modified.getSeverity());
|
||||
assertEquals("SubscriptionNotFound", code(() -> service.modifySubscription("missing", null, null, null, null,
|
||||
null, null, ALL_SOURCES_EXIST)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubscriptionRemovesIt() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
|
||||
service.deleteSubscription("watcher");
|
||||
|
||||
assertEquals("SubscriptionNotFound", code(() -> service.deleteSubscription("watcher")));
|
||||
assertTrue(service.describeSubscriptions(null, null, null, null, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeSubscriptionsFiltersByNameAndTagsAndPages() {
|
||||
service.createSubscription("tagged", TOPIC, null, List.of(), List.of(), null, null,
|
||||
Map.of("team", "data"), ALL_SOURCES_EXIST);
|
||||
create("untagged", null, List.of(), List.of(), null);
|
||||
|
||||
assertEquals(List.of("tagged"), names(service.describeSubscriptions("tagged", null, null, null, null)));
|
||||
assertEquals(List.of("tagged"), names(service.describeSubscriptions(null, List.of("team"), null, null, null)));
|
||||
assertEquals(List.of("tagged"), names(service.describeSubscriptions(null, null, List.of("data"), null, null)));
|
||||
assertEquals(List.of("tagged", "untagged"), names(service.describeSubscriptions(null, null, null, null, null)));
|
||||
assertEquals("SubscriptionNotFound", code(() -> service.describeSubscriptions("missing", null, null, null, null)));
|
||||
|
||||
for (int i = 0; i < 18; i++) {
|
||||
create(String.format("page-%02d", i), null, List.of(), List.of(), null);
|
||||
}
|
||||
PaginatedResult<EventSubscription> first = service.describeSubscriptions(null, null, null, 20, null);
|
||||
assertEquals(20, first.items().size());
|
||||
assertNull(first.nextToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchingEventsArePublishedToTheTopicWithTheirDetails() throws Exception {
|
||||
create("everything", null, List.of(), List.of(), null);
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "Amazon Redshift cluster 'warehouse' created.");
|
||||
|
||||
ArgumentCaptor<String> message = forClass(String.class);
|
||||
verify(sns).publish(eq(TOPIC), eq(null), message.capture(), eq("Amazon Redshift Notification"), eq("us-east-1"));
|
||||
JsonNode body = objectMapper.readTree(message.getValue());
|
||||
assertEquals("cluster", body.get("Event Source").asText());
|
||||
assertEquals("warehouse", body.get("Source ID").asText());
|
||||
assertEquals("REDSHIFT-EVENT-2000", body.get("Event ID").asText());
|
||||
assertEquals("INFO", body.get("Severity").asText());
|
||||
assertEquals("management", body.get("Event Categories").get(0).asText());
|
||||
assertEquals("2026-10-26 12:00:00.000", body.get("Event Time").asText());
|
||||
assertEquals("Amazon Redshift cluster 'warehouse' created.", body.get("Event Message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionFiltersDecideWhichEventsArePublished() {
|
||||
create("clusters-only", "cluster", List.of(), List.of(), null);
|
||||
create("one-cluster", "cluster", List.of("analytics"), List.of(), null);
|
||||
create("security-only", null, List.of(), List.of("security"), null);
|
||||
create("errors-only", null, List.of(), List.of(), "ERROR");
|
||||
service.modifySubscription("security-only", null, null, null, null, null, null, ALL_SOURCES_EXIST);
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
|
||||
// clusters-only matches; one-cluster names another cluster; security-only wants another
|
||||
// category; errors-only wants another severity.
|
||||
verify(sns, times(1)).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
|
||||
service.record(RedshiftEventCatalog.SNAPSHOT_FAILED, "nightly", "failed");
|
||||
|
||||
// The ERROR snapshot event reaches errors-only and nothing else.
|
||||
verify(sns, times(2)).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventIsPublishedToTheTopicItWasMatchedAgainstWhenTheSubscriptionChangesMidDelivery() throws Exception {
|
||||
create("watcher", "cluster", List.of(), List.of(), null);
|
||||
String replacementTopic = "arn:aws:sns:us-east-1:000000000000:replacement";
|
||||
CountDownLatch delivering = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
when(sns.topicExists(anyString(), anyString())).thenAnswer(invocation -> {
|
||||
delivering.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS), "Delivery was not released");
|
||||
return true;
|
||||
});
|
||||
|
||||
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
|
||||
Future<?> recording = executor.submit(() ->
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created"));
|
||||
try {
|
||||
assertTrue(delivering.await(5, TimeUnit.SECONDS), "Delivery did not start");
|
||||
service.modifySubscription("watcher", replacementTopic, "cluster-snapshot", null, null, null, null,
|
||||
ALL_SOURCES_EXIST);
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
recording.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
verify(sns).publish(eq(TOPIC), any(), anyString(), anyString(), anyString());
|
||||
verify(sns, never()).publish(eq(replacementTopic), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTopicPolicyIsCheckedForRedshiftBeforeEachPublish() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
|
||||
verify(authorizer).authorize("redshift", "sns:Publish", TOPIC,
|
||||
"arn:aws:redshift:us-east-1:000000000000:eventsubscription:watcher", "000000000000");
|
||||
verify(sns).publish(eq(TOPIC), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingTopicIsReportedAsMissingRatherThanDenied() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
when(sns.topicExists(anyString(), anyString())).thenReturn(false);
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
|
||||
assertEquals("topic-not-exist",
|
||||
service.describeSubscriptions("watcher", null, null, null, null).items().getFirst().getStatus());
|
||||
verify(sns, never()).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
verify(authorizer, never()).authorize(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicPolicyThatDeniesRedshiftBlocksDeliveryAndMarksTheSubscription() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(Decision.DENY);
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
|
||||
verify(sns, never()).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
assertEquals("no-permission",
|
||||
service.describeSubscriptions("watcher", null, null, null, null).items().getFirst().getStatus());
|
||||
assertEquals(1, service.describeEvents(null, null, null, null, null, null, null).items().size());
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_DELETED, "warehouse", "deleted");
|
||||
|
||||
verify(authorizer, times(1)).authorize(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledSubscriptionsPublishNothing() {
|
||||
service.createSubscription("quiet", TOPIC, null, List.of(), List.of(), null, false, Map.of(), ALL_SOURCES_EXIST);
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
|
||||
verify(sns, never()).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitInfoSeverityDoesNotReceiveErrors() {
|
||||
create("info-only", null, List.of(), List.of(), "INFO");
|
||||
service.record(RedshiftEventCatalog.SNAPSHOT_FAILED, "nightly", "failed");
|
||||
verify(sns, never()).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedSeverityReceivesBothSeverities() {
|
||||
create("all-severities", null, List.of(), List.of(), null);
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
service.record(RedshiftEventCatalog.SNAPSHOT_FAILED, "nightly", "failed");
|
||||
verify(sns, times(2)).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fifoTopicsAreRejectedBeforeCreatingSubscription() {
|
||||
when(sns.getTopicAttributes(TOPIC, "us-east-1")).thenReturn(Map.of("FifoTopic", "true"));
|
||||
assertEquals("SNSInvalidTopic", code(() -> create("fifo", null, List.of(), List.of(), null)));
|
||||
assertTrue(service.describeSubscriptions(null, null, null, null, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void permissionFailuresUseRedshiftErrorsAndStatus() {
|
||||
doThrow(new AwsException("AuthorizationError", "denied", 403))
|
||||
.when(sns).getTopicAttributes(TOPIC, "us-east-1");
|
||||
assertEquals("SNSNoAuthorization", code(() -> create("denied", null, List.of(), List.of(), null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lostPublishPermissionMarksSubscriptionWithoutFailingOperation() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
doThrow(new AwsException("AuthorizationError", "denied", 403))
|
||||
.when(sns).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
assertEquals("no-permission", service.describeSubscriptions("watcher", null, null, null, null)
|
||||
.items().getFirst().getStatus());
|
||||
assertEquals(1, service.describeEvents(null, null, null, null, null, null, null).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatingSourceTypePreservesSourceIds() {
|
||||
create("watcher", "cluster", List.of("warehouse"), List.of(), null);
|
||||
EventSubscription modified = service.modifySubscription("watcher", null, "cluster", null, null, null,
|
||||
false, ALL_SOURCES_EXIST);
|
||||
assertEquals(List.of("warehouse"), modified.getSourceIdsList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disablingSubscriptionDoesNotRequireItsDeletedSource() {
|
||||
create("watcher", "cluster", List.of("warehouse"), List.of(), null);
|
||||
EventSubscription modified = service.modifySubscription("watcher", null, null, null, null, null,
|
||||
false, (type, id) -> false);
|
||||
assertFalse(modified.isEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagKeyAndValueMustMatchTheSameTag() {
|
||||
service.createSubscription("wrong-value", TOPIC, null, List.of(), List.of(), null, null,
|
||||
Map.of("team", "other"), ALL_SOURCES_EXIST);
|
||||
service.createSubscription("wrong-key", TOPIC, null, List.of(), List.of(), null, null,
|
||||
Map.of("owner", "data"), ALL_SOURCES_EXIST);
|
||||
service.createSubscription("matching", TOPIC, null, List.of(), List.of(), null, null,
|
||||
Map.of("team", "data"), ALL_SOURCES_EXIST);
|
||||
assertEquals(List.of("matching"), names(service.describeSubscriptions(null,
|
||||
List.of("team"), List.of("data"), null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventHistoryAndSubscriptionNamesAreRegional() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
RedshiftEventService west = new RedshiftEventService(factory, sns, authorizer,
|
||||
new RegionResolver("us-west-2", "000000000000"), objectMapper, clock);
|
||||
assertTrue(west.describeEvents(null, null, null, null, null, null, null).items().isEmpty());
|
||||
assertTrue(west.describeSubscriptions(null, null, null, null, null).items().isEmpty());
|
||||
west.createSubscription("watcher", TOPIC, null, List.of(), List.of(), null, false, Map.of(),
|
||||
ALL_SOURCES_EXIST);
|
||||
assertTrue(service.describeSubscriptions("watcher", null, null, null, null).items().getFirst().isEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeletedTopicMarksTheSubscriptionAndNeverFailsTheOperation() {
|
||||
create("watcher", null, List.of(), List.of(), null);
|
||||
doThrow(new AwsException("NotFound", "Topic does not exist.", 404))
|
||||
.when(sns).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
|
||||
|
||||
assertEquals("topic-not-exist",
|
||||
service.describeSubscriptions("watcher", null, null, null, null).items().getFirst().getStatus());
|
||||
assertEquals(1, service.describeEvents(null, null, null, null, null, null, null).items().size());
|
||||
|
||||
service.record(RedshiftEventCatalog.CLUSTER_DELETED, "warehouse", "deleted");
|
||||
|
||||
verify(sns, times(1)).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
private EventSubscription create(String name, String sourceType, List<String> sourceIds, List<String> categories,
|
||||
String severity) {
|
||||
return service.createSubscription(name, TOPIC, sourceType, sourceIds, categories, severity, null, Map.of(),
|
||||
ALL_SOURCES_EXIST);
|
||||
}
|
||||
|
||||
private static String code(Runnable action) {
|
||||
return assertThrows(AwsException.class, action::run).getErrorCode();
|
||||
}
|
||||
|
||||
private static List<String> ids(PaginatedResult<RedshiftEvent> page) {
|
||||
return page.items().stream().map(RedshiftEvent::getEventId).toList();
|
||||
}
|
||||
|
||||
private static List<String> names(PaginatedResult<EventSubscription> page) {
|
||||
return page.items().stream().map(EventSubscription::getCustSubscriptionId).toList();
|
||||
}
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now;
|
||||
|
||||
|
||||
+94
-13
@@ -1,10 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
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 org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -14,11 +19,20 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftEventStorageTest {
|
||||
@@ -27,6 +41,7 @@ class RedshiftEventStorageTest {
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
private static final String EAST = "us-east-1";
|
||||
private static final String WEST = "us-west-2";
|
||||
private static final String SUBSCRIPTION = "persistent-watcher";
|
||||
private static final Instant NOW = Instant.parse("2026-10-26T12:00:00Z");
|
||||
|
||||
@TempDir
|
||||
@@ -34,14 +49,19 @@ class RedshiftEventStorageTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void historySurvivesRestart(String mode) {
|
||||
void historyAndSubscriptionsSurviveRestartWithoutReplayingNotifications(String mode) {
|
||||
SnsService sns = sns();
|
||||
String topic = topic(ACCOUNT, EAST);
|
||||
String originalKey;
|
||||
try (Fixture first = fixture(mode, ACCOUNT)) {
|
||||
try (Fixture first = fixture(mode, ACCOUNT, sns)) {
|
||||
createSubscription(first.east(), topic);
|
||||
first.east().record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created before restart");
|
||||
originalKey = history(first.east()).getFirst().getKey();
|
||||
verify(sns).publish(eq(topic), eq(null), anyString(), anyString(), eq(EAST));
|
||||
}
|
||||
|
||||
try (Fixture restarted = fixture(mode, ACCOUNT)) {
|
||||
clearInvocations(sns);
|
||||
try (Fixture restarted = fixture(mode, ACCOUNT, sns)) {
|
||||
restarted.factory().loadAll();
|
||||
restarted.factory().loadAll();
|
||||
List<RedshiftEvent> history = history(restarted.east());
|
||||
@@ -51,49 +71,86 @@ class RedshiftEventStorageTest {
|
||||
assertEquals("REDSHIFT-EVENT-2000", history.getFirst().getEventId());
|
||||
assertEquals("created before restart", history.getFirst().getMessage());
|
||||
|
||||
EventSubscription restored = restarted.east().describeSubscriptions(
|
||||
SUBSCRIPTION, null, null, null, null).items().getFirst();
|
||||
assertEquals(ACCOUNT, restored.getCustomerAwsId());
|
||||
assertEquals(topic, restored.getSnsTopicArn());
|
||||
assertEquals(NOW, restored.getSubscriptionCreationTime());
|
||||
assertEquals(Map.of("team", "analytics"), restored.getTags());
|
||||
assertTrue(restored.isEnabled());
|
||||
assertEquals("active", restored.getStatus());
|
||||
verifyNoInteractions(sns);
|
||||
|
||||
restarted.east().record(RedshiftEventCatalog.CLUSTER_REBOOTED, "warehouse", "rebooted after restart");
|
||||
assertEquals(2, history(restarted.east()).size());
|
||||
verify(sns).publish(eq(topic), eq(null), anyString(), anyString(), eq(EAST));
|
||||
}
|
||||
|
||||
try (Fixture third = fixture(mode, ACCOUNT)) {
|
||||
clearInvocations(sns);
|
||||
try (Fixture third = fixture(mode, ACCOUNT, sns)) {
|
||||
assertEquals(2, history(third.east()).size());
|
||||
assertEquals(2, history(third.east()).stream().map(RedshiftEvent::getKey).distinct().count());
|
||||
assertEquals(List.of("REDSHIFT-EVENT-2000", "REDSHIFT-EVENT-3000"), history(third.east()).stream()
|
||||
.map(RedshiftEvent::getEventId).sorted().toList());
|
||||
verifyNoInteractions(sns);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void persistedHistoryStaysWithinItsAccountAndRegion(String mode) {
|
||||
try (Fixture owner = fixture(mode, ACCOUNT)) {
|
||||
void persistedHistoryAndSubscriptionDeliveryStayWithinTheirAccountAndRegion(String mode) {
|
||||
SnsService sns = sns();
|
||||
String eastTopic = topic(ACCOUNT, EAST);
|
||||
String westTopic = topic(ACCOUNT, WEST);
|
||||
String otherTopic = topic(OTHER_ACCOUNT, EAST);
|
||||
try (Fixture owner = fixture(mode, ACCOUNT, sns)) {
|
||||
createSubscription(owner.east(), eastTopic);
|
||||
createSubscription(owner.west(), westTopic);
|
||||
owner.east().record(RedshiftEventCatalog.CLUSTER_CREATED, "east-cluster", "east owner");
|
||||
owner.west().record(RedshiftEventCatalog.CLUSTER_CREATED, "west-cluster", "west owner");
|
||||
assertEquals(List.of("east-cluster"), sourceIds(owner.east()));
|
||||
assertEquals(List.of("west-cluster"), sourceIds(owner.west()));
|
||||
}
|
||||
|
||||
try (Fixture other = fixture(mode, OTHER_ACCOUNT)) {
|
||||
try (Fixture other = fixture(mode, OTHER_ACCOUNT, sns)) {
|
||||
assertTrue(history(other.east()).isEmpty());
|
||||
assertTrue(history(other.west()).isEmpty());
|
||||
assertTrue(other.east().describeSubscriptions(null, null, null, null, null).items().isEmpty());
|
||||
createSubscription(other.east(), otherTopic);
|
||||
other.east().record(RedshiftEventCatalog.CLUSTER_CREATED, "other-cluster", "other owner");
|
||||
}
|
||||
|
||||
try (Fixture restored = fixture(mode, ACCOUNT)) {
|
||||
clearInvocations(sns);
|
||||
try (Fixture restored = fixture(mode, ACCOUNT, sns)) {
|
||||
assertEquals(List.of("east-cluster"), sourceIds(restored.east()));
|
||||
assertEquals(List.of("west-cluster"), sourceIds(restored.west()));
|
||||
assertEquals(eastTopic, restored.east().describeSubscriptions(SUBSCRIPTION, null, null, null, null)
|
||||
.items().getFirst().getSnsTopicArn());
|
||||
assertEquals(westTopic, restored.west().describeSubscriptions(SUBSCRIPTION, null, null, null, null)
|
||||
.items().getFirst().getSnsTopicArn());
|
||||
restored.east().record(RedshiftEventCatalog.CLUSTER_REBOOTED, "east-cluster", "owner reboot");
|
||||
assertEquals(2, history(restored.east()).size());
|
||||
verify(sns, times(1)).publish(anyString(), any(), anyString(), anyString(), anyString());
|
||||
verify(sns).publish(eq(eastTopic), eq(null), anyString(), anyString(), eq(EAST));
|
||||
assertEquals(1, history(restored.west()).size());
|
||||
}
|
||||
|
||||
try (Fixture otherRestored = fixture(mode, OTHER_ACCOUNT)) {
|
||||
try (Fixture otherRestored = fixture(mode, OTHER_ACCOUNT, sns)) {
|
||||
assertEquals(List.of("other-cluster"), sourceIds(otherRestored.east()));
|
||||
assertTrue(history(otherRestored.west()).isEmpty());
|
||||
EventSubscription subscription = otherRestored.east().describeSubscriptions(
|
||||
SUBSCRIPTION, null, null, null, null).items().getFirst();
|
||||
assertEquals(OTHER_ACCOUNT, subscription.getCustomerAwsId());
|
||||
assertEquals(otherTopic, subscription.getSnsTopicArn());
|
||||
otherRestored.east().modifySubscription(SUBSCRIPTION, null, null, null, null,
|
||||
null, false, (type, id) -> true);
|
||||
}
|
||||
try (Fixture otherDisabled = fixture(mode, OTHER_ACCOUNT, sns)) {
|
||||
assertFalse(otherDisabled.east().describeSubscriptions(SUBSCRIPTION, null, null, null, null)
|
||||
.items().getFirst().isEnabled());
|
||||
}
|
||||
}
|
||||
|
||||
private Fixture fixture(String mode, String account) {
|
||||
private Fixture fixture(String mode, String account, SnsService sns) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(account);
|
||||
when(config.storage().persistentPath()).thenReturn(directory.toString());
|
||||
@@ -102,12 +159,32 @@ class RedshiftEventStorageTest {
|
||||
when(access.storageMode("redshift")).thenReturn(mode);
|
||||
when(access.storageFlushInterval("redshift")).thenReturn(60_000L);
|
||||
StorageFactory factory = new StorageFactory(config, access);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
Clock clock = Clock.fixed(NOW, ZoneOffset.UTC);
|
||||
RedshiftEventService east = new RedshiftEventService(factory, new RegionResolver(EAST, account), clock);
|
||||
RedshiftEventService west = new RedshiftEventService(factory, new RegionResolver(WEST, account), clock);
|
||||
RedshiftEventService east = new RedshiftEventService(factory, sns, allowAll(), new RegionResolver(EAST, account), mapper, clock);
|
||||
RedshiftEventService west = new RedshiftEventService(factory, sns, allowAll(), new RegionResolver(WEST, account), mapper, clock);
|
||||
return new Fixture(factory, east, west);
|
||||
}
|
||||
|
||||
private static ServiceCallAuthorizer allowAll() {
|
||||
ServiceCallAuthorizer authorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
return authorizer;
|
||||
}
|
||||
|
||||
private static SnsService sns() {
|
||||
SnsService sns = mock(SnsService.class);
|
||||
when(sns.topicExists(anyString(), anyString())).thenReturn(true);
|
||||
when(sns.getTopicAttributes(anyString(), anyString())).thenReturn(Map.of());
|
||||
return sns;
|
||||
}
|
||||
|
||||
private static void createSubscription(RedshiftEventService service, String topic) {
|
||||
service.createSubscription(SUBSCRIPTION, topic, null, List.of(), List.of(), null, true,
|
||||
Map.of("team", "analytics"), (type, id) -> true);
|
||||
}
|
||||
|
||||
private static List<RedshiftEvent> history(RedshiftEventService service) {
|
||||
return service.describeEvents(null, null, null, null, null, null, null).items();
|
||||
}
|
||||
@@ -116,6 +193,10 @@ class RedshiftEventStorageTest {
|
||||
return history(service).stream().map(RedshiftEvent::getSourceIdentifier).toList();
|
||||
}
|
||||
|
||||
private static String topic(String account, String region) {
|
||||
return "arn:aws:sns:" + region + ":" + account + ":redshift-events";
|
||||
}
|
||||
|
||||
private record Fixture(StorageFactory factory, RedshiftEventService east,
|
||||
RedshiftEventService west) implements AutoCloseable {
|
||||
@Override
|
||||
|
||||
+264
-39
@@ -10,16 +10,28 @@ import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeEventsResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.Event;
|
||||
import software.amazon.awssdk.services.redshift.model.EventCategoriesMap;
|
||||
import software.amazon.awssdk.services.redshift.model.EventSubscription;
|
||||
import software.amazon.awssdk.services.redshift.model.Parameter;
|
||||
import software.amazon.awssdk.services.redshift.model.RedshiftException;
|
||||
import software.amazon.awssdk.services.redshift.model.Tag;
|
||||
import software.amazon.awssdk.services.redshift.model.TaggedResource;
|
||||
import software.amazon.awssdk.services.sns.SnsClient;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.Message;
|
||||
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -32,6 +44,59 @@ class RedshiftEventsIntegrationTest {
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@Test
|
||||
void sdkSubscriptionLifecyclePreservesNamedListsTagsAndTimestamps() {
|
||||
String name = name();
|
||||
try (RedshiftClient redshift = redshift(Region.US_EAST_1); SnsClient sns = sns(Region.US_EAST_1)) {
|
||||
String topic = sns.createTopic(request -> request.name(name)).topicArn();
|
||||
createGroup(redshift, name);
|
||||
try {
|
||||
EventSubscription created = redshift.createEventSubscription(request -> request
|
||||
.subscriptionName(name).snsTopicArn(topic).sourceType(SOURCE_TYPE)
|
||||
.sourceIds(name).eventCategories("configuration").severity("INFO")
|
||||
.tags(Tag.builder().key("team").value("analytics").build())).eventSubscription();
|
||||
try {
|
||||
assertEquals(name, created.custSubscriptionId());
|
||||
assertEquals(ACCOUNT, created.customerAwsId());
|
||||
assertEquals(SOURCE_TYPE, created.sourceType());
|
||||
assertEquals(List.of(name), created.sourceIdsList());
|
||||
assertEquals(List.of("configuration"), created.eventCategoriesList());
|
||||
assertEquals("INFO", created.severity());
|
||||
assertEquals("active", created.status());
|
||||
assertTrue(created.enabled());
|
||||
assertNotNull(created.subscriptionCreationTime());
|
||||
assertEquals("team", created.tags().getFirst().key());
|
||||
assertEquals("analytics", created.tags().getFirst().value());
|
||||
|
||||
List<EventSubscription> described = redshift.describeEventSubscriptions(request -> request
|
||||
.subscriptionName(name)).eventSubscriptionsList();
|
||||
assertEquals(1, described.size());
|
||||
assertEquals(created.subscriptionCreationTime(), described.getFirst().subscriptionCreationTime());
|
||||
assertEquals(List.of(name), redshift.describeEventSubscriptions(request -> request
|
||||
.tagKeys("team").tagValues("analytics")).eventSubscriptionsList().stream()
|
||||
.map(EventSubscription::custSubscriptionId).filter(name::equals).toList());
|
||||
|
||||
EventSubscription disabled = redshift.modifyEventSubscription(request -> request
|
||||
.subscriptionName(name).enabled(false)).eventSubscription();
|
||||
assertFalse(disabled.enabled());
|
||||
assertEquals(created.subscriptionCreationTime(), disabled.subscriptionCreationTime());
|
||||
assertEquals(List.of(name), disabled.sourceIdsList());
|
||||
assertEquals(List.of("configuration"), disabled.eventCategoriesList());
|
||||
assertEquals("INFO", disabled.severity());
|
||||
} finally {
|
||||
redshift.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
}
|
||||
RedshiftException missing = assertThrows(RedshiftException.class,
|
||||
() -> redshift.describeEventSubscriptions(request -> request.subscriptionName(name)));
|
||||
assertEquals("SubscriptionNotFound", missing.awsErrorDetails().errorCode());
|
||||
assertEquals(404, missing.statusCode());
|
||||
} finally {
|
||||
redshift.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
sns.deleteTopic(request -> request.topicArn(topic));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkDescribesRealParameterGroupEventsAndCategoryMetadata() {
|
||||
String name = name();
|
||||
@@ -71,57 +136,196 @@ class RedshiftEventsIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkReceivesAwsErrorsForAnUnpairedSourceAndOutOfRangePages() {
|
||||
void sdkSubscriptionDeliversMatchingEventsThroughSnsToSqsAndStopsWhenDisabled() {
|
||||
String name = name();
|
||||
try (RedshiftClient redshift = redshift(Region.US_EAST_1)) {
|
||||
RedshiftException unpaired = assertThrows(RedshiftException.class, () -> redshift.describeEvents(request ->
|
||||
request.sourceIdentifier(name)));
|
||||
assertEquals("InvalidParameterCombination", unpaired.awsErrorDetails().errorCode());
|
||||
RedshiftException pageSize = assertThrows(RedshiftException.class, () -> redshift.describeEvents(request ->
|
||||
request.maxRecords(19)));
|
||||
assertEquals("InvalidParameterValue", pageSize.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyIsIsolatedByRegion() {
|
||||
String name = name();
|
||||
try (RedshiftClient east = redshift(Region.US_EAST_1); RedshiftClient west = redshift(Region.US_WEST_2)) {
|
||||
createGroup(east, name);
|
||||
try (RedshiftClient redshift = redshift(Region.US_EAST_1); SnsClient sns = sns(Region.US_EAST_1);
|
||||
SqsClient sqs = sqs()) {
|
||||
String topic = sns.createTopic(request -> request.name(name)).topicArn();
|
||||
String queue = sqs.createQueue(request -> request.queueName(name)).queueUrl();
|
||||
String queueArn = sqs.getQueueAttributes(request -> request.queueUrl(queue)
|
||||
.attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN);
|
||||
String snsSubscription = sns.subscribe(request -> request.topicArn(topic).protocol("sqs")
|
||||
.endpoint(queueArn).attributes(Map.of("RawMessageDelivery", "true"))).subscriptionArn();
|
||||
redshift.createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(topic)
|
||||
.sourceType(SOURCE_TYPE).eventCategories("configuration").severity("INFO"));
|
||||
try {
|
||||
assertEquals(1, east.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
assertTrue(west.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().isEmpty());
|
||||
createGroup(redshift, name);
|
||||
try {
|
||||
AtomicReference<Message> received = new AtomicReference<>();
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> {
|
||||
List<Message> messages = sqs.receiveMessage(request -> request.queueUrl(queue)
|
||||
.maxNumberOfMessages(1).waitTimeSeconds(0)).messages();
|
||||
if (messages.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
received.set(messages.getFirst());
|
||||
return true;
|
||||
});
|
||||
assertTrue(received.get().body().contains("REDSHIFT-EVENT-1003"));
|
||||
assertTrue(received.get().body().contains(name));
|
||||
sqs.deleteMessage(request -> request.queueUrl(queue).receiptHandle(received.get().receiptHandle()));
|
||||
|
||||
redshift.modifyEventSubscription(request -> request.subscriptionName(name).enabled(false));
|
||||
redshift.modifyClusterParameterGroup(request -> request.parameterGroupName(name)
|
||||
.parameters(Parameter.builder().parameterName("statement_timeout").parameterValue("5001").build()));
|
||||
assertTrue(sqs.receiveMessage(request -> request.queueUrl(queue).waitTimeSeconds(1)).messages().isEmpty());
|
||||
} finally {
|
||||
redshift.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
}
|
||||
} finally {
|
||||
east.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
redshift.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
sns.unsubscribe(request -> request.subscriptionArn(snsSubscription));
|
||||
sns.deleteTopic(request -> request.topicArn(topic));
|
||||
sqs.deleteQueue(request -> request.queueUrl(queue));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyIsIsolatedByAccount() {
|
||||
void sdkReceivesAwsErrorsForInvalidFiltersAndFifoTopics() {
|
||||
String name = name();
|
||||
String otherAccount = "414141414141";
|
||||
try (RedshiftClient owner = redshift(Region.US_EAST_1, ACCOUNT);
|
||||
RedshiftClient other = redshift(Region.US_EAST_1, otherAccount)) {
|
||||
createGroup(owner, name);
|
||||
try (RedshiftClient redshift = redshift(Region.US_EAST_1); SnsClient sns = sns(Region.US_EAST_1)) {
|
||||
String topic = sns.createTopic(request -> request.name(name)).topicArn();
|
||||
String fifo = sns.createTopic(request -> request.name(name + ".fifo")
|
||||
.attributes(Map.of("FifoTopic", "true"))).topicArn();
|
||||
try {
|
||||
assertEquals(1, owner.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
assertTrue(other.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().isEmpty());
|
||||
createGroup(other, name);
|
||||
RedshiftException unpaired = assertThrows(RedshiftException.class, () -> redshift.describeEvents(request ->
|
||||
request.sourceIdentifier(name)));
|
||||
assertEquals("InvalidParameterCombination", unpaired.awsErrorDetails().errorCode());
|
||||
RedshiftException severity = assertThrows(RedshiftException.class, () -> redshift.createEventSubscription(
|
||||
request -> request.subscriptionName(name).snsTopicArn(topic).severity("WARN")));
|
||||
assertEquals("SubscriptionSeverityNotFound", severity.awsErrorDetails().errorCode());
|
||||
RedshiftException fifoError = assertThrows(RedshiftException.class, () -> redshift.createEventSubscription(
|
||||
request -> request.subscriptionName(name).snsTopicArn(fifo)));
|
||||
assertEquals("SNSInvalidTopic", fifoError.awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
sns.deleteTopic(request -> request.topicArn(topic));
|
||||
sns.deleteTopic(request -> request.topicArn(fifo));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionNamesAndHistoryAreIsolatedByRegion() {
|
||||
String name = name();
|
||||
try (RedshiftClient east = redshift(Region.US_EAST_1); RedshiftClient west = redshift(Region.US_WEST_2);
|
||||
SnsClient eastSns = sns(Region.US_EAST_1); SnsClient westSns = sns(Region.US_WEST_2)) {
|
||||
String eastTopic = eastSns.createTopic(request -> request.name(name)).topicArn();
|
||||
String westTopic = westSns.createTopic(request -> request.name(name)).topicArn();
|
||||
east.createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(eastTopic));
|
||||
try {
|
||||
west.createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(westTopic));
|
||||
try {
|
||||
assertEquals(1, other.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
assertEquals(1, owner.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
assertEquals(eastTopic, east.describeEventSubscriptions(request -> request.subscriptionName(name))
|
||||
.eventSubscriptionsList().getFirst().snsTopicArn());
|
||||
assertEquals(westTopic, west.describeEventSubscriptions(request -> request.subscriptionName(name))
|
||||
.eventSubscriptionsList().getFirst().snsTopicArn());
|
||||
createGroup(east, name);
|
||||
try {
|
||||
assertTrue(west.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().isEmpty());
|
||||
} finally {
|
||||
east.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
}
|
||||
} finally {
|
||||
other.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
west.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
}
|
||||
} finally {
|
||||
owner.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
east.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
eastSns.deleteTopic(request -> request.topicArn(eastTopic));
|
||||
westSns.deleteTopic(request -> request.topicArn(westTopic));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkTagsSubscriptionArnAndSubscriptionDescriptionsReflectChanges() {
|
||||
String name = name();
|
||||
String arn = "arn:aws:redshift:us-east-1:" + ACCOUNT + ":eventsubscription:" + name;
|
||||
Tag original = Tag.builder().key("team").value("analytics").build();
|
||||
Tag updated = Tag.builder().key("team").value("platform").build();
|
||||
Tag environment = Tag.builder().key("environment").value("test").build();
|
||||
try (RedshiftClient redshift = redshift(Region.US_EAST_1); SnsClient sns = sns(Region.US_EAST_1)) {
|
||||
String topic = sns.createTopic(request -> request.name(name)).topicArn();
|
||||
try {
|
||||
redshift.createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(topic).tags(original));
|
||||
try {
|
||||
List<TaggedResource> initial = redshift.describeTags(request -> request.resourceName(arn)).taggedResources();
|
||||
assertEquals(1, initial.size());
|
||||
assertEquals(arn, initial.getFirst().resourceName());
|
||||
assertEquals("eventsubscription", initial.getFirst().resourceType());
|
||||
assertEquals(original, initial.getFirst().tag());
|
||||
|
||||
redshift.createTags(request -> request.resourceName(arn).tags(updated, environment));
|
||||
List<Tag> described = redshift.describeTags(request -> request.resourceName(arn)).taggedResources()
|
||||
.stream().map(TaggedResource::tag).toList();
|
||||
assertEquals(2, described.size());
|
||||
assertTrue(described.containsAll(List.of(updated, environment)));
|
||||
List<Tag> subscriptionTags = redshift.describeEventSubscriptions(request -> request.subscriptionName(name))
|
||||
.eventSubscriptionsList().getFirst().tags();
|
||||
assertEquals(2, subscriptionTags.size());
|
||||
assertTrue(subscriptionTags.containsAll(List.of(updated, environment)));
|
||||
|
||||
redshift.deleteTags(request -> request.resourceName(arn).tagKeys("team"));
|
||||
assertEquals(List.of(environment), redshift.describeTags(request -> request.resourceName(arn))
|
||||
.taggedResources().stream().map(TaggedResource::tag).toList());
|
||||
assertEquals(List.of(environment), redshift.describeEventSubscriptions(request -> request.subscriptionName(name))
|
||||
.eventSubscriptionsList().getFirst().tags());
|
||||
} finally {
|
||||
redshift.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
}
|
||||
} finally {
|
||||
sns.deleteTopic(request -> request.topicArn(topic));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionNamesAndHistoryAreIsolatedByAccount() {
|
||||
String name = name();
|
||||
String otherAccount = "414141414141";
|
||||
try (RedshiftClient owner = redshift(Region.US_EAST_1); RedshiftClient other = redshift(Region.US_EAST_1, otherAccount);
|
||||
SnsClient ownerSns = sns(Region.US_EAST_1); SnsClient otherSns = sns(Region.US_EAST_1, otherAccount)) {
|
||||
String ownerTopic = ownerSns.createTopic(request -> request.name(name)).topicArn();
|
||||
String otherTopic = otherSns.createTopic(request -> request.name(name)).topicArn();
|
||||
try {
|
||||
owner.createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(ownerTopic));
|
||||
try {
|
||||
assertTrue(other.describeEventSubscriptions().eventSubscriptionsList().stream()
|
||||
.noneMatch(subscription -> name.equals(subscription.custSubscriptionId())));
|
||||
other.createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(otherTopic));
|
||||
try {
|
||||
assertEquals(ACCOUNT, owner.describeEventSubscriptions(request -> request.subscriptionName(name))
|
||||
.eventSubscriptionsList().getFirst().customerAwsId());
|
||||
assertEquals(otherAccount, other.describeEventSubscriptions(request -> request.subscriptionName(name))
|
||||
.eventSubscriptionsList().getFirst().customerAwsId());
|
||||
createGroup(owner, name);
|
||||
try {
|
||||
assertEquals(1, owner.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
assertTrue(other.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().isEmpty());
|
||||
createGroup(other, name);
|
||||
try {
|
||||
assertEquals(1, other.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
assertEquals(1, owner.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
|
||||
.events().size());
|
||||
} finally {
|
||||
other.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
}
|
||||
} finally {
|
||||
owner.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
|
||||
}
|
||||
} finally {
|
||||
other.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
}
|
||||
} finally {
|
||||
owner.deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
}
|
||||
} finally {
|
||||
ownerSns.deleteTopic(request -> request.topicArn(ownerTopic));
|
||||
otherSns.deleteTopic(request -> request.topicArn(otherTopic));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,8 +336,29 @@ class RedshiftEventsIntegrationTest {
|
||||
|
||||
private RedshiftClient redshift(Region region, String account) {
|
||||
return RedshiftClient.builder().endpointOverride(endpoint).region(region)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
|
||||
.build();
|
||||
.credentialsProvider(credentials(account)).build();
|
||||
}
|
||||
|
||||
private SnsClient sns(Region region) {
|
||||
return sns(region, ACCOUNT);
|
||||
}
|
||||
|
||||
private SnsClient sns(Region region, String account) {
|
||||
return SnsClient.builder().endpointOverride(endpoint).region(region)
|
||||
.credentialsProvider(credentials(account)).build();
|
||||
}
|
||||
|
||||
private SqsClient sqs() {
|
||||
return SqsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(credentials()).build();
|
||||
}
|
||||
|
||||
private static StaticCredentialsProvider credentials() {
|
||||
return credentials(ACCOUNT);
|
||||
}
|
||||
|
||||
private static StaticCredentialsProvider credentials(String account) {
|
||||
return StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"));
|
||||
}
|
||||
|
||||
private static String name() {
|
||||
|
||||
+14
@@ -3,12 +3,14 @@ package io.github.hectorvent.floci.services.redshift;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
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.Parameter;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
|
||||
import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant;
|
||||
@@ -33,6 +35,18 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftQueryHandlerTest {
|
||||
|
||||
@Test
|
||||
void eventSubscriptionResponsesUseTheRedshiftNamespace() {
|
||||
EventSubscription subscription = new EventSubscription();
|
||||
subscription.setCustSubscriptionId("watcher");
|
||||
subscription.setSubscriptionCreationTime(Instant.parse("2026-10-26T12:00:00Z"));
|
||||
when(service.createEventSubscription(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(subscription);
|
||||
Response response = handler.handle("CreateEventSubscription", new MultivaluedHashMap<>());
|
||||
assertTrue(response.getEntity().toString().contains(
|
||||
"<CreateEventSubscriptionResponse xmlns=\"" + AwsNamespaces.REDSHIFT + "\">"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonFiniteEventTimestampsReturnAnAwsValidationError() {
|
||||
for (String invalid : List.of("NaN", "Infinity", "-Infinity", "1e300")) {
|
||||
|
||||
@@ -2435,6 +2435,14 @@ class RedshiftServiceTest {
|
||||
service.createTags("arn:aws:redshift:us-east-1:111111111111:reservednode:foo", Map.of("env", "test")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeTagsRejectsEventSubscriptionArnWithoutName() {
|
||||
AwsException e = assertThrows(AwsException.class, () ->
|
||||
service.describeTags("arn:aws:redshift:us-east-1:111111111111:eventsubscription:", null, null));
|
||||
|
||||
assertEquals("InvalidParameterValue", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeTagsForSpecificResource() {
|
||||
Cluster cluster = new Cluster();
|
||||
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.redshift.model.Event;
|
||||
import software.amazon.awssdk.services.sns.SnsClient;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.Message;
|
||||
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.doAnswer;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftSnapshotEventsIntegrationTest {
|
||||
|
||||
private static final String OWNER = "565656565656";
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
|
||||
@InjectMock
|
||||
RedshiftContainerManager manager;
|
||||
@InjectMock
|
||||
RedshiftProxyManager proxy;
|
||||
@Inject
|
||||
RedshiftSnapshotScheduler scheduler;
|
||||
@Inject
|
||||
StorageFactory factory;
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void backgroundSnapshotHistoryAndNotificationsUseTheResourceAccountAndRegion(boolean snapshotFails) throws Exception {
|
||||
String name = "sdk-snapshot-events-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String clusterId = name + "-cluster";
|
||||
String scheduleId = name + "-schedule";
|
||||
String terminalEvent = snapshotFails ? "REDSHIFT-EVENT-3503" : "REDSHIFT-EVENT-3004";
|
||||
when(manager.start(anyString(), anyString(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(new RedshiftContainerHandle("mock", clusterId, "localhost", 5432));
|
||||
doAnswer(invocation -> {
|
||||
if (snapshotFails) {
|
||||
throw new IOException("snapshot failed for " + clusterId);
|
||||
}
|
||||
Files.writeString(invocation.getArgument(3, Path.class), "backup contents");
|
||||
return null;
|
||||
}).when(manager).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
|
||||
|
||||
try (Scope ownerWest = scope(OWNER, Region.US_WEST_2);
|
||||
Scope fallback = scope(DEFAULT_ACCOUNT, Region.US_EAST_1);
|
||||
Scope ownerEast = scope(OWNER, Region.US_EAST_1);
|
||||
Watcher westWatcher = watcher(ownerWest, name);
|
||||
Watcher fallbackWatcher = watcher(fallback, name);
|
||||
Watcher eastWatcher = watcher(ownerEast, name)) {
|
||||
ownerWest.redshift().createSnapshotSchedule(request -> request.scheduleIdentifier(scheduleId)
|
||||
.scheduleDefinitions("rate(1 hour)"));
|
||||
try {
|
||||
ownerWest.redshift().createCluster(request -> request.clusterIdentifier(clusterId).nodeType("dc2.large")
|
||||
.masterUsername("admin").masterUserPassword("Secret123").automatedSnapshotRetentionPeriod(1));
|
||||
try {
|
||||
ownerWest.redshift().modifyClusterSnapshotSchedule(request -> request.clusterIdentifier(clusterId)
|
||||
.scheduleIdentifier(scheduleId));
|
||||
AccountAwareStorageBackend<Cluster> clusters = factory.create("redshift", "redshift-clusters.json",
|
||||
new TypeReference<Map<String, Cluster>>() { });
|
||||
Instant due = clusters.getForAccount(OWNER, clusterId).orElseThrow()
|
||||
.getAutomatedSnapshotAnchor().plusSeconds(3600);
|
||||
CompletableFuture.runAsync(() -> scheduler.tick(due)).get(20, TimeUnit.SECONDS);
|
||||
|
||||
List<Event> history = snapshotEvents(ownerWest.redshift(), clusterId);
|
||||
assertEquals(List.of("REDSHIFT-EVENT-2009", terminalEvent), history.stream().map(Event::eventId).toList());
|
||||
assertTrue(snapshotEvents(fallback.redshift(), clusterId).isEmpty(),
|
||||
"Background events must not be stored under the default account");
|
||||
assertTrue(snapshotEvents(ownerEast.redshift(), clusterId).isEmpty(),
|
||||
"Background events must not use the default region within the resource account");
|
||||
|
||||
List<Message> delivered = receiveTwo(ownerWest.sqs(), westWatcher.queueUrl());
|
||||
assertEquals(2, delivered.size());
|
||||
assertTrue(delivered.stream().allMatch(message -> message.body().contains(clusterId)));
|
||||
assertTrue(delivered.stream().anyMatch(message -> message.body().contains("REDSHIFT-EVENT-2009")));
|
||||
assertTrue(delivered.stream().anyMatch(message -> message.body().contains(terminalEvent)));
|
||||
assertTrue(fallback.sqs().receiveMessage(request -> request.queueUrl(fallbackWatcher.queueUrl())
|
||||
.waitTimeSeconds(0)).messages().isEmpty(), "Default-account subscription received a foreign event");
|
||||
assertTrue(ownerEast.sqs().receiveMessage(request -> request.queueUrl(eastWatcher.queueUrl())
|
||||
.waitTimeSeconds(0)).messages().isEmpty(), "Another region's subscription received the snapshot event");
|
||||
verify(manager).takeSnapshot(eq(OWNER), eq(clusterId), eq("admin"), any(Path.class));
|
||||
} finally {
|
||||
ownerWest.redshift().deleteCluster(request -> request.clusterIdentifier(clusterId).skipFinalClusterSnapshot(true));
|
||||
}
|
||||
} finally {
|
||||
ownerWest.redshift().deleteSnapshotSchedule(request -> request.scheduleIdentifier(scheduleId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Scope scope(String account, Region region) {
|
||||
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"));
|
||||
RedshiftClient redshift = RedshiftClient.builder().endpointOverride(endpoint).region(region)
|
||||
.credentialsProvider(credentials).build();
|
||||
SnsClient sns = SnsClient.builder().endpointOverride(endpoint).region(region).credentialsProvider(credentials).build();
|
||||
SqsClient sqs = SqsClient.builder().endpointOverride(endpoint).region(region).credentialsProvider(credentials).build();
|
||||
return new Scope(redshift, sns, sqs);
|
||||
}
|
||||
|
||||
private static Watcher watcher(Scope scope, String name) {
|
||||
String topic = scope.sns().createTopic(request -> request.name(name)).topicArn();
|
||||
String queue = scope.sqs().createQueue(request -> request.queueName(name)).queueUrl();
|
||||
String queueArn = scope.sqs().getQueueAttributes(request -> request.queueUrl(queue)
|
||||
.attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN);
|
||||
String snsSubscription = scope.sns().subscribe(request -> request.topicArn(topic).protocol("sqs")
|
||||
.endpoint(queueArn).attributes(Map.of("RawMessageDelivery", "true"))).subscriptionArn();
|
||||
scope.redshift().createEventSubscription(request -> request.subscriptionName(name).snsTopicArn(topic)
|
||||
.sourceType("cluster-snapshot"));
|
||||
return new Watcher(scope, name, topic, queue, snsSubscription);
|
||||
}
|
||||
|
||||
private static List<Event> snapshotEvents(RedshiftClient client, String clusterId) {
|
||||
return client.describeEvents().events().stream()
|
||||
.filter(event -> "cluster-snapshot".equals(event.sourceTypeAsString()) && event.message().contains(clusterId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<Message> receiveTwo(SqsClient sqs, String queue) {
|
||||
List<Message> received = new ArrayList<>();
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> {
|
||||
received.addAll(sqs.receiveMessage(request -> request.queueUrl(queue).maxNumberOfMessages(10)
|
||||
.waitTimeSeconds(0)).messages());
|
||||
return received.size() >= 2;
|
||||
});
|
||||
return received;
|
||||
}
|
||||
|
||||
private record Scope(RedshiftClient redshift, SnsClient sns, SqsClient sqs) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
redshift.close();
|
||||
sns.close();
|
||||
sqs.close();
|
||||
}
|
||||
}
|
||||
|
||||
private record Watcher(Scope scope, String name, String topicArn,
|
||||
String queueUrl, String snsSubscription) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
scope.redshift().deleteEventSubscription(request -> request.subscriptionName(name));
|
||||
scope.sns().unsubscribe(request -> request.subscriptionArn(snsSubscription));
|
||||
scope.sns().deleteTopic(request -> request.topicArn(topicArn));
|
||||
scope.sqs().deleteQueue(request -> request.queueUrl(queueUrl));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user