From c40b11fe9ae0063eeaa371fb6b164e928c6b6e35 Mon Sep 17 00:00:00 2001 From: Tal Efraim <105146337+Tal-E@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:20:34 +0200 Subject: [PATCH] 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. --- .../configuration/advanced/application-yml.md | 1 + docs/configuration/environment-variables.md | 1 + docs/services/cloudwatch.md | 18 ++++ docs/services/sqs.md | 2 +- .../io/floci/aws/config/EmulatorConfig.java | 11 +++ .../metrics/CloudWatchMetricsService.java | 26 +++++ .../cloudwatch/metrics/MetricKeyIndex.java | 49 +++++++++- .../metrics/MinuteMetricsPublisher.java | 29 ++++-- .../metrics/RedshiftMetricsPublisher.java | 8 +- .../aws/services/sqs/SqsMetricsPublisher.java | 3 +- src/main/resources/application.yml | 1 + .../metrics/CloudWatchMetricsServiceTest.java | 94 +++++++++++++++++++ .../metrics/MetricKeyIndexTest.java | 32 +++++++ .../metrics/MinuteMetricsPublisherTest.java | 66 ++++++++++++- .../RedshiftMetricsIntegrationTest.java | 2 +- .../metrics/RedshiftMetricsPublisherTest.java | 2 +- 16 files changed, 328 insertions(+), 17 deletions(-) diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 62a984cb38..f636a3f29c 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -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 diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index f21c83c409..f54fd58ce6 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -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 diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 8436bab8f4..109d6ec766 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -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. diff --git a/docs/services/sqs.md b/docs/services/sqs.md index 905dbd36d8..53e830a881 100644 --- a/docs/services/sqs.md +++ b/docs/services/sqs.md @@ -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 diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 4a977a9d00..c7582a5019 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -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 { diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java index d36b509b0f..0eb29176ad 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java @@ -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> oldestByAccount = metricKeys.removeOldest(namespace, ceiling, ceiling - ceiling / 10); + if (oldestByAccount.isEmpty()) { + return; + } + if (metricStore instanceof AccountAwareStorageBackend 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 void deleteInEveryAccount(StorageBackend store, Predicate expired) { if (store instanceof AccountAwareStorageBackend aware) { aware.deleteAllAccountsMatching(expired); diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndex.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndex.java index b20c3d4be1..26f537c634 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndex.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndex.java @@ -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> 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> removeOldest(String namespace, int ceiling, int keep) { + String namespaceSegment = "::" + namespace + "::"; + Map> removedByAccount = new HashMap<>(); + endingsBySeriesByAccount.forEach((account, endingsBySeries) -> { + List namespaceSeries = new ArrayList<>(); + long held = 0; + for (Map.Entry> endings : endingsBySeries.entrySet()) { + if (isInNamespace(endings.getKey(), namespaceSegment)) { + namespaceSeries.add(endings.getKey()); + held += endings.getValue().size(); + } + } + if (held <= ceiling) { + return; + } + List 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 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 keysBetween(String account, String series, long fromSeconds, long toSeconds) { Map> endingsBySeries = endingsBySeriesByAccount.get(account); diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisher.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisher.java index 48f38399a2..8174a21f80 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisher.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisher.java @@ -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 { @@ -28,23 +29,27 @@ public abstract class MinuteMetricsPublisher { 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 { 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. */ diff --git a/src/main/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisher.java b/src/main/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisher.java index e3b97bf563..48a5751977 100644 --- a/src/main/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisher.java +++ b/src/main/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisher.java @@ -28,12 +28,14 @@ public class RedshiftMetricsPublisher { @Inject public RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService, Instance 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 collectors, boolean enabled) { - this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) { + Iterable collectors, boolean enabled, + int maxStoredDatapoints) { + this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled, maxStoredDatapoints) { @Override protected List collectTargets(Instant now) { return redshiftService.availableMetricTargets(); diff --git a/src/main/java/io/floci/aws/services/sqs/SqsMetricsPublisher.java b/src/main/java/io/floci/aws/services/sqs/SqsMetricsPublisher.java index a40574dcea..fcfcb2f501 100644 --- a/src/main/java/io/floci/aws/services/sqs/SqsMetricsPublisher.java +++ b/src/main/java/io/floci/aws/services/sqs/SqsMetricsPublisher.java @@ -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 collectTargets(Instant now) { return sqsService.collectQueueMetrics(now); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 147750298d..9a999283cc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -741,6 +741,7 @@ floci: max-stored-events: 20000 cloudwatchmetrics: enabled: true + max-stored-datapoints: 100000 paymentcryptography: enabled: true secretsmanager: diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java index b1e65a9e31..222a9d203b 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java @@ -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 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 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 storedMinutes(String namespace, long firstMinute) { + List 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 minutesFrom(long firstMinute, int from, int to) { + List minutes = new ArrayList<>(); + for (int i = from; i < to; i++) { + minutes.add(Instant.ofEpochSecond(firstMinute + 60L * i)); + } + return minutes; + } + // ──────────────────────────── GetMetricStatistics ──────────────────────────── @Test diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndexTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndexTest.java index 35cd49542e..7b812a05d4 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndexTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/MetricKeyIndexTest.java @@ -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> 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()); + } } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisherTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisherTest.java index cf448e7874..1b471ddf18 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisherTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/MinuteMetricsPublisherTest.java @@ -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 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 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 publisher(boolean enabled) { - return new MinuteMetricsPublisher<>(metrics, "AWS/Test", enabled, clock, scheduler) { + return publisher(metrics, enabled, 0); + } + + private MinuteMetricsPublisher publisher(CloudWatchMetricsService service, int maxStoredDatapoints) { + return publisher(service, true, maxStoredDatapoints); + } + + private MinuteMetricsPublisher publisher(CloudWatchMetricsService service, boolean enabled, + int maxStoredDatapoints) { + return new MinuteMetricsPublisher<>(service, "AWS/Test", enabled, maxStoredDatapoints, clock, scheduler) { @Override protected List collectTargets(Instant now) { return List.of("target"); diff --git a/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsIntegrationTest.java index 9614df8bbf..6e1c7236ca 100644 --- a/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsIntegrationTest.java @@ -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 diff --git a/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisherTest.java b/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisherTest.java index 8495e539dc..fa66157dbd 100644 --- a/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisherTest.java +++ b/src/test/java/io/floci/aws/services/redshift/metrics/RedshiftMetricsPublisherTest.java @@ -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