Light, fluffy, and always free - The AWS Local Emulator alternative
feat(redshift): publish CloudWatch cluster metrics (#6740)
Vũ Thế Huy5bd4bd481a53
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftMetricsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftMetricsTest.javanew file mode 100644index 0000000000..c43c8992fc--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftMetricsTest.java@@ -0,0 +1,65 @@+package com.floci.test;++import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;+import software.amazon.awssdk.services.cloudwatch.model.Datapoint;+import software.amazon.awssdk.services.cloudwatch.model.Dimension;+import software.amazon.awssdk.services.cloudwatch.model.Statistic;+import software.amazon.awssdk.services.redshift.RedshiftClient;++import java.time.Duration;+import java.time.Instant;+import java.util.List;+import java.util.UUID;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++@DisplayName("Redshift CloudWatch metrics")+class RedshiftMetricsTest {++ private static final Duration PUBLISH_TIMEOUT = Duration.ofSeconds(150);++ @Test+ @DisplayName("SDK reads HealthStatus and DatabaseConnections of an available cluster from AWS/Redshift")+ void availableClusterPublishesStateMetrics() throws InterruptedException {+ assumeFalse(TestFixtures.isRealAws(), "Relies on Floci publishing within its one-minute tick");+ String clusterId = "compat-rsmetric-" + UUID.randomUUID().toString().substring(0, 8);+ Dimension dimension = Dimension.builder().name("ClusterIdentifier").value(clusterId).build();+ try (RedshiftClient redshift = TestFixtures.redshiftClient();+ CloudWatchClient cloudWatch = TestFixtures.cloudWatchClient()) {+ redshift.createCluster(request -> request.clusterIdentifier(clusterId).nodeType("dc2.large")+ .masterUsername("admin").masterUserPassword("Secret123"));+ try {+ List<Datapoint> health = awaitDatapoints(cloudWatch, "HealthStatus", dimension);+ assertThat(health).isNotEmpty();+ assertThat(health.get(0).sum()).isEqualTo(1.0);+ assertThat(health.get(0).unitAsString()).isEqualTo("Count");++ List<Datapoint> connections = awaitDatapoints(cloudWatch, "DatabaseConnections", dimension);+ assertThat(connections).isNotEmpty();+ assertThat(connections.get(0).sum()).isGreaterThanOrEqualTo(0.0);+ } finally {+ redshift.deleteCluster(request -> request.clusterIdentifier(clusterId)+ .skipFinalClusterSnapshot(true));+ }+ }+ }++ private static List<Datapoint> awaitDatapoints(CloudWatchClient cloudWatch, String metricName,+ Dimension dimension) throws InterruptedException {+ TestFixtures.await(() -> !datapoints(cloudWatch, metricName, dimension).isEmpty(),+ dimension.value(), "AWS/Redshift " + metricName + " datapoints",+ PUBLISH_TIMEOUT.toNanos(), 1_000);+ return datapoints(cloudWatch, metricName, dimension);+ }++ private static List<Datapoint> datapoints(CloudWatchClient cloudWatch, String metricName, Dimension dimension) {+ return cloudWatch.getMetricStatistics(request -> request.namespace("AWS/Redshift")+ .metricName(metricName).dimensions(dimension)+ .startTime(Instant.now().minus(Duration.ofMinutes(10)))+ .endTime(Instant.now().plus(Duration.ofMinutes(2)))+ .period(60).statistics(Statistic.SUM)).datapoints();+ }+}diff --git a/docs/services/redshift.md b/docs/services/redshift.mdindex 9d0c82282f..b234fe437c 100644--- a/docs/services/redshift.md+++ b/docs/services/redshift.md@@ -286,6 +286,30 @@ are coalesced to one current backup, which contains the data at dump time, ratheas historical backups. Older persisted clusters acquire their initial scheduling anchor on thefirst sweep. Cleanup after deleting a cluster runs on the next sweep.+## CloudWatch metrics++Floci publishes metrics for every `available` cluster to the `AWS/Redshift` CloudWatch namespace once a minute, each stamped with the minute that ended. The only dimension is `ClusterIdentifier`.++Each minute is attempted at most once per publisher lifetime. After a pause, overdue ticks skip minutes already attempted instead of publishing duplicate samples. Failed writes are not retried within the same minute because they may already have stored some samples.++| Metric | Unit | Value |+| --- | --- | --- |+| `HealthStatus` | `Count` | `1` while the cluster is `available` |+| `MaintenanceMode` | `Count` | `0`; Floci models no maintenance windows |+| `DatabaseConnections` | `Count` | Clients currently connected through the cluster's auth proxy |++A cluster that is not `available` (for example `creating`, `deleting` or `failed`) publishes nothing, and `DatabaseConnections` is omitted for a cluster whose proxy is not running. A reboot keeps the status `available`, so `HealthStatus` stays `1` during it and `DatabaseConnections` is omitted until the proxy is back. `DatabaseConnections` counts PostgreSQL wire-protocol clients only: the [Redshift Data API](redshift-data.md) reaches the database around the proxy, so its connections are not counted. Datapoints older than 15 days are dropped hourly.++```bash+aws --endpoint-url http://localhost:4566 cloudwatch get-metric-statistics \+ --namespace AWS/Redshift --metric-name HealthStatus \+ --dimensions Name=ClusterIdentifier,Value=my-cluster \+ --start-time "$(date -u -d '-10 minutes' +%FT%TZ)" --end-time "$(date -u +%FT%TZ)" \+ --period 60 --statistics Sum+```++Set `FLOCI_SERVICES_REDSHIFT_CLOUDWATCH_METRICS_ENABLED=false` to turn publishing off. Publishing also requires the CloudWatch Metrics service to be enabled.+## DynamoDB zero-ETLThe supported zero-ETL path is DynamoDB Streams to a provisioned Redshift cluster. The source ARN@@ -378,6 +402,7 @@ For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyC|----------|---------|-------------|| `FLOCI_SERVICES_REDSHIFT_ENABLED` | `true` | Enable or disable Redshift || `FLOCI_SERVICES_REDSHIFT_AUTOMATED_SNAPSHOTS_ENABLED` | `true` | Run background automated snapshot and retention sweeps |+| `FLOCI_SERVICES_REDSHIFT_CLOUDWATCH_METRICS_ENABLED` | `true` | Publish the `AWS/Redshift` metrics of available clusters to CloudWatch once a minute, see [CloudWatch metrics](#cloudwatch-metrics) || `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_SWEEP_INTERVAL_SECONDS` | `60` | Delay between background snapshot sweeps || `FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION` | `postgres:15-alpine` | PostgreSQL Docker image backing each cluster || `FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT` | `5439` | Reported Redshift port hint (the real host port is dynamic and comes from `DescribeClusters`) |diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex d5a726b52e..98240f50ff 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -1725,6 +1725,13 @@ public interface EmulatorConfig {interface RedshiftServiceConfig {@WithDefault("true")boolean automatedSnapshotsEnabled();++ /**+ * Publish the AWS/Redshift CloudWatch metrics of every available cluster once a minute.+ * Env: FLOCI_SERVICES_REDSHIFT_CLOUDWATCH_METRICS_ENABLED+ */+ @WithDefault("true")+ boolean cloudwatchMetricsEnabled();@WithDefault("60")long snapshotSweepIntervalSeconds();@WithDefault("true")diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/MinuteMetricsPublisher.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/MinuteMetricsPublisher.javanew file mode 100644index 0000000000..5841328d52--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/MinuteMetricsPublisher.java@@ -0,0 +1,127 @@+package io.github.hectorvent.floci.services.cloudwatch.metrics;++import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import org.jboss.logging.Logger;++import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.List;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;++/**+ * Shared scheduling, minute claims and retention for service-generated CloudWatch metrics. A tick+ * runs just after each minute boundary and stamps its samples with the minute that ended, so a call+ * lands in the minute it was made, as on AWS. Once an hour it drops the namespace's datapoints older+ * than the 15 days AWS keeps one-minute data, so the generated history stays bounded.+ */+public abstract class MinuteMetricsPublisher<T> {++ private static final Logger LOG = Logger.getLogger(MinuteMetricsPublisher.class);+ private static final long MINUTE_MILLIS = 60_000;+ private static final long TICK_OFFSET_MILLIS = 1_000;+ private static final Duration RETENTION = Duration.ofDays(15);++ private final CloudWatchMetricsService metricsService;+ private final String namespace;+ private final boolean enabled;+ private final Clock clock;+ private final ScheduledExecutorService scheduler;+ private long lastAttemptedMinute = Long.MIN_VALUE;++ protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled) {+ this(metricsService, namespace, enabled, Clock.systemUTC(), Executors.newSingleThreadScheduledExecutor(task -> {+ Thread thread = new Thread(task, namespace + "-metrics-publisher");+ thread.setDaemon(true);+ return thread;+ }));+ }++ protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled,+ Clock clock, ScheduledExecutorService scheduler) {+ this.metricsService = metricsService;+ this.namespace = namespace;+ this.enabled = enabled;+ this.clock = clock;+ this.scheduler = scheduler;+ }++ public void start() {+ if (!enabled) {+ return;+ }+ long untilNextMinute = MINUTE_MILLIS - clock.millis() % MINUTE_MILLIS;+ scheduler.scheduleAtFixedRate(() -> publish(clock.instant()), untilNextMinute + TICK_OFFSET_MILLIS,+ MINUTE_MILLIS, TimeUnit.MILLISECONDS);+ }++ /** Finish a running tick before EmulatorLifecycle shuts down storage. */+ public void stop() {+ scheduler.shutdown();+ try {+ if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {+ LOG.warnv("The {0} metrics publisher did not finish its tick within 5 seconds", namespace);+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ LOG.warnv(e, "Interrupted while stopping the {0} metrics publisher", namespace);+ }+ }++ /**+ * Nothing may escape: the scheduler stops for good after a tick throws. One target's failed write+ * drops only that target's samples for the minute.+ */+ public synchronized void publish(Instant now) {+ long minute = endedMinute(now);+ if (minute <= lastAttemptedMinute) {+ return;+ }+ // Collection can drain counters, and a failed write may already have stored some samples.+ lastAttemptedMinute = minute;+ List<T> targets;+ try {+ targets = collectTargets(now);+ } catch (RuntimeException e) {+ LOG.warnv(e, "Collecting {0} metric targets failed; this minute's samples are dropped", namespace);+ return;+ }+ for (T target : targets) {+ try {+ List<MetricDatum> datums = collectDatums(target, minute);+ if (!datums.isEmpty()) {+ metricsService.putMetricDataForAccount(accountId(target), namespace, datums, region(target));+ }+ } catch (RuntimeException e) {+ LOG.warnv(e, "Publishing {0} metrics for {1} of account {2} in {3} failed; its samples are dropped",+ namespace, targetName(target), accountId(target), region(target));+ }+ }+ if (minute % 3600 == 0) {+ try {+ metricsService.deleteMetricDataBefore(namespace, Instant.ofEpochSecond(minute).minus(RETENTION));+ } catch (RuntimeException e) {+ LOG.warnv(e, "Dropping {0} datapoints older than {1} failed; the next hour tries again",+ namespace, RETENTION);+ }+ }+ }++ /** Reading half a minute back absorbs drift of the fixed-rate schedule away from the boundary. */+ private static long endedMinute(Instant tick) {+ return tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES).getEpochSecond();+ }++ protected abstract List<T> collectTargets(Instant now);++ protected abstract List<MetricDatum> collectDatums(T target, long timestampSeconds);++ protected abstract String accountId(T target);++ protected abstract String region(T target);++ protected abstract String targetName(T target);+}diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.javaindex 2ccd9412b4..df07517da9 100644--- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo;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.metrics.RedshiftMetricTarget;import io.github.hectorvent.floci.services.redshift.model.AutomatedSnapshotState;import io.github.hectorvent.floci.services.redshift.model.Cluster;import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;@@ -788,6 +789,15 @@ public class RedshiftService implements ManagedSecretRotator {return clusters.scanForAccount(accountId, k -> true);}+ /** The available clusters of every account, for the AWS/Redshift metrics publisher. */+ public List<RedshiftMetricTarget> availableMetricTargets() {+ return clusters.scanAllAccountEntries(k -> true).stream()+ .filter(entry -> "available".equals(entry.value().getClusterStatus()))+ .map(entry -> new RedshiftMetricTarget(entry.accountId(), snapshotRegion(entry.value()),+ entry.value(), relayKey(entry.accountId(), entry.value().getClusterIdentifier())))+ .toList();+ }+/** Internal deletion used by provisioner cleanup, which explicitly skips the final snapshot. */public Cluster deleteCluster(String identifier) {return deleteCluster(identifier, true, null, null);diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftClusterStateMetricCollector.java b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftClusterStateMetricCollector.javanew file mode 100644index 0000000000..6dc7b69095--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftClusterStateMetricCollector.java@@ -0,0 +1,47 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.ArrayList;+import java.util.List;+import java.util.OptionalInt;++/**+ * The metrics Floci can report from its own state: health and maintenance follow the cluster status, and+ * DatabaseConnections is the number of clients open on the cluster's auth proxy. Data API connections+ * reach the database around that proxy and are not counted.+ */+@ApplicationScoped+public class RedshiftClusterStateMetricCollector implements RedshiftMetricCollector {++ private static final String COUNT = "Count";++ private final RedshiftProxyManager proxyManager;++ @Inject+ public RedshiftClusterStateMetricCollector(RedshiftProxyManager proxyManager) {+ this.proxyManager = proxyManager;+ }++ @Override+ public List<MetricDatum> collect(RedshiftMetricTarget target, long timestampSeconds) {+ if (!"available".equals(target.cluster().getClusterStatus())) {+ return List.of();+ }+ String identifier = target.cluster().getClusterIdentifier();+ List<Dimension> dimensions = List.of(new Dimension("ClusterIdentifier", identifier));+ List<MetricDatum> datums = new ArrayList<>(List.of(+ MetricDatum.of("HealthStatus", COUNT, 1, dimensions, timestampSeconds),+ MetricDatum.of("MaintenanceMode", COUNT, 0, dimensions, timestampSeconds)));+ OptionalInt connections = proxyManager.activeConnections(target.proxyKey());+ if (connections.isPresent()) {+ datums.add(MetricDatum.of("DatabaseConnections", COUNT, connections.getAsInt(), dimensions,+ timestampSeconds));+ }+ return datums;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricCollector.java b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricCollector.javanew file mode 100644index 0000000000..6fe5f3e8c6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricCollector.java@@ -0,0 +1,15 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;++import java.util.List;++/**+ * Supplies AWS/Redshift samples for one cluster each minute. Every CDI bean of this type is asked by+ * {@link RedshiftMetricsPublisher}; a collector returns nothing for a cluster it has no real value for.+ */+public interface RedshiftMetricCollector {++ /** {@code timestampSeconds} is the epoch second of the minute that ended; stamp every sample with it. */+ List<MetricDatum> collect(RedshiftMetricTarget target, long timestampSeconds);+}diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricTarget.java b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricTarget.javanew file mode 100644index 0000000000..5f147e56a2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricTarget.java@@ -0,0 +1,6 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.services.redshift.model.Cluster;++/** One cluster to publish metrics for, with the account and region its samples belong to. */+public record RedshiftMetricTarget(String accountId, String region, Cluster cluster, String proxyKey) { }diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsPublisher.java b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsPublisher.javanew file mode 100644index 0000000000..b235ec3235--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsPublisher.java@@ -0,0 +1,85 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.MinuteMetricsPublisher;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import io.github.hectorvent.floci.services.redshift.RedshiftService;+import io.quarkus.runtime.ShutdownEvent;+import io.quarkus.runtime.StartupEvent;+import jakarta.annotation.Priority;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.event.Observes;+import jakarta.enterprise.inject.Instance;+import jakarta.inject.Inject;++import java.time.Instant;+import java.util.ArrayList;+import java.util.List;++/** Supplies available clusters and collector samples to the shared minute publisher. */+@ApplicationScoped+public class RedshiftMetricsPublisher {++ static final String NAMESPACE = "AWS/Redshift";++ private final MinuteMetricsPublisher<RedshiftMetricTarget> publisher;++ @Inject+ public RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,+ Instance<RedshiftMetricCollector> collectors, EmulatorConfig config) {+ this(redshiftService, metricsService, collectors, isEnabled(config));+ }++ RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,+ Iterable<RedshiftMetricCollector> collectors, boolean enabled) {+ this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {+ @Override+ protected List<RedshiftMetricTarget> collectTargets(Instant now) {+ return redshiftService.availableMetricTargets();+ }++ @Override+ protected List<MetricDatum> collectDatums(RedshiftMetricTarget target, long timestampSeconds) {+ List<MetricDatum> datums = new ArrayList<>();+ for (RedshiftMetricCollector collector : collectors) {+ datums.addAll(collector.collect(target, timestampSeconds));+ }+ return datums;+ }++ @Override+ protected String accountId(RedshiftMetricTarget target) {+ return target.accountId();+ }++ @Override+ protected String region(RedshiftMetricTarget target) {+ return target.region();+ }++ @Override+ protected String targetName(RedshiftMetricTarget target) {+ return target.cluster().getClusterIdentifier();+ }+ };+ }++ static boolean isEnabled(EmulatorConfig config) {+ return config.services().redshift().enabled() && config.services().redshift().cloudwatchMetricsEnabled()+ && config.services().cloudwatchmetrics().enabled();+ }++ void onStart(@Observes StartupEvent ignored) {+ publisher.start();+ }++ void onStop(@Observes @Priority(1000) ShutdownEvent ignored) {+ publisher.stop();+ }++ void publish(Instant now) {+ publisher.publish(now);+ }++}diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.javaindex a0c82f824b..7a3b219b53 100644--- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java@@ -52,6 +52,7 @@ public class RedshiftAuthProxy {}private final int handshakeTimeoutMillis;private final int backendConnectTimeoutMillis;+ private final int maxConnections;private final Semaphore connectionPermits;private volatile boolean running;@@ -125,7 +126,13 @@ public class RedshiftAuthProxy {this.roleConfiguration = new RoleConfiguration(iamRoleArns, null);this.handshakeTimeoutMillis = handshakeTimeoutMillis;this.backendConnectTimeoutMillis = backendConnectTimeoutMillis;- this.connectionPermits = new Semaphore(Math.max(1, maxConnections));+ this.maxConnections = Math.max(1, maxConnections);+ this.connectionPermits = new Semaphore(this.maxConnections);+ }++ /** Client connections currently open on this proxy: each holds one permit from accept to close. */+ public int activeConnections() {+ return maxConnections - connectionPermits.availablePermits();}public void start(int proxyPort) throws IOException {diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.javaindex 8de5830628..dd87a2f204 100644--- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java@@ -16,6 +16,7 @@ import org.jboss.logging.Logger;import java.io.IOException;import java.util.List;+import java.util.OptionalInt;import java.util.concurrent.ConcurrentHashMap;/**@@ -151,6 +152,12 @@ public class RedshiftProxyManager {}}+ /** Open client connections of the proxy registered under {@code relayKey}; empty when none runs. */+ public OptionalInt activeConnections(String relayKey) {+ RedshiftAuthProxy proxy = proxies.get(relayKey);+ return proxy == null ? OptionalInt.empty() : OptionalInt.of(proxy.activeConnections());+ }+public synchronized void stopProxy(String relayKey) {// Retry any listener a previous failed start/replace could not close. If it still// cannot be closed this throws, and the entry stays for the next retry.diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisher.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisher.javaindex 644d75d3ee..23a8cd7a76 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisher.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisher.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.sqs;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.MinuteMetricsPublisher;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;import io.quarkus.runtime.ShutdownEvent;@@ -10,110 +11,67 @@ import jakarta.annotation.Priority;import jakarta.enterprise.context.ApplicationScoped;import jakarta.enterprise.event.Observes;import jakarta.inject.Inject;-import org.jboss.logging.Logger;-import java.time.Duration;import java.time.Instant;-import java.time.temporal.ChronoUnit;import java.util.ArrayList;import java.util.List;-import java.util.concurrent.Executors;-import java.util.concurrent.ScheduledExecutorService;-import java.util.concurrent.TimeUnit;/**- * Sends the AWS/SQS metrics of every active queue to CloudWatch once a minute, shaped as SQS sends+ * Supplies the AWS/SQS metrics of every active queue to the minute publisher, shaped as SQS sends* them: one sample of each depth gauge, and for each counter one sample per call in the minute plus* the zero sample AWS adds to every minute. SentMessageSize has one sample per message and no zero- * sample. A tick runs just after each minute boundary and stamps its samples with the minute that- * ended, so a call lands in the minute it was made, as on AWS. Once an hour it drops the AWS/SQS- * datapoints older than the 15 days AWS keeps one-minute data, so the generated history stays bounded.+ * sample.*/@ApplicationScopedpublic class SqsMetricsPublisher {static final String NAMESPACE = "AWS/SQS";- private static final Logger LOG = Logger.getLogger(SqsMetricsPublisher.class);- private static final long MINUTE_MILLIS = 60_000;- private static final long TICK_OFFSET_MILLIS = 1_000;- private static final Duration RETENTION = Duration.ofDays(15);private static final String COUNT = "Count";- private final SqsService sqsService;- private final CloudWatchMetricsService metricsService;- private final boolean enabled;- private final ScheduledExecutorService scheduler;+ private final MinuteMetricsPublisher<SqsService.QueueMetrics> publisher;@Injectpublic SqsMetricsPublisher(SqsService sqsService, CloudWatchMetricsService metricsService, EmulatorConfig config) {- this.sqsService = sqsService;- this.metricsService = metricsService;- this.enabled = config.services().sqs().enabled() && config.services().sqs().cloudwatchMetricsEnabled()+ boolean enabled = config.services().sqs().enabled() && config.services().sqs().cloudwatchMetricsEnabled()&& config.services().cloudwatchmetrics().enabled();- this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {- Thread t = new Thread(r, "sqs-metrics-publisher");- t.setDaemon(true);- return t;- });+ this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {+ @Override+ protected List<SqsService.QueueMetrics> collectTargets(Instant now) {+ return sqsService.collectQueueMetrics(now);+ }++ @Override+ protected List<MetricDatum> collectDatums(SqsService.QueueMetrics target, long timestampSeconds) {+ return datums(target, timestampSeconds);+ }++ @Override+ protected String accountId(SqsService.QueueMetrics target) {+ return target.accountId();+ }++ @Override+ protected String region(SqsService.QueueMetrics target) {+ return target.region();+ }++ @Override+ protected String targetName(SqsService.QueueMetrics target) {+ return target.queueName();+ }+ };}void onStart(@Observes StartupEvent ignored) {- if (!enabled) {- return;- }- long untilNextMinute = MINUTE_MILLIS - System.currentTimeMillis() % MINUTE_MILLIS;- scheduler.scheduleAtFixedRate(() -> publish(Instant.now()), untilNextMinute + TICK_OFFSET_MILLIS,- MINUTE_MILLIS, TimeUnit.MILLISECONDS);+ publisher.start();}- /** Before EmulatorLifecycle's default-priority storage shutdown, letting a running tick finish its writes. */void onStop(@Observes @Priority(1000) ShutdownEvent ignored) {- scheduler.shutdown();- try {- if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {- LOG.warn("The AWS/SQS metrics publisher did not finish its tick within 5 seconds");- }- } catch (InterruptedException e) {- Thread.currentThread().interrupt();- LOG.warnv(e, "Interrupted while stopping the AWS/SQS metrics publisher");- }+ publisher.stop();}- /**- * Nothing may escape: the scheduler stops for good after a tick throws. One queue's failed write- * drops only that queue's samples for the minute.- */void publish(Instant now) {- List<SqsService.QueueMetrics> queues;- try {- queues = sqsService.collectQueueMetrics(now);- } catch (RuntimeException e) {- LOG.warnv(e, "Collecting AWS/SQS queue metrics failed; this minute's samples are dropped");- return;- }- long minute = endedMinute(now);- for (SqsService.QueueMetrics queue : queues) {- try {- metricsService.putMetricDataForAccount(queue.accountId(), NAMESPACE, datums(queue, minute),- queue.region());- } catch (RuntimeException e) {- LOG.warnv(e, "Publishing AWS/SQS metrics for queue {0} of account {1} in {2} failed; its samples "- + "for this minute are dropped", queue.queueName(), queue.accountId(), queue.region());- }- }- if (minute % 3600 == 0) {- try {- metricsService.deleteMetricDataBefore(NAMESPACE, Instant.ofEpochSecond(minute).minus(RETENTION));- } catch (RuntimeException e) {- LOG.warnv(e, "Dropping AWS/SQS datapoints older than {0} failed; the next hour tries again", RETENTION);- }- }- }-- /** The minute a tick's samples belong to. Reading it half a minute back absorbs any drift of the- * fixed-rate schedule away from the minute boundary. */- private static long endedMinute(Instant tick) {- return tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES).getEpochSecond();+ publisher.publish(now);}private static List<MetricDatum> datums(SqsService.QueueMetrics queue, long timestamp) {diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 81eabf961e..9dffd7901a 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -534,6 +534,7 @@ floci:redshift:enabled: trueautomated-snapshots-enabled: true+ cloudwatch-metrics-enabled: truesnapshot-sweep-interval-seconds: 60default-port: 5439image-version: postgres:15-alpinediff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/MinuteMetricsPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/MinuteMetricsPublisherTest.javanew file mode 100644index 0000000000..6ba5421ac9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/MinuteMetricsPublisherTest.java@@ -0,0 +1,99 @@+package io.github.hectorvent.floci.services.cloudwatch.metrics;++import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.time.Clock;+import java.time.Instant;+import java.time.ZoneOffset;+import java.util.List;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++class MinuteMetricsPublisherTest {++ private final CloudWatchMetricsService metrics = mock(CloudWatchMetricsService.class);+ private final ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);+ private final Clock clock = Clock.fixed(Instant.parse("2026-10-27T12:34:20Z"), ZoneOffset.UTC);++ @Test+ void startupAlignsTicksToTheMinuteAndStampsTheEndedMinute() {+ MinuteMetricsPublisher<String> publisher = publisher(true);+ publisher.start();+ ArgumentCaptor<Runnable> tick = ArgumentCaptor.forClass(Runnable.class);+ verify(scheduler).scheduleAtFixedRate(tick.capture(), eq(41_000L), eq(60_000L), eq(TimeUnit.MILLISECONDS));++ tick.getValue().run();+ tick.getValue().run();++ ArgumentCaptor<List<MetricDatum>> datums = ArgumentCaptor.forClass(List.class);+ verify(metrics).putMetricDataForAccount(eq("111111111111"), eq("AWS/Test"), datums.capture(), eq("us-east-1"));+ assertEquals(Instant.parse("2026-10-27T12:33:00Z").getEpochSecond(),+ datums.getValue().getFirst().getTimestamp());+ }++ @Test+ void disabledPublisherDoesNotScheduleTicks() {+ publisher(false).start();++ verifyNoInteractions(scheduler, metrics);+ }++ @Test+ void shutdownWaitsFiveSecondsForAnActiveTick() throws Exception {+ publisher(true).stop();++ verify(scheduler).shutdown();+ verify(scheduler).awaitTermination(5, TimeUnit.SECONDS);+ }++ @Test+ void shutdownRestoresTheInterruptFlag() throws Exception {+ when(scheduler.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(new InterruptedException("stopping"));+ try {+ publisher(true).stop();++ assertTrue(Thread.currentThread().isInterrupted());+ } finally {+ Thread.interrupted();+ }+ }++ private MinuteMetricsPublisher<String> publisher(boolean enabled) {+ return new MinuteMetricsPublisher<>(metrics, "AWS/Test", enabled, clock, scheduler) {+ @Override+ protected List<String> collectTargets(Instant now) {+ return List.of("target");+ }++ @Override+ protected List<MetricDatum> collectDatums(String target, long timestampSeconds) {+ return List.of(MetricDatum.of("Value", "Count", 1, List.of(), timestampSeconds));+ }++ @Override+ protected String accountId(String target) {+ return "111111111111";+ }++ @Override+ protected String region(String target) {+ return "us-east-1";+ }++ @Override+ protected String targetName(String target) {+ return target;+ }+ };+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.javaindex c563ea27aa..6a561528fd 100644--- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReaderimport io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;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.metrics.RedshiftMetricTarget;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;@@ -63,6 +64,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertSame;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.*;@@ -2398,6 +2400,39 @@ class RedshiftServiceTest {assertEquals("0", reloaded.getParameters().getFirst().getParameterValue());}+ @Test+ void availableMetricTargetsListsOnlyAvailableClustersOfEveryAccountWithTheirRegion() {+ Cluster available = new Cluster();+ available.setClusterIdentifier("warehouse");+ available.setClusterStatus("available");+ available.setSnapshotRegion("eu-west-1");+ Cluster otherAccount = new Cluster();+ otherAccount.setClusterIdentifier("warehouse");+ otherAccount.setClusterStatus("available");+ Cluster creating = new Cluster();+ creating.setClusterIdentifier("new");+ creating.setClusterStatus("creating");+ Cluster deleting = new Cluster();+ deleting.setClusterIdentifier("old");+ deleting.setClusterStatus("deleting");+ when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(+ new AccountAwareStorageBackend.AccountEntry<>("111111111111", "warehouse", available),+ new AccountAwareStorageBackend.AccountEntry<>("222222222222", "warehouse", otherAccount),+ new AccountAwareStorageBackend.AccountEntry<>("111111111111", "new", creating),+ new AccountAwareStorageBackend.AccountEntry<>("111111111111", "old", deleting)));++ List<RedshiftMetricTarget> targets = service.availableMetricTargets();++ assertEquals(2, targets.size());+ assertEquals("111111111111", targets.get(0).accountId());+ assertEquals("eu-west-1", targets.get(0).region());+ assertEquals("111111111111:warehouse", targets.get(0).proxyKey());+ assertSame(available, targets.get(0).cluster());+ assertEquals("222222222222", targets.get(1).accountId());+ assertEquals("222222222222:warehouse", targets.get(1).proxyKey());+ assertSame(otherAccount, targets.get(1).cluster());+ }+@Testvoid createAndListTagsForCluster() {Cluster cluster = new Cluster();diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftClusterStateMetricCollectorTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftClusterStateMetricCollectorTest.javanew file mode 100644index 0000000000..ff1d1df062--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftClusterStateMetricCollectorTest.java@@ -0,0 +1,76 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import io.github.hectorvent.floci.services.redshift.model.Cluster;+import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.util.List;+import java.util.Map;+import java.util.OptionalInt;+import java.util.function.Function;+import java.util.stream.Collectors;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++class RedshiftClusterStateMetricCollectorTest {++ private static final String KEY = "proxy-key-supplied-by-redshift-service";+ private static final long TIMESTAMP = 1_793_102_340L;++ private final RedshiftProxyManager proxies = mock(RedshiftProxyManager.class);+ private final RedshiftClusterStateMetricCollector collector = new RedshiftClusterStateMetricCollector(proxies);++ private static RedshiftMetricTarget target(String status) {+ Cluster cluster = new Cluster();+ cluster.setClusterIdentifier("warehouse");+ cluster.setClusterStatus(status);+ return new RedshiftMetricTarget("111111111111", "us-east-1", cluster, KEY);+ }++ private static Map<String, MetricDatum> byName(List<MetricDatum> datums) {+ return datums.stream().collect(Collectors.toMap(MetricDatum::getMetricName, Function.identity()));+ }++ @Test+ void availableClusterReportsHealthMaintenanceAndConnections() {+ when(proxies.activeConnections(KEY)).thenReturn(OptionalInt.of(3));++ Map<String, MetricDatum> datums = byName(collector.collect(target("available"), TIMESTAMP));++ assertEquals(3, datums.size());+ assertEquals(1.0, datums.get("HealthStatus").getValue());+ assertEquals(0.0, datums.get("MaintenanceMode").getValue());+ assertEquals(3.0, datums.get("DatabaseConnections").getValue());+ for (MetricDatum datum : datums.values()) {+ assertEquals("Count", datum.getUnit());+ assertEquals(TIMESTAMP, datum.getTimestamp());+ assertEquals(List.of(new Dimension("ClusterIdentifier", "warehouse")), datum.getDimensions());+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"creating", "deleting", "failed", "unavailable"})+ void clusterNotAvailableReportsNothing(String status) {+ when(proxies.activeConnections(KEY)).thenReturn(OptionalInt.of(3));++ assertTrue(collector.collect(target(status), TIMESTAMP).isEmpty());+ }++ @Test+ void missingProxyOmitsDatabaseConnections() {+ when(proxies.activeConnections(KEY)).thenReturn(OptionalInt.empty());++ Map<String, MetricDatum> datums = byName(collector.collect(target("available"), TIMESTAMP));++ assertEquals(2, datums.size());+ assertTrue(datums.containsKey("HealthStatus"));+ assertTrue(datums.containsKey("MaintenanceMode"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsIntegrationTest.javanew file mode 100644index 0000000000..09c5dd5da3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsIntegrationTest.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService.Datapoint;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService.MetricIdentity;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;+import io.github.hectorvent.floci.services.redshift.RedshiftService;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.enterprise.inject.Instance;+import jakarta.inject.Inject;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.List;+import java.util.Set;+import java.util.stream.Collectors;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class RedshiftMetricsIntegrationTest {++ private static final String REGION = "us-east-1";+ private static final String NAMESPACE = "AWS/Redshift";++ @Inject+ RedshiftService redshift;++ @Inject+ Instance<RedshiftMetricCollector> collectors;++ @Inject+ CloudWatchMetricsService cloudWatch;++ private RedshiftMetricsPublisher publisher;+ private String clusterId;++ @BeforeEach+ void setUp() {+ publisher = new RedshiftMetricsPublisher(redshift, cloudWatch, collectors, true);+ }++ @AfterEach+ void cleanUp() {+ publisher.onStop(null);+ if (clusterId != null) {+ redshift.deleteCluster(clusterId);+ clusterId = null;+ }+ }++ /** The minute a tick stamps its samples with, read back alone so the scheduler's own ticks cannot interfere. */+ private List<Datapoint> statisticsAt(String metricName, String identifier, Instant tick) {+ Instant minute = tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES);+ return cloudWatch.getMetricStatistics(NAMESPACE, metricName,+ List.of(new Dimension("ClusterIdentifier", identifier)), minute, minute.plusSeconds(59), 60,+ List.of("Sum"), null, REGION);+ }++ @Test+ void createdClusterPublishesItsStateMetricsReadableThroughCloudWatch() {+ clusterId = "it-metrics-state";+ redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");+ Instant tick = Instant.now().plusSeconds(100);++ publisher.publish(tick);++ Set<String> names = cloudWatch.listMetrics(NAMESPACE, null,+ List.of(new Dimension("ClusterIdentifier", clusterId)), REGION).stream()+ .map(MetricIdentity::metricName).collect(Collectors.toSet());+ assertEquals(Set.of("HealthStatus", "MaintenanceMode", "DatabaseConnections"), names);++ List<Datapoint> health = statisticsAt("HealthStatus", clusterId, tick);+ assertEquals(1, health.size());+ assertEquals(1.0, health.getFirst().sum());+ assertEquals("Count", health.getFirst().unit());+ assertEquals(0.0, statisticsAt("DatabaseConnections", clusterId, tick).getFirst().sum());+ }++ @Test+ void deletedClusterStopsPublishing() {+ clusterId = "it-metrics-deleted";+ redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");+ Instant whileAvailable = Instant.now().plusSeconds(100);+ publisher.publish(whileAvailable);+ assertEquals(1, statisticsAt("HealthStatus", clusterId, whileAvailable).size());++ redshift.deleteCluster(clusterId);+ String deleted = clusterId;+ clusterId = null;+ Instant afterDelete = whileAvailable.plusSeconds(600);+ publisher.publish(afterDelete);++ assertTrue(statisticsAt("HealthStatus", deleted, afterDelete).isEmpty(),+ "a deleted cluster must publish no samples");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsPublisherTest.javanew file mode 100644index 0000000000..bbfdb59319--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/metrics/RedshiftMetricsPublisherTest.java@@ -0,0 +1,225 @@+package io.github.hectorvent.floci.services.redshift.metrics;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import io.github.hectorvent.floci.services.redshift.RedshiftService;+import io.github.hectorvent.floci.services.redshift.model.Cluster;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.Answers;+import org.mockito.ArgumentCaptor;++import java.time.Duration;+import java.time.Instant;+import java.util.ArrayList;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+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.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+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.when;++class RedshiftMetricsPublisherTest {++ private static final String REGION = "eu-west-1";+ private static final String NAMESPACE = "AWS/Redshift";++ private RedshiftService redshift;+ private CloudWatchMetricsService cloudWatch;++ @BeforeEach+ void setUp() {+ redshift = mock(RedshiftService.class);+ cloudWatch = mock(CloudWatchMetricsService.class);+ }++ private static RedshiftMetricTarget target(String accountId, String identifier) {+ Cluster cluster = new Cluster();+ cluster.setClusterIdentifier(identifier);+ cluster.setClusterStatus("available");+ return new RedshiftMetricTarget(accountId, REGION, cluster, "proxy-for-" + identifier);+ }++ private static MetricDatum sample(String identifier, long timestamp) {+ return MetricDatum.of("HealthStatus", "Count", 1, List.of(new Dimension("ClusterIdentifier", identifier)),+ timestamp);+ }++ private RedshiftMetricsPublisher publisher(RedshiftMetricCollector... collectors) {+ return new RedshiftMetricsPublisher(redshift, cloudWatch, List.of(collectors), true);+ }++ @Test+ void publishWritesCollectorSamplesStampedWithTheEndedMinute() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));+ List<Long> stamps = new ArrayList<>();+ RedshiftMetricCollector collector = (target, timestamp) -> {+ stamps.add(timestamp);+ return List.of(sample(target.cluster().getClusterIdentifier(), timestamp));+ };++ publisher(collector).publish(Instant.parse("2026-10-27T12:00:20Z"));++ long endedMinute = Instant.parse("2026-10-27T11:59:00Z").getEpochSecond();+ assertEquals(List.of(endedMinute), stamps);+ ArgumentCaptor<List<MetricDatum>> written = ArgumentCaptor.forClass(List.class);+ verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), written.capture(), eq(REGION));+ assertEquals(1, written.getValue().size());+ assertEquals("HealthStatus", written.getValue().getFirst().getMetricName());+ assertEquals(endedMinute, written.getValue().getFirst().getTimestamp());+ }++ @Test+ void overdueTicksPublishEachMinuteOnlyOnce() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));+ RedshiftMetricsPublisher publisher = publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)));++ publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));+ publisher.publish(Instant.parse("2026-10-27T12:04:02Z"));+ publisher.publish(Instant.parse("2026-10-27T12:04:20Z"));+ publisher.publish(Instant.parse("2026-10-27T12:05:01Z"));++ ArgumentCaptor<List<MetricDatum>> written = ArgumentCaptor.forClass(List.class);+ verify(cloudWatch, times(2)).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE),+ written.capture(), eq(REGION));+ assertEquals(List.of(Instant.parse("2026-10-27T12:03:00Z").getEpochSecond(),+ Instant.parse("2026-10-27T12:04:00Z").getEpochSecond()),+ written.getAllValues().stream().map(datums -> datums.getFirst().getTimestamp()).toList());+ verify(redshift, times(2)).availableMetricTargets();+ }++ @Test+ void clockMovingBackwardsDoesNotRepublishAnEarlierMinute() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));+ RedshiftMetricsPublisher publisher = publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)));++ publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));+ publisher.publish(Instant.parse("2026-10-27T12:03:01Z"));+ publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));++ verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), anyList(), eq(REGION));+ }++ @Test+ void aFailedWriteIsNotRetriedWithinTheMinute() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));+ doThrow(new IllegalStateException("write may have stored some samples")).when(cloudWatch)+ .putMetricDataForAccount(anyString(), anyString(), anyList(), anyString());+ RedshiftMetricsPublisher publisher = publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)));++ publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));+ publisher.publish(Instant.parse("2026-10-27T12:04:02Z"));++ verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), anyList(), eq(REGION));+ }++ @Test+ void aThrowingCollectorDropsOnlyThatClustersSamples() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(+ target("111111111111", "broken"), target("111111111111", "healthy")));+ RedshiftMetricCollector collector = (target, timestamp) -> {+ if ("broken".equals(target.cluster().getClusterIdentifier())) {+ throw new IllegalStateException("collector failed");+ }+ return List.of(sample(target.cluster().getClusterIdentifier(), timestamp));+ };++ assertDoesNotThrow(() -> publisher(collector).publish(Instant.parse("2026-10-27T12:00:20Z")));++ ArgumentCaptor<List<MetricDatum>> written = ArgumentCaptor.forClass(List.class);+ verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), written.capture(), eq(REGION));+ assertEquals("healthy", written.getValue().getFirst().getDimensions().getFirst().value());+ }++ @Test+ void aFailedWriteForOneClusterDoesNotStopTheNext() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(+ target("111111111111", "first"), target("222222222222", "second")));+ doThrow(new IllegalStateException("store failed")).when(cloudWatch)+ .putMetricDataForAccount(eq("111111111111"), anyString(), anyList(), anyString());++ assertDoesNotThrow(() -> publisher((target, timestamp) -> List.of(sample("x", timestamp)))+ .publish(Instant.parse("2026-10-27T12:00:20Z")));++ verify(cloudWatch).putMetricDataForAccount(eq("222222222222"), eq(NAMESPACE), anyList(), eq(REGION));+ }++ @Test+ void sameClusterIdentifierInTwoAccountsLandsInEachAccount() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(+ target("111111111111", "warehouse"), target("222222222222", "warehouse")));++ publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)))+ .publish(Instant.parse("2026-10-27T12:00:20Z"));++ verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), anyList(), eq(REGION));+ verify(cloudWatch).putMetricDataForAccount(eq("222222222222"), eq(NAMESPACE), anyList(), eq(REGION));+ }++ @Test+ void aClusterWithNoSamplesWritesNothing() {+ when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));++ publisher((target, timestamp) -> List.of()).publish(Instant.parse("2026-10-27T12:00:20Z"));++ verify(cloudWatch, never()).putMetricDataForAccount(anyString(), anyString(), anyList(), anyString());+ }++ @Test+ void enumerationFailureDropsTheTickWithoutThrowing() {+ when(redshift.availableMetricTargets()).thenThrow(new IllegalStateException("storage unavailable"));++ assertDoesNotThrow(() -> publisher((target, timestamp) -> List.of(sample("x", timestamp)))+ .publish(Instant.parse("2026-10-27T12:00:20Z")));++ verify(cloudWatch, never()).putMetricDataForAccount(anyString(), anyString(), anyList(), anyString());+ }++ @Test+ void publishDropsDatapointsOlderThanFifteenDaysOnTheHour() {+ when(redshift.availableMetricTargets()).thenReturn(List.of());+ RedshiftMetricsPublisher publisher = publisher();++ publisher.publish(Instant.parse("2026-10-27T12:01:00Z"));++ Instant hour = Instant.parse("2026-10-27T12:00:00Z");+ verify(cloudWatch).deleteMetricDataBefore(NAMESPACE, hour.minus(Duration.ofDays(15)));+ }++ @Test+ void publishKeepsHistoryBetweenHours() {+ when(redshift.availableMetricTargets()).thenReturn(List.of());++ publisher().publish(Instant.parse("2026-10-27T12:30:20Z"));++ verify(cloudWatch, never()).deleteMetricDataBefore(anyString(), any());+ }++ @Test+ void isDisabledWhenTheFlagOrCloudwatchMetricsIsOff() {+ assertTrue(RedshiftMetricsPublisher.isEnabled(config(true, true, true)));+ assertFalse(RedshiftMetricsPublisher.isEnabled(config(true, false, true)));+ assertFalse(RedshiftMetricsPublisher.isEnabled(config(true, true, false)));+ assertFalse(RedshiftMetricsPublisher.isEnabled(config(false, true, true)));+ }++ private static EmulatorConfig config(boolean redshiftEnabled, boolean flag, boolean cloudwatchEnabled) {+ EmulatorConfig config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);+ when(config.services().redshift().enabled()).thenReturn(redshiftEnabled);+ when(config.services().redshift().cloudwatchMetricsEnabled()).thenReturn(flag);+ when(config.services().cloudwatchmetrics().enabled()).thenReturn(cloudwatchEnabled);+ return config;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.javaindex 8d7c669528..9c15d55bb0 100644--- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java@@ -235,6 +235,33 @@ class RedshiftAuthProxyTest {}}+ @Test+ void activeConnectionsCountsOpenClientsAndFallsOnClose() throws Exception {+ fakeBackend = new ServerSocket(0);+ int proxyPort = FreePorts.anyInterfacePort();+ proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),+ "admin", "Secret123", "dev",+ mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,+ mock(S3Service.class), mock(IamService.class), 5000, 5000, 5);+ proxy.start(proxyPort);+ assertEquals(0, proxy.activeConnections());++ try (Socket first = new Socket("localhost", proxyPort); Socket second = new Socket("localhost", proxyPort)) {+ awaitActiveConnections(2);+ first.close();+ awaitActiveConnections(1);+ }+ awaitActiveConnections(0);+ }++ private void awaitActiveConnections(int expected) throws InterruptedException {+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);+ while (proxy.activeConnections() != expected && System.nanoTime() < deadline) {+ Thread.sleep(25);+ }+ assertEquals(expected, proxy.activeConnections());+ }+@Testvoid startRetriesTheBindWhileThePortIsMomentarilyStillInUse() throws Exception {fakeBackend = new ServerSocket(0);diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.javaindex a9a76020fd..915261343a 100644--- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java@@ -14,6 +14,7 @@ import java.lang.reflect.Field;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.util.List;+import java.util.OptionalInt;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.Semaphore;@@ -88,6 +89,19 @@ class RedshiftProxyManagerTest {}}+ @Test+ void activeConnectionsIsEmptyWithoutAProxyAndZeroForAnIdleOne() throws Exception {+ RedshiftProxyManager manager = newManager();+ int port = FreePorts.anyInterfacePort();+ try {+ assertEquals(OptionalInt.empty(), manager.activeConnections(KEY));+ start(manager, KEY, port);+ assertEquals(OptionalInt.of(0), manager.activeConnections(KEY));+ } finally {+ manager.stopAll();+ }+ }+@Testvoid stopProxyRemovesTheKeyAndReleasesThePort() throws Exception {RedshiftProxyManager manager = newManager();diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisherTest.javaindex 8187a646d3..9bc9dccec1 100644--- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisherTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsMetricsPublisherTest.java@@ -39,6 +39,52 @@ class SqsMetricsPublisherTest {private CloudWatchMetricsService cloudWatch;private SqsMetricsPublisher publisher;+ @Test+ void overdueTicksDoNotDuplicateSamplesOrDrainTheNextMinutesActivity() {+ String url = sqs.createQueue("overdue", null, REGION).getQueueUrl();+ sqs.sendMessage(url, "first", null, REGION);+ Instant tick = Instant.now().truncatedTo(ChronoUnit.MINUTES).plusSeconds(1);+ publisher.publish(tick);+ sqs.sendMessage(url, "next", null, REGION);++ publisher.publish(tick.plusSeconds(1));+ publisher.publish(tick.plusSeconds(60));++ assertSamples(datapoint("overdue", "NumberOfMessagesSent", tick), 2, 1, 0, 1, "Count");+ assertSamples(datapoint("overdue", "NumberOfMessagesSent", tick.plusSeconds(60)), 2, 1, 0, 1, "Count");+ }++ @Test+ void clockRollbackDoesNotRepublishAnEarlierMinute() {+ sqs.createQueue("rollback", null, REGION);+ Instant tick = Instant.now().truncatedTo(ChronoUnit.MINUTES).plusSeconds(1);+ publisher.publish(tick);++ publisher.publish(tick.minusSeconds(60));+ publisher.publish(tick);++ assertSamples(datapoint("rollback", "NumberOfMessagesSent", tick), 1, 0, 0, 0, "Count");+ assertNull(datapoint("rollback", "NumberOfMessagesSent", tick.minusSeconds(60)));+ }++ @Test+ void aPartiallyFailedWriteIsNotRetriedWithinTheMinute() {+ sqs.createQueue("partial", null, REGION);+ CloudWatchMetricsService failing = spy(cloudWatch);+ doAnswer(invocation -> {+ invocation.callRealMethod();+ throw new IllegalStateException("failed after writing samples");+ }).when(failing).putMetricDataForAccount(any(), any(), any(), any());+ SqsMetricsPublisher partial = new SqsMetricsPublisher(sqs, failing,+ mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS));+ Instant tick = Instant.now().truncatedTo(ChronoUnit.MINUTES).plusSeconds(1);++ partial.publish(tick);+ partial.publish(tick.plusSeconds(1));++ assertSamples(datapoint("partial", "NumberOfMessagesSent", tick), 1, 0, 0, 0, "Count");+ }+@BeforeEachvoid setUp() {RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 7d0c2ec815..2e56a97e07 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -212,6 +212,7 @@ floci:redshift:enabled: trueautomated-snapshots-enabled: false+ cloudwatch-metrics-enabled: truesnapshot-sweep-interval-seconds: 60default-port: 5439image-version: postgres:15-alpine