fix(cloudwatch): bound the datapoints Floci publishes itself (#9348)

The CloudWatch metric store has no size bound, and since SQS publishes AWS/SQS
metrics for every active queue each minute it grows with no PutMetricData call,
until a persisted cwmetrics.json no longer fits the heap on load.

floci.services.cloudwatchmetrics.max-stored-datapoints (default 100000) now caps
the datapoints kept per account in each namespace a MinuteMetricsPublisher
writes (AWS/SQS, AWS/Redshift). After each tick the publisher drops the oldest
over the ceiling, down to nine tenths of it, through the metric key index;
other namespaces are never cut, and 0 or less turns the ceiling off.
This commit is contained in:
Tal Efraim authored and GitHub committed 2026-11-24 11:20:34 -04:00
1 parent cb573492ca
commit c40b11fe9a
16 files changed
+328 -17

No files matched your search

@@ -266,6 +266,7 @@ floci:
cloudwatchmetrics:
enabled: true
max-stored-datapoints: 100000 # per account, in each namespace Floci publishes itself (AWS/SQS, AWS/Redshift); oldest dropped first, 0 keeps all
secretsmanager:
enabled: true
@@ -418,6 +418,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_CLOUDWATCHMETRICS_ENABLED` | `true` | Enable the CloudWatch Metrics service |
| `FLOCI_SERVICES_CLOUDWATCHMETRICS_MAX_STORED_DATAPOINTS` | `100000` | Maximum datapoints retained per account in each namespace Floci publishes itself (`AWS/SQS`, `AWS/Redshift`); oldest datapoints are dropped first, and `0` keeps them all. Datapoints in other namespaces are not affected |
### Secrets Manager
+18
View File
@@ -566,6 +566,24 @@ Composite alarms support boolean rules over alarm states. Request `AlarmTypes` c
action lists are stored but not executed. Action suppression is not implemented and is
rejected with `ValidationError`.
### Metric storage {#metric-storage}
Every datapoint is one entry in the metric store, which is held in memory and written out as a
whole: about 500 bytes of JSON each in `cwmetrics.json`. Services that publish their own metrics
fill it without a `PutMetricData` call: an active SQS queue adds 8 to 11 datapoints a minute.
Floci therefore keeps at most 100,000 datapoints per account in each namespace it publishes
itself, `AWS/SQS` and `AWS/Redshift` (`FLOCI_SERVICES_CLOUDWATCHMETRICS_MAX_STORED_DATAPOINTS`).
Once a minute, an account holding more than that in one of those namespaces loses its oldest
datapoints there, by datapoint timestamp and whichever metrics they belong to, until nine tenths
of the ceiling are left. A store loaded from disk above the ceiling is cut back the same way a
minute after startup. With the default, 50 active queues keep about four hours of history; raise
the ceiling to keep more, up to the 15 days those datapoints are kept for, or set it to `0` to
keep them all.
Datapoints in any other namespace are never dropped for the ceiling, so what a client writes with
`PutMetricData` under its own namespace stays.
### Metric alarm updates
Updating a metric alarm preserves its current state, state reason, state timestamps and tags.
+1 -1
View File
@@ -137,7 +137,7 @@ Floci publishes the `AWS/SQS` metrics of every active queue to CloudWatch once a
These match what AWS publishes. A deduplicated FIFO send still counts in `NumberOfMessagesSent`, and a message a redrive policy moves to a dead-letter queue does not. `ApproximateAgeOfOldestMessage` counts a message moved to a FIFO dead-letter queue or by `StartMessageMoveTask` from the move.
Known differences: a `SendMessageBatch` or `DeleteMessageBatch` call adds one sample per entry where AWS adds one per call, so `Sum` matches while `SampleCount`, `Average`, `Minimum` and `Maximum` can differ. A message in a standard dead-letter queue keeps its original send time for its age, where AWS counts from the move, and a standard-queue message received three times or more still counts toward the age, where AWS leaves it out until it is deleted. Floci keeps these datapoints for the 15 days AWS keeps one-minute data and then drops them, where AWS goes on serving them at 5 minute and 1 hour resolution. The fair-queue metrics (`ApproximateNumberOfNoisyGroups` and the `InQuietGroups` variants) are not published, and the delay of up to 15 minutes AWS has before a newly active queue reports is not reproduced.
Known differences: a `SendMessageBatch` or `DeleteMessageBatch` call adds one sample per entry where AWS adds one per call, so `Sum` matches while `SampleCount`, `Average`, `Minimum` and `Maximum` can differ. A message in a standard dead-letter queue keeps its original send time for its age, where AWS counts from the move, and a standard-queue message received three times or more still counts toward the age, where AWS leaves it out until it is deleted. Floci keeps these datapoints for the 15 days AWS keeps one-minute data and then drops them, where AWS goes on serving them at 5 minute and 1 hour resolution, and drops the oldest sooner once an account holds more `AWS/SQS` datapoints than the [metric store ceiling](cloudwatch.md#metric-storage). The fair-queue metrics (`ApproximateNumberOfNoisyGroups` and the `InQuietGroups` variants) are not published, and the delay of up to 15 minutes AWS has before a newly active queue reports is not reproduced.
## Configuration
@@ -2554,6 +2554,17 @@ public interface EmulatorConfig {
interface CloudWatchMetricsServiceConfig {
@WithDefault("true")
boolean enabled();
/**
* Upper bound on the datapoints kept per account in each namespace a service publishes by
* itself, such as AWS/SQS. Every datapoint is its own entry in a store that is held in memory
* and written out whole, and those services add some for each resource every minute, so
* without a bound the store outgrows the heap long before the 15 days AWS keeps one-minute
* data. Oldest datapoints are dropped first once exceeded; 0 or less keeps them all. Other
* namespaces, where only a client's PutMetricData writes, are never cut back.
*/
@WithDefault("100000")
int maxStoredDatapoints();
}
interface PaymentCryptographyServiceConfig {
@@ -254,6 +254,32 @@ public class CloudWatchMetricsService implements Resettable {
deleteInEveryAccount(metricStore, d -> namespace.equals(d.getNamespace()) && d.getTimestamp() < cutoffSeconds);
}
/**
* Drops the oldest {@code namespace} datapoints of every account holding more than {@code ceiling} of
* them, down to nine tenths of it so that the next calls find nothing to sort. A service that writes
* its own metrics each minute calls it: that history grows without a request, and would outgrow the
* heap well inside the 15 days it is kept for. Counting reads the key index, so nothing is dropped
* before storage has loaded.
*/
public void deleteOldestMetricData(String namespace, int ceiling) {
if (!metricKeys.isBuilt()) {
return;
}
// Index first, as in deleteMetricDataBefore.
Map<String, Set<String>> oldestByAccount = metricKeys.removeOldest(namespace, ceiling, ceiling - ceiling / 10);
if (oldestByAccount.isEmpty()) {
return;
}
if (metricStore instanceof AccountAwareStorageBackend<MetricDatum> aware) {
aware.deleteAllAtomicallyForAccounts(oldestByAccount);
} else {
oldestByAccount.values().forEach(metricStore::deleteAllAtomically);
}
oldestByAccount.forEach((account, oldest) -> LOG.debugv(
"Dropped the {0} oldest {1} datapoint(s) of account {2} to stay within the ceiling of {3}",
oldest.size(), namespace, account, ceiling));
}
private static <V> void deleteInEveryAccount(StorageBackend<String, V> store, Predicate<V> expired) {
if (store instanceof AccountAwareStorageBackend<V> aware) {
aware.deleteAllAccountsMatching(expired);
@@ -1,9 +1,13 @@
package io.floci.aws.services.cloudwatch.metrics;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
@@ -56,13 +60,56 @@ final class MetricKeyIndex {
String cutoff = timestampSegment(cutoffSeconds);
for (Map<String, NavigableSet<String>> endingsBySeries : endingsBySeriesByAccount.values()) {
endingsBySeries.forEach((series, endings) -> {
if (series.startsWith(namespaceSegment, series.indexOf("::"))) {
if (isInNamespace(series, namespaceSegment)) {
endings.headSet(cutoff).clear();
}
});
}
}
/**
* In every account holding more than {@code ceiling} keys of {@code namespace}, removes the oldest of
* them across its series until {@code keep} are left. Returns the removed keys by account.
*/
Map<String, Set<String>> removeOldest(String namespace, int ceiling, int keep) {
String namespaceSegment = "::" + namespace + "::";
Map<String, Set<String>> removedByAccount = new HashMap<>();
endingsBySeriesByAccount.forEach((account, endingsBySeries) -> {
List<String> namespaceSeries = new ArrayList<>();
long held = 0;
for (Map.Entry<String, NavigableSet<String>> endings : endingsBySeries.entrySet()) {
if (isInNamespace(endings.getKey(), namespaceSegment)) {
namespaceSeries.add(endings.getKey());
held += endings.getValue().size();
}
}
if (held <= ceiling) {
return;
}
List<SeriesEnding> oldestFirst = new ArrayList<>();
for (String series : namespaceSeries) {
for (String ending : endingsBySeries.get(series)) {
oldestFirst.add(new SeriesEnding(series, ending));
}
}
oldestFirst.sort(Comparator.comparing(SeriesEnding::ending).thenComparing(SeriesEnding::series));
Set<String> removed = new HashSet<>();
for (SeriesEnding oldest : oldestFirst.subList(0, Math.max(0, oldestFirst.size() - keep))) {
endingsBySeries.get(oldest.series()).remove(oldest.ending());
removed.add(oldest.series() + oldest.ending());
}
removedByAccount.put(account, removed);
});
return removedByAccount;
}
private static boolean isInNamespace(String series, String namespaceSegment) {
return series.startsWith(namespaceSegment, series.indexOf("::"));
}
/** One key split as the index holds it; an ending starts with its timestamp, so endings sort by time. */
private record SeriesEnding(String series, String ending) {}
/** The account's keys of {@code series} stamped in {@code [fromSeconds, toSeconds)}, oldest first. */
List<String> keysBetween(String account, String series, long fromSeconds, long toSeconds) {
Map<String, NavigableSet<String>> endingsBySeries = endingsBySeriesByAccount.get(account);
@@ -16,7 +16,8 @@ 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.
* than the 15 days AWS keeps one-minute data, and every minute the oldest of an account's beyond the
* ceiling it was given, so the generated history stays bounded. A ceiling of 0 or less keeps them all.
*/
public abstract class MinuteMetricsPublisher<T> {
@@ -28,23 +29,27 @@ public abstract class MinuteMetricsPublisher<T> {
private final CloudWatchMetricsService metricsService;
private final String namespace;
private final boolean enabled;
private final int maxStoredDatapoints;
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,
int maxStoredDatapoints) {
this(metricsService, namespace, enabled, maxStoredDatapoints, 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) {
int maxStoredDatapoints, Clock clock, ScheduledExecutorService scheduler) {
this.metricsService = metricsService;
this.namespace = namespace;
this.enabled = enabled;
this.maxStoredDatapoints = maxStoredDatapoints;
this.clock = clock;
this.scheduler = scheduler;
}
@@ -108,6 +113,14 @@ public abstract class MinuteMetricsPublisher<T> {
namespace, RETENTION);
}
}
if (maxStoredDatapoints > 0) {
try {
metricsService.deleteOldestMetricData(namespace, maxStoredDatapoints);
} catch (RuntimeException e) {
LOG.warnv(e, "Dropping the oldest {0} datapoints over the ceiling of {1} failed; the next minute"
+ " tries again", namespace, maxStoredDatapoints);
}
}
}
/** Reading half a minute back absorbs drift of the fixed-rate schedule away from the boundary. */
@@ -28,12 +28,14 @@ public class RedshiftMetricsPublisher {
@Inject
public RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,
Instance<RedshiftMetricCollector> collectors, EmulatorConfig config) {
this(redshiftService, metricsService, collectors, isEnabled(config));
this(redshiftService, metricsService, collectors, isEnabled(config),
config.services().cloudwatchmetrics().maxStoredDatapoints());
}
RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,
Iterable<RedshiftMetricCollector> collectors, boolean enabled) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {
Iterable<RedshiftMetricCollector> collectors, boolean enabled,
int maxStoredDatapoints) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled, maxStoredDatapoints) {
@Override
protected List<RedshiftMetricTarget> collectTargets(Instant now) {
return redshiftService.availableMetricTargets();
@@ -34,7 +34,8 @@ public class SqsMetricsPublisher {
public SqsMetricsPublisher(SqsService sqsService, CloudWatchMetricsService metricsService, EmulatorConfig config) {
boolean enabled = config.services().sqs().enabled() && config.services().sqs().cloudwatchMetricsEnabled()
&& config.services().cloudwatchmetrics().enabled();
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled,
config.services().cloudwatchmetrics().maxStoredDatapoints()) {
@Override
protected List<SqsService.QueueMetrics> collectTargets(Instant now) {
return sqsService.collectQueueMetrics(now);
+1
View File
@@ -741,6 +741,7 @@ floci:
max-stored-events: 20000
cloudwatchmetrics:
enabled: true
max-stored-datapoints: 100000
paymentcryptography:
enabled: true
secretsmanager:
@@ -458,6 +458,100 @@ class CloudWatchMetricsServiceTest {
60, List.of("Sum"), null, REGION).stream().map(CloudWatchMetricsService.Datapoint::sum).toList());
}
@Test
void deleteOldestMetricData_cutsOnlyThatNamespaceBackToNineTenthsOfTheCeiling() {
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 6000;
putOnePerMinute(service, null, "AWS/SQS", minute, 12);
putOnePerMinute(service, null, NAMESPACE, minute, 12);
service.deleteOldestMetricData("AWS/SQS", 10);
assertEquals(minutesFrom(minute, 3, 12), storedMinutes("AWS/SQS", minute));
assertEquals(minutesFrom(minute, 0, 12), storedMinutes(NAMESPACE, minute));
}
@Test
void deleteOldestMetricData_leavesANamespaceThatHoldsExactlyTheCeiling() {
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 6000;
putOnePerMinute(service, null, "AWS/SQS", minute, 10);
service.deleteOldestMetricData("AWS/SQS", 10);
assertEquals(minutesFrom(minute, 0, 10), storedMinutes("AWS/SQS", minute));
}
@Test
void deleteOldestMetricData_countsEachAccountOnItsOwn() {
AccountAwareStorageBackend<MetricDatum> store = AccountAwareStorageBackend.inMemory("000000000000");
CloudWatchMetricsService accountAware = new CloudWatchMetricsService(store, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"));
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 6000;
putOnePerMinute(accountAware, "111111111111", "AWS/SQS", minute, 12);
putOnePerMinute(accountAware, null, "AWS/SQS", minute, 8);
accountAware.deleteOldestMetricData("AWS/SQS", 10);
assertEquals(9, store.scanForAccount("111111111111", k -> true).size());
assertEquals(8, store.scan(k -> true).size());
}
@Test
void deleteOldestMetricData_cutsBackAStoreThatWasLoadedPastTheCeiling() {
AccountAwareStorageBackend<MetricDatum> store = AccountAwareStorageBackend.inMemory("000000000000");
RegionResolver resolver = new RegionResolver("us-east-1", "000000000000");
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 6000;
putOnePerMinute(new CloudWatchMetricsService(store, new InMemoryStorage<>(), resolver), null, "AWS/SQS",
minute, 30);
CloudWatchMetricsService restarted = new CloudWatchMetricsService(store, new InMemoryStorage<>(), resolver);
restarted.deleteOldestMetricData("AWS/SQS", 10);
assertEquals(9, store.scan(k -> true).size());
}
@Test
void deleteOldestMetricData_waitsForTheKeyIndex() {
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 6000;
putOnePerMinute(service, null, "AWS/SQS", minute, 12);
service.beforeReset();
service.deleteOldestMetricData("AWS/SQS", 10);
assertEquals(minutesFrom(minute, 0, 12), storedMinutes("AWS/SQS", minute));
service.afterReset();
service.deleteOldestMetricData("AWS/SQS", 10);
assertEquals(minutesFrom(minute, 3, 12), storedMinutes("AWS/SQS", minute));
}
private void putOnePerMinute(CloudWatchMetricsService target, String accountId, String namespace,
long firstMinute, int count) {
for (int i = 0; i < count; i++) {
MetricDatum datum = datum(i % 2 == 0 ? "Sent" : "Received", 1);
datum.setTimestamp(firstMinute + 60L * i);
target.putMetricDataForAccount(accountId, namespace, List.of(datum), REGION);
}
}
/** The minutes for which {@code namespace} still holds a datapoint of either metric, oldest first. */
private List<Instant> storedMinutes(String namespace, long firstMinute) {
List<Instant> minutes = new ArrayList<>();
for (String metric : List.of("Sent", "Received")) {
service.getMetricStatistics(namespace, metric, null, Instant.ofEpochSecond(firstMinute),
Instant.ofEpochSecond(firstMinute + 6000), 60, List.of("Sum"), null, REGION)
.forEach(point -> minutes.add(point.timestamp()));
}
minutes.sort(null);
return minutes;
}
private static List<Instant> minutesFrom(long firstMinute, int from, int to) {
List<Instant> minutes = new ArrayList<>();
for (int i = from; i < to; i++) {
minutes.add(Instant.ofEpochSecond(firstMinute + 60L * i));
}
return minutes;
}
// ──────────────────────────── GetMetricStatistics ────────────────────────────
@Test
@@ -3,6 +3,8 @@ package io.floci.aws.services.cloudwatch.metrics;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -59,4 +61,34 @@ class MetricKeyIndexTest {
assertEquals(List.of(key(SERIES, 60, "b")), index.keysBetween(ACCOUNT, SERIES, 0, 120));
assertEquals(List.of(key(otherNamespace, 59, "c")), index.keysBetween(ACCOUNT, otherNamespace, 0, 120));
}
@Test
void removeOldest_takesTheOldestKeysAcrossTheNamespacesSeriesUntilTheKeepCountIsLeft() {
String received = "us-east-1::AWS/SQS::NumberOfMessagesReceived::QueueName=orders::";
String otherNamespace = "us-east-1::AWS/SQSX::NumberOfMessagesSent::QueueName=orders::";
MetricKeyIndex index = new MetricKeyIndex();
for (String key : List.of(key(SERIES, 10, "a"), key(received, 20, "b"), key(SERIES, 30, "c"),
key(received, 40, "d"), key(SERIES, 50, "e"), key(otherNamespace, 1, "f"))) {
index.add(ACCOUNT, key);
}
index.add("111111111111", key(SERIES, 5, "g"));
Map<String, Set<String>> removed = index.removeOldest("AWS/SQS", 4, 3);
assertEquals(Map.of(ACCOUNT, Set.of(key(SERIES, 10, "a"), key(received, 20, "b"))), removed);
assertEquals(List.of(key(SERIES, 30, "c"), key(SERIES, 50, "e")), index.keysBetween(ACCOUNT, SERIES, 0, 120));
assertEquals(List.of(key(received, 40, "d")), index.keysBetween(ACCOUNT, received, 0, 120));
assertEquals(List.of(key(otherNamespace, 1, "f")), index.keysBetween(ACCOUNT, otherNamespace, 0, 120));
assertEquals(List.of(key(SERIES, 5, "g")), index.keysBetween("111111111111", SERIES, 0, 120));
}
@Test
void removeOldest_leavesAnAccountThatHoldsExactlyTheCeiling() {
MetricKeyIndex index = new MetricKeyIndex();
index.add(ACCOUNT, key(SERIES, 10, "a"));
index.add(ACCOUNT, key(SERIES, 20, "b"));
assertEquals(Map.of(), index.removeOldest("AWS/SQS", 2, 1));
assertEquals(2, index.keysBetween(ACCOUNT, SERIES, 0, 120).size());
}
}
@@ -1,5 +1,7 @@
package io.floci.aws.services.cloudwatch.metrics;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -13,8 +15,13 @@ 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.anyInt;
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.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -68,8 +75,65 @@ class MinuteMetricsPublisherTest {
}
}
@Test
void everyTickCutsTheNamespaceBackToTheCeiling() {
publisher(metrics, 500).publish(clock.instant());
verify(metrics).deleteOldestMetricData("AWS/Test", 500);
}
@Test
void aCeilingOfZeroKeepsEveryDatapoint() {
publisher(metrics, 0).publish(clock.instant());
verify(metrics, never()).deleteOldestMetricData(anyString(), anyInt());
}
@Test
void aFailedCutIsTriedAgainTheNextMinute() {
doThrow(new IllegalStateException("store closed")).when(metrics).deleteOldestMetricData("AWS/Test", 500);
MinuteMetricsPublisher<String> publisher = publisher(metrics, 500);
publisher.publish(clock.instant());
publisher.publish(clock.instant().plusSeconds(60));
verify(metrics, times(2)).deleteOldestMetricData("AWS/Test", 500);
}
@Test
void theCeilingLeavesAClientsOwnNamespaceAlone() {
CloudWatchMetricsService stored = new CloudWatchMetricsService(new InMemoryStorage<>(),
new InMemoryStorage<>(), new RegionResolver("us-east-1", "111111111111"));
Instant start = clock.instant().minusSeconds(86_400);
for (int i = 0; i < 3; i++) {
stored.putMetricData("MyApp", List.of(MetricDatum.of("Value", "Count", 1, List.of(),
start.plusSeconds(60L * i).getEpochSecond())), "us-east-1");
}
MinuteMetricsPublisher<String> publisher = publisher(stored, 2);
for (int i = 0; i < 3; i++) {
publisher.publish(clock.instant().plusSeconds(60L * i));
}
Instant end = clock.instant().plusSeconds(600);
assertEquals(3, stored.getMetricStatistics("MyApp", "Value", null, start, end, 60, List.of("Sum"), null,
"us-east-1").size());
assertEquals(List.of(Instant.parse("2026-10-27T12:34:00Z"), Instant.parse("2026-10-27T12:35:00Z")),
stored.getMetricStatistics("AWS/Test", "Value", null, start, end, 60, List.of("Sum"), null,
"us-east-1").stream().map(CloudWatchMetricsService.Datapoint::timestamp).toList());
}
private MinuteMetricsPublisher<String> publisher(boolean enabled) {
return new MinuteMetricsPublisher<>(metrics, "AWS/Test", enabled, clock, scheduler) {
return publisher(metrics, enabled, 0);
}
private MinuteMetricsPublisher<String> publisher(CloudWatchMetricsService service, int maxStoredDatapoints) {
return publisher(service, true, maxStoredDatapoints);
}
private MinuteMetricsPublisher<String> publisher(CloudWatchMetricsService service, boolean enabled,
int maxStoredDatapoints) {
return new MinuteMetricsPublisher<>(service, "AWS/Test", enabled, maxStoredDatapoints, clock, scheduler) {
@Override
protected List<String> collectTargets(Instant now) {
return List.of("target");
@@ -41,7 +41,7 @@ class RedshiftMetricsIntegrationTest {
@BeforeEach
void setUp() {
publisher = new RedshiftMetricsPublisher(redshift, cloudWatch, collectors, true);
publisher = new RedshiftMetricsPublisher(redshift, cloudWatch, collectors, true, 0);
}
@AfterEach
@@ -58,7 +58,7 @@ class RedshiftMetricsPublisherTest {
}
private RedshiftMetricsPublisher publisher(RedshiftMetricCollector... collectors) {
return new RedshiftMetricsPublisher(redshift, cloudWatch, List.of(collectors), true);
return new RedshiftMetricsPublisher(redshift, cloudWatch, List.of(collectors), true, 0);
}
@Test