fix(cloudwatch): read one metric's datapoints through a sorted key index instead of scanning the store (#9345)

This commit is contained in:
Ignas authored and GitHub committed 2026-11-24 07:41:06 -04:00
1 parent de6aaa4e0a
commit 75f94407d4
7 files changed
+288 -19

No files matched your search

@@ -14,6 +14,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
@@ -245,6 +246,16 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return result;
}
/**
* Passes every account-relative key with the account that owns it, as {@link #scanAllAccountEntries}
* resolves them, without reading any value.
*/
public void forEachKeyInAllAccounts(BiConsumer<String, String> accountAndKey) {
for (String rawKey : delegate.keys()) {
accountAndKey.accept(ownerOf(rawKey), hasAccountPrefix(rawKey) ? rawKey.substring(13) : rawKey);
}
}
/**
* Returns entries across every account while preserving the account that owns each logical key.
* The filter receives the account-relative key. Keys without a 12-digit ASCII account prefix,
@@ -10,6 +10,7 @@ import io.floci.aws.lifecycle.inithook.InitializationHook;
import io.floci.aws.lifecycle.inithook.InitializationHooksRunner;
import io.floci.aws.services.amazonmq.container.RabbitMqManager;
import io.floci.aws.services.appsync.graphql.SchemaCreationWorker;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.codeartifact.CodeArtifactService;
import io.floci.aws.services.docdb.container.DocDbContainerManager;
import io.floci.aws.services.dynamodb.DynamoDbRuntime;
@@ -123,6 +124,7 @@ public class EmulatorLifecycle {
private final PersistentPathValidator persistentPathValidator;
private final EksService eksService;
private final CodeArtifactService codeArtifactService;
private final CloudWatchMetricsService cloudWatchMetricsService;
private final DynamoDbRuntime dynamoDbRuntime;
private final RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer;
// Set on the boot thread, read by the async HttpServerStart observer.
@@ -170,7 +172,8 @@ public class EmulatorLifecycle {
DynamoDbRuntime dynamoDbRuntime,
RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer,
EksService eksService,
CodeArtifactService codeArtifactService) {
CodeArtifactService codeArtifactService,
CloudWatchMetricsService cloudWatchMetricsService) {
this.storageFactory = storageFactory;
this.serviceRegistry = serviceRegistry;
this.config = config;
@@ -212,6 +215,7 @@ public class EmulatorLifecycle {
this.persistentPathValidator = persistentPathValidator;
this.eksService = eksService;
this.codeArtifactService = codeArtifactService;
this.cloudWatchMetricsService = cloudWatchMetricsService;
this.dynamoDbRuntime = dynamoDbRuntime;
this.redshiftZeroEtlConsumer = redshiftZeroEtlConsumer;
}
@@ -243,6 +247,7 @@ public class EmulatorLifecycle {
serviceRegistry.logEnabledServices();
storageFactory.loadAll();
cloudWatchMetricsService.buildMetricKeyIndex();
int sweptSessions = iamService.sweepOrphanedLambdaExecutionRoleSessions();
if (sweptSessions > 0) {
LOG.infov("Removed {0} orphaned Lambda execution-role session(s)", sweptSessions);
@@ -16,6 +16,7 @@ import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
@@ -58,7 +59,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class CloudWatchMetricsService {
public class CloudWatchMetricsService implements Resettable {
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsService.class);
@@ -84,6 +85,7 @@ public class CloudWatchMetricsService {
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
private final StorageBackend<String, MetricDatum> metricStore;
private final MetricKeyIndex metricKeys = new MetricKeyIndex();
private final StorageBackend<String, Alarm> alarmStore;
private final StorageBackend<String, AlarmHistoryItem> historyStore;
private final RegionResolver regionResolver;
@@ -131,6 +133,45 @@ public class CloudWatchMetricsService {
this.historyStore = historyStore;
this.regionResolver = regionResolver;
this.alarmSnsNotifier = alarmSnsNotifier;
// A store handed in directly has nothing left to load.
buildMetricKeyIndex();
}
/**
* Adds the store's keys to the metric key index and starts reading through it.
* {@code EmulatorLifecycle} calls it once storage has loaded; reads scan the store until then.
*/
public void buildMetricKeyIndex() {
if (metricStore instanceof AccountAwareStorageBackend<MetricDatum> aware) {
aware.forEachKeyInAllAccounts(metricKeys::add);
} else {
String account = metricKeyAccount(null);
metricStore.keys().forEach(key -> metricKeys.add(account, key));
}
metricKeys.markBuilt();
}
/** Empties the metric key index before storage is wiped, so a datum written after the wipe keeps its key. */
@Override
public void beforeReset() {
metricKeys.clear();
}
@Override
public void clear() {
}
@Override
public void afterReset() {
buildMetricKeyIndex();
}
/** The account whose index partition holds {@code accountId}'s keys; the request's when null. */
private String metricKeyAccount(String accountId) {
if (metricStore instanceof AccountAwareStorageBackend<?> aware) {
return accountId != null ? accountId : aware.accountId();
}
return "";
}
public void putMetricData(String namespace, List<MetricDatum> datums, String region) {
@@ -191,7 +232,7 @@ public class CloudWatchMetricsService {
private void storeDatum(String accountId, String namespace, MetricDatum datum, String region, String id) {
String key = region + "::" + namespace + "::" + datum.getMetricName()
+ "::" + buildDimKey(datum.getDimensions()) + "::"
+ String.format("%013d", datum.getTimestamp()) + "::" + id;
+ MetricKeyIndex.timestampSegment(datum.getTimestamp()) + "::" + id;
if (accountId != null && metricStore instanceof AccountAwareStorageBackend<?> rawAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<MetricDatum> aware = (AccountAwareStorageBackend<MetricDatum>) rawAware;
@@ -199,6 +240,7 @@ public class CloudWatchMetricsService {
} else {
metricStore.put(key, datum);
}
metricKeys.add(metricKeyAccount(accountId), key);
}
/**
@@ -207,6 +249,8 @@ public class CloudWatchMetricsService {
*/
public void deleteMetricDataBefore(String namespace, Instant cutoff) {
long cutoffSeconds = cutoff.getEpochSecond();
// Index first: a read skips a key whose datum is gone, but cannot find a datum without a key.
metricKeys.removeBefore(namespace, cutoffSeconds);
deleteInEveryAccount(metricStore, d -> namespace.equals(d.getNamespace()) && d.getTimestamp() < cutoffSeconds);
}
@@ -314,22 +358,13 @@ public class CloudWatchMetricsService {
String prefix = region + "::" + namespace + "::" + metricName + "::" + dimKey + "::";
long startEpoch = startTime != null ? startTime.getEpochSecond() : 0;
long endEpoch = endTime != null ? endTime.getEpochSecond() : Long.MAX_VALUE;
// An end time with a fractional second includes datapoints stamped in that second.
long endExclusive = endTime == null ? Long.MAX_VALUE
: endTime.getEpochSecond() + (endTime.getNano() > 0 ? 1 : 0);
List<MetricDatum> matching = metricStore.scan(k -> {
if (!k.startsWith(prefix)) return false;
// Extract timestamp from key segment
String[] parts = k.split("::");
if (parts.length < 6) return false;
try {
long ts = Long.parseLong(parts[parts.length - 2]);
boolean beforeEnd = endTime == null || ts < endEpoch
|| (ts == endEpoch && endTime.getNano() > 0);
return ts >= startEpoch && beforeEnd;
} catch (NumberFormatException e) {
return false;
}
});
List<MetricDatum> matching = metricKeys.isBuilt()
? indexedDatapoints(prefix, startEpoch, endExclusive)
: scannedDatapoints(prefix, startEpoch, endExclusive);
if (unit != null && !unit.isBlank() && !"None".equals(unit)) {
matching = matching.stream()
@@ -365,6 +400,33 @@ public class CloudWatchMetricsService {
return result;
}
private List<MetricDatum> indexedDatapoints(String prefix, long startEpoch, long endExclusive) {
List<MetricDatum> matching = new ArrayList<>();
for (String key : metricKeys.keysBetween(metricKeyAccount(null), prefix, startEpoch, endExclusive)) {
// A key deleted since the index listed it is skipped.
metricStore.get(key).ifPresent(matching::add);
}
return matching;
}
private List<MetricDatum> scannedDatapoints(String prefix, long startEpoch, long endExclusive) {
return metricStore.scan(k -> {
if (!k.startsWith(prefix)) {
return false;
}
String[] parts = k.split("::");
if (parts.length < 6) {
return false;
}
try {
long ts = Long.parseLong(parts[parts.length - 2]);
return ts >= startEpoch && ts < endExclusive;
} catch (NumberFormatException e) {
return false;
}
});
}
public List<MetricDataResult> getMetricData(
List<MetricDataQuery> queries,
Instant startTime,
@@ -0,0 +1,79 @@
package io.floci.aws.services.cloudwatch.metrics;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
/**
* The metric store's keys per account, sorted, so a read of one metric's datapoints between two
* times walks that key range instead of every key in the store. Values stay in the store.
*
* <p>A key is its series, {@code region::namespace::metric::dimensions::}, followed by the datum's
* zero-padded timestamp ({@link #timestampSegment}) and id, which never contains {@code ::}. Each
* series is held once, with its keys' {@code timestamp::id} endings sorted by time.</p>
*
* <p>The index serves reads once {@link #markBuilt} runs on a store that has finished loading;
* until then {@link #isBuilt} is false and callers scan the store. Only {@link #clear} removes keys
* other than by retention, so a key added while the store is being read in is kept.</p>
*/
final class MetricKeyIndex {
private final Map<String, Map<String, NavigableSet<String>>> endingsBySeriesByAccount = new ConcurrentHashMap<>();
private volatile boolean built;
/** The timestamp segment of a store key: zero-padded so keys sort by time within a metric. */
static String timestampSegment(long epochSeconds) {
return String.format("%013d", epochSeconds);
}
boolean isBuilt() {
return built;
}
void markBuilt() {
built = true;
}
/** Removes every key and stops serving reads until the next {@link #markBuilt}. */
void clear() {
built = false;
endingsBySeriesByAccount.clear();
}
void add(String account, String key) {
int endingStart = key.lastIndexOf("::", key.lastIndexOf("::") - 1) + 2;
endingsBySeriesByAccount.computeIfAbsent(account, ignored -> new ConcurrentHashMap<>())
.computeIfAbsent(key.substring(0, endingStart), ignored -> new ConcurrentSkipListSet<>())
.add(key.substring(endingStart));
}
/** Removes the keys of every {@code namespace} series, in every account, stamped before {@code cutoffSeconds}. */
void removeBefore(String namespace, long cutoffSeconds) {
String namespaceSegment = "::" + namespace + "::";
String cutoff = timestampSegment(cutoffSeconds);
for (Map<String, NavigableSet<String>> endingsBySeries : endingsBySeriesByAccount.values()) {
endingsBySeries.forEach((series, endings) -> {
if (series.startsWith(namespaceSegment, series.indexOf("::"))) {
endings.headSet(cutoff).clear();
}
});
}
}
/** 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);
NavigableSet<String> endings = endingsBySeries == null ? null : endingsBySeries.get(series);
if (endings == null || fromSeconds >= toSeconds) {
return List.of();
}
List<String> keys = new ArrayList<>();
for (String ending : endings.subSet(timestampSegment(fromSeconds), true, timestampSegment(toSeconds), false)) {
keys.add(series + ending);
}
return keys;
}
}
@@ -9,6 +9,7 @@ import io.floci.aws.lifecycle.inithook.InitializationHook;
import io.floci.aws.lifecycle.inithook.InitializationHooksRunner;
import io.floci.aws.services.amazonmq.container.RabbitMqManager;
import io.floci.aws.services.appsync.graphql.SchemaCreationWorker;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.codeartifact.CodeArtifactService;
import io.floci.aws.services.docdb.container.DocDbContainerManager;
import io.floci.aws.services.dynamodb.DynamoDbRuntime;
@@ -122,6 +123,7 @@ class EmulatorLifecycleTest {
@Mock private EcsService ecsService;
@Mock private EksService eksService;
@Mock private CodeArtifactService codeArtifactService;
@Mock private CloudWatchMetricsService cloudWatchMetricsService;
@Mock private InitializationHooksRunner initializationHooksRunner;
@Mock private SqsEventSourcePoller sqsPoller;
@Mock private KinesisEventSourcePoller kinesisPoller;
@@ -187,7 +189,8 @@ class EmulatorLifecycleTest {
pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState,
schemaCreationWorker, stepFunctionsService, durableExecutionService, containerTeardowns,
persistentPathValidator,
dynamoDbRuntime, redshiftZeroEtlConsumer, eksService, codeArtifactService);
dynamoDbRuntime, redshiftZeroEtlConsumer, eksService, codeArtifactService,
cloudWatchMetricsService);
Mockito.lenient().when(containerTeardowns.iterator())
.thenReturn(Collections.emptyIterator());
}
@@ -411,6 +411,53 @@ class CloudWatchMetricsServiceTest {
assertEquals(1.0, points.getFirst().sampleCount());
}
@Test
void getMetricStatistics_readsDatapointsTheStoreHeldBeforeTheIndexWasBuilt() {
InMemoryStorage<String, MetricDatum> store = new InMemoryStorage<>();
CloudWatchMetricsService loaded = new CloudWatchMetricsService(
store, new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 120;
MetricDatum persisted = datum("Requests", 7);
persisted.setNamespace(NAMESPACE);
persisted.setTimestamp(minute);
persisted.setSampleCount(1.0);
persisted.setSum(7.0);
persisted.setMinimum(7.0);
persisted.setMaximum(7.0);
store.put(REGION + "::" + NAMESPACE + "::Requests::::"
+ MetricKeyIndex.timestampSegment(minute) + "::persisted", persisted);
loaded.buildMetricKeyIndex();
List<CloudWatchMetricsService.Datapoint> points = loaded.getMetricStatistics(
NAMESPACE, "Requests", null, Instant.ofEpochSecond(minute), Instant.ofEpochSecond(minute + 60),
60, List.of("Sum"), null, REGION);
assertEquals(1, points.size());
assertEquals(7.0, points.getFirst().sum());
}
@Test
void deleteMetricDataBefore_dropsOnlyTheNamespacesOlderDatapoints() {
long minute = (Instant.now().getEpochSecond() / 60) * 60 - 600;
MetricDatum old = datum("Requests", 1);
old.setTimestamp(minute);
MetricDatum recent = datum("Requests", 2);
recent.setTimestamp(minute + 120);
MetricDatum otherNamespace = datum("Requests", 4);
otherNamespace.setTimestamp(minute);
service.putMetricData(NAMESPACE, List.of(old, recent), REGION);
service.putMetricData("Other/Metrics", List.of(otherNamespace), REGION);
service.deleteMetricDataBefore(NAMESPACE, Instant.ofEpochSecond(minute + 60));
Instant start = Instant.ofEpochSecond(minute);
Instant end = Instant.ofEpochSecond(minute + 180);
assertEquals(List.of(2.0), service.getMetricStatistics(NAMESPACE, "Requests", null, start, end,
60, List.of("Sum"), null, REGION).stream().map(CloudWatchMetricsService.Datapoint::sum).toList());
assertEquals(List.of(4.0), service.getMetricStatistics("Other/Metrics", "Requests", null, start, end,
60, List.of("Sum"), null, REGION).stream().map(CloudWatchMetricsService.Datapoint::sum).toList());
}
// ──────────────────────────── GetMetricStatistics ────────────────────────────
@Test
@@ -0,0 +1,62 @@
package io.floci.aws.services.cloudwatch.metrics;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MetricKeyIndexTest {
private static final String ACCOUNT = "000000000000";
private static final String SERIES = "us-east-1::AWS/SQS::NumberOfMessagesSent::QueueName=orders::";
private static String key(String series, long timestamp, String id) {
return series + MetricKeyIndex.timestampSegment(timestamp) + "::" + id;
}
@Test
void keysBetween_includesTheStartSecondAndExcludesTheEndSecond() {
MetricKeyIndex index = new MetricKeyIndex();
for (String key : List.of(key(SERIES, 59, "a"), key(SERIES, 60, "b"), key(SERIES, 119, "c"),
key(SERIES, 120, "d"))) {
index.add(ACCOUNT, key);
}
assertEquals(List.of(key(SERIES, 60, "b"), key(SERIES, 119, "c")),
index.keysBetween(ACCOUNT, SERIES, 60, 120));
}
@Test
void keysBetween_skipsAMetricWhoseDimensionsExtendTheRequestedOnes() {
String wider = "us-east-1::AWS/SQS::NumberOfMessagesSent::QueueName=orders,Region=eu::";
MetricKeyIndex index = new MetricKeyIndex();
index.add(ACCOUNT, key(SERIES, 60, "a"));
index.add(ACCOUNT, key(wider, 60, "b"));
assertEquals(List.of(key(SERIES, 60, "a")), index.keysBetween(ACCOUNT, SERIES, 0, Long.MAX_VALUE));
}
@Test
void keysBetween_readsOnlyTheGivenAccount() {
MetricKeyIndex index = new MetricKeyIndex();
index.add(ACCOUNT, key(SERIES, 60, "a"));
index.add("111111111111", key(SERIES, 60, "b"));
assertEquals(List.of(key(SERIES, 60, "b")), index.keysBetween("111111111111", SERIES, 0, 120));
}
@Test
void removeBefore_keepsTheCutoffSecondAndOtherNamespaces() {
String otherNamespace = "us-east-1::AWS/SQSX::NumberOfMessagesSent::QueueName=orders::";
MetricKeyIndex index = new MetricKeyIndex();
index.add(ACCOUNT, key(SERIES, 59, "a"));
index.add(ACCOUNT, key(SERIES, 60, "b"));
index.add(ACCOUNT, key(otherNamespace, 59, "c"));
index.removeBefore("AWS/SQS", 60);
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));
}
}