fix(cloudwatch): preserve weighted samples on public metric APIs (#8974)

* fix(cloudwatch): preserve weighted samples on public metric APIs
* fix(cloudwatch): index Query fields before weighted parsing
* fix(cloudwatch): include datum paths in weighted length errors

Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-19 11:57:03 -04:00
1 parent 9795119ce0
commit d8a638e4af
10 files changed
+470 -13

No files matched your search

+4 -1
View File
@@ -481,7 +481,10 @@ through 2^360. They reject incomplete `StatisticValues` sets and datums combinin
`StatisticValues` before storing any part of the batch. Missing statistics return `MissingParameter`;
invalid values and non-object statistics return `InvalidParameterValue`; combining scalar and
statistics returns `InvalidParameterCombination`. JSON bodies use the corresponding SDK exception
shape names. The console's supported numeric values use the same bounds.
shape names. `Values` accepts 1 to 150 numeric samples with optional matching, nonnegative
`Counts`; omitted counts default to one. The public JSON and Query APIs normalize these weighted
samples without expanding their counts and reject combinations with `Value` or `StatisticValues`.
The console's supported numeric values use the same bounds.
**Endpoint:** `http://localhost:4566/`. Query: GET or POST; JSON: POST.
@@ -128,7 +128,7 @@ public class CloudWatchMetricsJsonHandler {
* to a value other than {@code null} or {@code false}, is refused rather than answered as if it
* were unset, and a top-level {@code null} member is dropped. {@code PutMetricData} also checks
* the complete batch for supported scalar or statistic-set shapes before storing any metrics;
* {@code Values} and {@code Counts} are refused because this handler does not parse them.
* {@code Values} and {@code Counts} remain outside this compatibility subset.
* Other operations pass nested members on unchecked, nulls included. A {@code DescribeAlarms} answer that would list
* an alarm defined with {@code Metrics} is refused too, since the console's API gives those
* items its own shape, with {@code Alias} instead of {@code Id} and {@code MetricStat}. The
@@ -964,7 +964,7 @@ public class CloudWatchMetricsJsonHandler {
datum.setMaximum(MetricNumberValidation.parse(statsValues.path("Maximum"), statsPath + ".Maximum"));
}
datums.add(datum);
datums.addAll(MetricValues.fromJson(item, memberPath, datum));
}
return datums;
}
@@ -710,6 +710,7 @@ public class CloudWatchMetricsQueryHandler {
private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {
Map<String, SortedSet<Integer>> memberIndexes = new HashMap<>();
Map<String, Map<String, List<String>>> fieldsByDatum = new HashMap<>();
Set<String> statisticPrefixes = new HashSet<>();
// An empty EntityMetricData entry serializes to no keys, so its index is absent
// while later entries keep theirs: iterate the indexes present, not 1..first gap.
@@ -720,6 +721,7 @@ public class CloudWatchMetricsQueryHandler {
String prefix = member.group();
memberIndexes.computeIfAbsent(member.group(1), ignored -> new TreeSet<>())
.add(parseMetricMemberIndex(member.group(2), prefix));
fieldsByDatum.computeIfAbsent(prefix, ignored -> new HashMap<>()).put(key, params.get(key));
if (key.startsWith(prefix + "StatisticValues.")) {
statisticPrefixes.add(prefix);
}
@@ -730,11 +732,13 @@ public class CloudWatchMetricsQueryHandler {
}
}
List<MetricDatum> datums = parseMetricData(params, "MetricData",
memberIndexes.getOrDefault("MetricData", Collections.emptySortedSet()), statisticPrefixes);
memberIndexes.getOrDefault("MetricData", Collections.emptySortedSet()),
fieldsByDatum, statisticPrefixes);
for (int index : entityIndexes) {
String listPrefix = "EntityMetricData.member." + index + ".MetricData";
datums.addAll(parseMetricData(params, listPrefix,
memberIndexes.getOrDefault(listPrefix, Collections.emptySortedSet()), statisticPrefixes));
memberIndexes.getOrDefault(listPrefix, Collections.emptySortedSet()),
fieldsByDatum, statisticPrefixes));
}
LOG.debugv("Query PutMetricData parsed {0} datums", datums.size());
return datums;
@@ -749,7 +753,9 @@ public class CloudWatchMetricsQueryHandler {
}
private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params, String listPrefix,
SortedSet<Integer> memberIndexes, Set<String> statisticPrefixes) {
SortedSet<Integer> memberIndexes,
Map<String, Map<String, List<String>>> fieldsByDatum,
Set<String> statisticPrefixes) {
List<MetricDatum> datums = new ArrayList<>();
for (int i : memberIndexes) {
String memberPrefix = listPrefix + ".member." + i + ".";
@@ -797,7 +803,7 @@ public class CloudWatchMetricsQueryHandler {
}
datum.setDimensions(dims);
datums.add(datum);
datums.addAll(MetricValues.fromQuery(fieldsByDatum.get(memberPrefix), memberPrefix, datum));
}
return datums;
}
@@ -150,7 +150,7 @@ public class CloudWatchMetricsService {
datum.setTimestamp(nowSeconds);
}
// Synthesize StatisticValues if only a scalar value was provided
if (datum.getSampleCount() == 0 && datum.getSum() == 0) {
if (!datum.hasSampleCount() && datum.getSum() == 0) {
datum.setSampleCount(1);
datum.setSum(datum.getValue());
datum.setMinimum(datum.getValue());
@@ -41,7 +41,7 @@ final class MetricNumberValidation {
return Double.isFinite(value) && Math.abs(value) <= MAX_ABSOLUTE_VALUE;
}
private static double finite(double value, String path) {
static double finite(double value, String path) {
if (!isValid(value)) {
throw invalid(path);
}
@@ -0,0 +1,120 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/** Normalize each distinct value to a recoverable statistic set without expanding its count. */
final class MetricValues {
private static final int MAX_VALUES = 150;
private MetricValues() {
}
static List<MetricDatum> fromJson(JsonNode input, String memberPath, MetricDatum datum) {
List<Double> values = jsonNumbers(input.get("Values"), "Values");
List<Double> counts = jsonNumbers(input.get("Counts"), "Counts");
return normalize(datum, memberPath + ".", values, counts,
input.hasNonNull("Value") || input.hasNonNull("StatisticValues"));
}
/** Parse fields indexed for one datum, so a batch never rescans the entire request per sample. */
static List<MetricDatum> fromQuery(Map<String, List<String>> input, String prefix, MetricDatum datum) {
List<Double> values = queryNumbers(input, prefix + "Values");
List<Double> counts = queryNumbers(input, prefix + "Counts");
boolean otherFormat = input.containsKey(prefix + "Value")
|| input.keySet().stream().anyMatch(key -> key.startsWith(prefix + "StatisticValues."));
return normalize(datum, prefix, values, counts, otherFormat);
}
private static List<Double> jsonNumbers(JsonNode input, String field) {
if (input == null || input.isNull()) {
return null;
}
if (!input.isArray() || input.isEmpty() || input.size() > MAX_VALUES) {
throw CloudWatchMetricsException.invalidParameterValue(field + " must contain 1 to 150 numbers.");
}
List<Double> numbers = new ArrayList<>(input.size());
for (JsonNode value : input) {
if (!value.isNumber()) {
throw CloudWatchMetricsException.invalidParameterValue(field + " must contain numbers.");
}
numbers.add(value.doubleValue());
}
return numbers;
}
private static List<Double> queryNumbers(Map<String, List<String>> input, String field) {
TreeMap<Integer, Double> numbers = new TreeMap<>();
for (Map.Entry<String, List<String>> entry : input.entrySet()) {
String key = entry.getKey();
if (!key.equals(field) && !key.startsWith(field + ".")) {
continue;
}
String prefix = field + ".member.";
try {
if (!key.startsWith(prefix) || entry.getValue().size() != 1) {
throw new IllegalArgumentException();
}
int index = Integer.parseInt(key.substring(prefix.length()));
if (index < 1 || index > MAX_VALUES) {
throw new IllegalArgumentException();
}
double value = Double.parseDouble(entry.getValue().getFirst());
Double previous = numbers.putIfAbsent(index, value);
if (previous != null) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException error) {
throw CloudWatchMetricsException.invalidParameterValue(
field + " must contain 1 to 150 consecutively indexed numbers.");
}
}
if (numbers.isEmpty()) {
return null;
}
if (numbers.lastKey() != numbers.size()) {
throw CloudWatchMetricsException.invalidParameterValue(field + " has a missing member.");
}
return new ArrayList<>(numbers.values());
}
private static List<MetricDatum> normalize(MetricDatum template, String memberPrefix, List<Double> values,
List<Double> counts, boolean otherFormat) {
if (values == null) {
if (counts != null) {
throw CloudWatchMetricsException.invalidParameterCombination("Counts requires Values.");
}
return List.of(template);
}
if (otherFormat) {
throw CloudWatchMetricsException.invalidParameterCombination(
"Values cannot be combined with Value or StatisticValues.");
}
if (counts != null && counts.size() != values.size()) {
throw CloudWatchMetricsException.invalidParameterValue("The parameters " + memberPrefix
+ "Values and " + memberPrefix + "Counts must be of the same size.");
}
List<MetricDatum> result = new ArrayList<>(values.size());
for (int i = 0; i < values.size(); i++) {
double value = MetricNumberValidation.finite(values.get(i), "Values.member." + (i + 1));
double count = counts == null ? 1 : counts.get(i);
if (!Double.isFinite(count) || count < 0 || !Double.isFinite(value * count)) {
throw CloudWatchMetricsException.invalidParameterValue(
"Counts must be nonnegative finite numbers with a finite weighted sum.");
}
MetricDatum sample = MetricDatum.of(template.getMetricName(), template.getUnit(), value,
List.copyOf(template.getDimensions()), template.getTimestamp());
sample.setSampleCount(count);
sample.setSum(value * count);
sample.setMinimum(value);
sample.setMaximum(value);
result.add(sample);
}
return result;
}
}
@@ -1,5 +1,6 @@
package io.floci.aws.services.cloudwatch.metrics.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@@ -16,6 +17,8 @@ public class MetricDatum {
private long timestamp;
private double value;
private double sampleCount;
@JsonIgnore
private boolean sampleCountSet;
private double sum;
private double minimum;
private double maximum;
@@ -54,7 +57,13 @@ public class MetricDatum {
public void setValue(double value) { this.value = value; }
public double getSampleCount() { return sampleCount; }
public void setSampleCount(double sampleCount) { this.sampleCount = sampleCount; }
public void setSampleCount(double sampleCount) {
this.sampleCount = sampleCount;
this.sampleCountSet = true;
}
@JsonIgnore
public boolean hasSampleCount() { return sampleCountSet; }
public double getSum() { return sum; }
public void setSum(double sum) { this.sum = sum; }
@@ -50,15 +50,21 @@ class CloudWatchMetricsQueryHandlerTest {
metricsService, mock(CloudWatchDashboardsService.class),
mock(CloudWatchMetricStreamsService.class));
@Test
void aLargeMixedBatchDoesNotRescanEveryFormFieldForEachDatum() {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void aLargeMixedBatchDoesNotRescanEveryFormFieldForEachDatum(boolean weighted) {
MultivaluedMap<String, String> params = spy(new MultivaluedHashMap<String, String>());
params.putSingle("Namespace", "LargeBatch");
for (String list : List.of("MetricData", "EntityMetricData.member.2.MetricData")) {
for (int index = 1; index <= 500; index++) {
String prefix = list + ".member." + index + ".";
params.putSingle(prefix + "MetricName", "Metric" + index);
params.putSingle(prefix + "Value", Integer.toString(index));
if (weighted) {
params.putSingle(prefix + "Values.member.1", Integer.toString(index));
params.putSingle(prefix + "Counts.member.1", "2");
} else {
params.putSingle(prefix + "Value", Integer.toString(index));
}
}
}
@@ -68,8 +74,13 @@ class CloudWatchMetricsQueryHandlerTest {
verify(metricsService).putMetricData(eq("LargeBatch"), datums.capture(), eq(REGION));
assertEquals(1000, datums.getValue().size());
assertEquals(500.0, datums.getValue().getLast().getValue());
if (weighted) {
assertEquals(2.0, datums.getValue().getLast().getSampleCount());
assertEquals(1000.0, datums.getValue().getLast().getSum());
}
// Bound whole-map scans independently of the number of datums; no timing assertion.
verify(params, atMost(3)).keySet();
verify(params, atMost(3)).entrySet();
}
@ParameterizedTest
@@ -0,0 +1,235 @@
package io.floci.aws.services.cloudwatch.metrics;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
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.EntityMetricData;
import software.amazon.awssdk.services.cloudwatch.model.InvalidParameterCombinationException;
import software.amazon.awssdk.services.cloudwatch.model.InvalidParameterValueException;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudWatchWeightedSamplesIntegrationTest {
private static final String ACCOUNT = "000000000358";
private static final Dimension DIMENSION = Dimension.builder().name("Route").value("weighted").build();
@ParameterizedTest
@CsvSource({"us-east-1,false", "us-east-1,true", "us-gov-west-1,false", "us-gov-west-1,true"})
void sdkRetainsWeightedAndDefaultCounts(String regionName, boolean entity) {
Instant now = Instant.now();
String namespace = "WeightedSamples/" + UUID.randomUUID();
List<MetricDatum> datums = List.of(
metric("Weighted", now).values(2.0, 5.0).counts(3.0, 2.0).build(),
metric("DefaultCounts", now).values(2.0, 5.0).build(),
metric("ZeroWeight", now).values(7.0, 11.0).counts(0.0, 0.0).build());
PutMetricDataRequest.Builder request = PutMetricDataRequest.builder().namespace(namespace);
if (entity) {
request.entityMetricData(EntityMetricData.builder().metricData(datums).build())
.strictEntityValidation(false);
} else {
request.metricData(datums);
}
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.of(regionName))) {
client.putMetricData(request.build());
assertStatistics(client, namespace, "Weighted", now, 16, 5, 2, 5);
assertStatistics(client, namespace, "DefaultCounts", now, 7, 2, 2, 5);
Datapoint zero = statistics(client, namespace, "ZeroWeight", now);
assertEquals(0, zero.sum());
assertEquals(0, zero.sampleCount());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void queryRetainsWeightedSamplesAndMetadata(boolean entity) {
Instant now = Instant.now();
String namespace = "WeightedQuery/" + UUID.randomUUID();
String prefix = entity ? "EntityMetricData.member.1.MetricData.member.1."
: "MetricData.member.1.";
query().formParam("Namespace", namespace)
.formParam("StrictEntityValidation", "false")
.formParam(prefix + "MetricName", "Weighted")
.formParam(prefix + "Timestamp", now.toString())
.formParam(prefix + "Unit", "Milliseconds")
.formParam(prefix + "Dimensions.member.1.Name", DIMENSION.name())
.formParam(prefix + "Dimensions.member.1.Value", DIMENSION.value())
.formParam(prefix + "Values.member.1", "2")
.formParam(prefix + "Values.member.2", "5")
.formParam(prefix + "Counts.member.1", "3")
.formParam(prefix + "Counts.member.2", "2")
.when().post("/").then().statusCode(200);
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.US_EAST_1)) {
assertStatistics(client, namespace, "Weighted", now, 16, 5, 2, 5);
}
}
@ParameterizedTest
@ValueSource(strings = {"us-east-1", "us-gov-west-1"})
void sdkRejectsInvalidCountsBeforeStoringTheBatch(String regionName) {
Instant now = Instant.now();
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.of(regionName))) {
for (List<Double> counts : List.of(List.of(1.0), List.of(-1.0, 2.0))) {
String namespace = "WeightedInvalid/" + UUID.randomUUID();
InvalidParameterValueException error = assertThrows(InvalidParameterValueException.class,
() -> client.putMetricData(request -> request.namespace(namespace).metricData(
metric("First", now).value(7.0).build(),
metric("Invalid", now).values(2.0, 5.0).counts(counts).build())));
assertEquals(400, error.statusCode());
assertTrue(error.getMessage().contains("Counts"));
assertTrue(client.listMetrics(request -> request.namespace(namespace)).metrics().isEmpty());
}
}
}
@ParameterizedTest
@CsvSource({"false,1", "false,3", "true,1", "true,3"})
void sdkReportsMismatchedCountsAtTheDatumPath(boolean entity, int countLength) {
Instant now = Instant.now();
String namespace = "WeightedCountMismatch/" + UUID.randomUUID();
List<Double> counts = countLength == 1 ? List.of(1.0) : List.of(1.0, 2.0, 3.0);
List<MetricDatum> datums = List.of(
metric("First", now).value(7.0).build(),
metric("Invalid", now).values(2.0, 5.0).counts(counts).build());
PutMetricDataRequest.Builder request = PutMetricDataRequest.builder().namespace(namespace);
if (entity) {
request.entityMetricData(
EntityMetricData.builder().metricData(metric("FirstEntity", now).value(1.0).build()).build(),
EntityMetricData.builder().metricData(datums).build()).strictEntityValidation(false);
} else {
request.metricData(datums);
}
String memberPath = entity ? "EntityMetricData.member.2.MetricData.member.2" : "MetricData.member.2";
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.US_EAST_1)) {
InvalidParameterValueException error = assertThrows(InvalidParameterValueException.class,
() -> client.putMetricData(request.build()));
assertEquals(400, error.statusCode());
assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode());
assertEquals("The parameters " + memberPath + ".Values and " + memberPath
+ ".Counts must be of the same size.", error.awsErrorDetails().errorMessage());
assertTrue(client.listMetrics(list -> list.namespace(namespace)).metrics().isEmpty());
}
}
@ParameterizedTest
@CsvSource({"false,1", "false,3", "true,1", "true,3"})
void queryReportsMismatchedCountsAtTheDatumPath(boolean entity, int countLength) {
String namespace = "WeightedQueryCountMismatch/" + UUID.randomUUID();
String listPath = entity ? "EntityMetricData.member.2.MetricData" : "MetricData";
String memberPath = listPath + ".member.2";
RequestSpecification request = query().formParam("Namespace", namespace)
.formParam("StrictEntityValidation", "false")
.formParam(listPath + ".member.1.MetricName", "First")
.formParam(listPath + ".member.1.Value", "7")
.formParam(memberPath + ".MetricName", "Invalid")
.formParam(memberPath + ".Values.member.1", "2")
.formParam(memberPath + ".Values.member.2", "5");
if (entity) {
request.formParam("EntityMetricData.member.1.MetricData.member.1.MetricName", "FirstEntity")
.formParam("EntityMetricData.member.1.MetricData.member.1.Value", "1");
}
for (int index = 1; index <= countLength; index++) {
request.formParam(memberPath + ".Counts.member." + index, Integer.toString(index));
}
request.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo("The parameters " + memberPath
+ ".Values and " + memberPath + ".Counts must be of the same size."));
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.US_EAST_1)) {
assertTrue(client.listMetrics(list -> list.namespace(namespace)).metrics().isEmpty());
}
}
@ParameterizedTest
@ValueSource(strings = {"us-east-1", "us-gov-west-1"})
void sdkRejectsConflictingValuesBeforeStoringTheBatch(String regionName) {
Instant now = Instant.now();
String namespace = "WeightedConflict/" + UUID.randomUUID();
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.of(regionName))) {
InvalidParameterCombinationException error = assertThrows(InvalidParameterCombinationException.class,
() -> client.putMetricData(request -> request.namespace(namespace).metricData(
metric("First", now).value(7.0).build(),
metric("Invalid", now).value(2.0).values(2.0, 5.0).build())));
assertEquals(400, error.statusCode());
assertTrue(error.getMessage().contains("Values cannot be combined"));
assertTrue(client.listMetrics(request -> request.namespace(namespace)).metrics().isEmpty());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void queryRejectsMissingValueIndicesBeforeStoringTheBatch(boolean entity) {
String namespace = "WeightedQueryInvalid/" + UUID.randomUUID();
String prefix = entity ? "EntityMetricData.member.1.MetricData.member.1."
: "MetricData.member.2.";
query().formParam("Namespace", namespace)
.formParam("MetricData.member.1.MetricName", "First")
.formParam("MetricData.member.1.Value", "7")
.formParam(prefix + "MetricName", "Invalid")
.formParam(prefix + "Values.member.2", "5")
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", containsString("Values has a missing member"));
try (CloudWatchClient client = AwsTestClients.create(
CloudWatchClient.builder(), ACCOUNT, Region.US_EAST_1)) {
assertTrue(client.listMetrics(request -> request.namespace(namespace)).metrics().isEmpty());
}
}
private static MetricDatum.Builder metric(String name, Instant now) {
return MetricDatum.builder().metricName(name).timestamp(now)
.unit("Milliseconds").dimensions(DIMENSION);
}
private static Datapoint statistics(CloudWatchClient client, String namespace, String name, Instant now) {
List<Datapoint> points = client.getMetricStatistics(request -> request.namespace(namespace)
.metricName(name).dimensions(DIMENSION).unit("Milliseconds")
.startTime(now.minusSeconds(120)).endTime(now.plusSeconds(120)).period(60)
.statisticsWithStrings("Sum", "SampleCount", "Minimum", "Maximum", "Average")).datapoints();
assertEquals(1, points.size());
return points.getFirst();
}
private static void assertStatistics(CloudWatchClient client, String namespace, String name, Instant now,
double sum, double count, double minimum, double maximum) {
Datapoint point = statistics(client, namespace, name, now);
assertEquals(sum, point.sum());
assertEquals(count, point.sampleCount());
assertEquals(minimum, point.minimum());
assertEquals(maximum, point.maximum());
assertEquals(sum / count, point.average());
assertEquals("Milliseconds", point.unitAsString());
}
private static RequestSpecification query() {
return given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261119/us-east-1/monitoring/aws4_request")
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "PutMetricData").formParam("Version", "2010-08-01");
}
}
@@ -0,0 +1,73 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MetricValuesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void querySamplesPreserveZeroWeightsAndDefaultCounts() {
MetricDatum template = MetricDatum.of("Latency", "Milliseconds", 0, List.of(), 123);
List<MetricDatum> weighted = MetricValues.fromQuery(Map.of(
"Values.member.1", List.of("7"), "Values.member.2", List.of("11"),
"Counts.member.1", List.of("0"), "Counts.member.2", List.of("2")), "", template);
assertEquals(2, weighted.size());
assertTrue(weighted.getFirst().hasSampleCount());
assertEquals(0, weighted.getFirst().getSampleCount());
assertEquals(7, weighted.getFirst().getMinimum());
assertEquals(22, weighted.getLast().getSum());
assertEquals(123, weighted.getLast().getTimestamp());
List<MetricDatum> unweighted = MetricValues.fromQuery(
Map.of("Values.member.1", List.of("7")), "", template);
assertEquals(1, unweighted.getFirst().getSampleCount());
assertEquals(7, unweighted.getFirst().getSum());
}
@Test
void queryRejectsMissingIndicesBeforeReturningSamples() {
AwsException error = assertThrows(AwsException.class, () -> MetricValues.fromQuery(
Map.of("Values.member.2", List.of("7")), "", new MetricDatum()));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertTrue(error.getMessage().contains("Values has a missing member"));
}
@Test
void largeCountsDoNotExpandTheStoredSamples() throws Exception {
List<MetricDatum> samples = MetricValues.fromJson(
MAPPER.readTree("{\"Values\":[2,5],\"Counts\":[1000000000,2]}"),
"MetricData.member.1", MetricDatum.of("Latency", "Milliseconds", 0, List.of(), 123));
assertEquals(2, samples.size());
assertEquals(1_000_000_000, samples.getFirst().getSampleCount());
assertEquals(2_000_000_000, samples.getFirst().getSum());
}
@ParameterizedTest
@CsvSource(value = {
"{\"Values\":[]}|InvalidParameterValue|Values",
"{\"Values\":[1],\"Counts\":[]}|InvalidParameterValue|Counts",
"{\"Values\":[1],\"Counts\":[-1]}|InvalidParameterValue|Counts",
"{\"Values\":[1],\"Counts\":[1,2]}|InvalidParameterValue|Counts",
"{\"Values\":[\"1\"]}|InvalidParameterValue|Values",
"{\"Values\":[1e200]}|InvalidParameterValue|Values",
"{\"Counts\":[1]}|InvalidParameterCombination|Counts requires Values",
"{\"Values\":[1],\"Value\":1}|InvalidParameterCombination|Values cannot be combined"
}, delimiter = '|')
void invalidSamplesAreRejected(String json, String code, String field) {
AwsException error = assertThrows(AwsException.class,
() -> MetricValues.fromJson(MAPPER.readTree(json), "MetricData.member.1", new MetricDatum()));
assertEquals(code, error.getErrorCode());
assertTrue(error.getMessage().contains(field));
}
}