mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudwatch): accept summaries accompanying weighted values (#9560)
StatisticValues sent beside Values and Counts is read as a summary of the same distribution, so the weighted samples are kept without counting the summary twice. A conflicting scalar Value or a malformed summary still fails before anything is published. The weighted-summary and metric-math alarm tests share one JSON-to-Query conversion in CloudWatchTestRequests.
This commit is contained in:
1 parent
6ba4970877
commit
15a0aacb06
6 files changed
+165
-27
No files matched your search
@@ -492,7 +492,8 @@ invalid values and non-object statistics return `InvalidParameterValue`; combini
|
||||
statistics returns `InvalidParameterCombination`. JSON bodies use the corresponding SDK exception
|
||||
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`.
|
||||
samples without expanding their counts. A `StatisticValues` set sent with `Values` summarizes the same
|
||||
distribution and is not counted again. Combining `Value` and `Values` is rejected.
|
||||
The console's supported numeric values use the same bounds.
|
||||
|
||||
**Endpoint:** `http://localhost:4566/`. Query: GET or POST; JSON: POST.
|
||||
|
||||
@@ -19,15 +19,14 @@ final class MetricValues {
|
||||
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"));
|
||||
input.hasNonNull("Value"));
|
||||
}
|
||||
|
||||
/** 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."));
|
||||
boolean otherFormat = input.containsKey(prefix + "Value");
|
||||
return normalize(datum, prefix, values, counts, otherFormat);
|
||||
}
|
||||
|
||||
@@ -83,6 +82,10 @@ final class MetricValues {
|
||||
return new ArrayList<>(numbers.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* StatisticValues accompanying Values summarizes the same distribution. Keep the weighted samples
|
||||
* without counting that summary again; scalar Value and Values remain alternative forms.
|
||||
*/
|
||||
private static List<MetricDatum> normalize(MetricDatum template, String memberPrefix, List<Double> values,
|
||||
List<Double> counts, boolean otherFormat) {
|
||||
if (values == null) {
|
||||
@@ -92,8 +95,7 @@ final class MetricValues {
|
||||
return List.of(template);
|
||||
}
|
||||
if (otherFormat) {
|
||||
throw CloudWatchMetricsException.invalidParameterCombination(
|
||||
"Values cannot be combined with Value or StatisticValues.");
|
||||
throw CloudWatchMetricsException.invalidParameterCombination("Values cannot be combined with Value.");
|
||||
}
|
||||
if (counts != null && counts.size() != values.size()) {
|
||||
throw CloudWatchMetricsException.invalidParameterValue("The parameters " + memberPrefix
|
||||
|
||||
+1
-21
@@ -103,7 +103,7 @@ class CloudWatchMetricMathAlarmTest {
|
||||
|
||||
private void put(ObjectNode request, boolean queryProtocol) {
|
||||
if (queryProtocol) {
|
||||
assertEquals(200, queryHandler.handle("PutMetricAlarm", toQuery(request), REGION).getStatus());
|
||||
assertEquals(200, queryHandler.handle("PutMetricAlarm", CloudWatchTestRequests.toQuery(request), REGION).getStatus());
|
||||
} else {
|
||||
assertEquals(200, jsonHandler.handle("PutMetricAlarm", request, REGION).getStatus());
|
||||
}
|
||||
@@ -172,26 +172,6 @@ class CloudWatchMetricMathAlarmTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> toQuery(JsonNode value) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
flatten(value, "", params);
|
||||
return params;
|
||||
}
|
||||
|
||||
private static void flatten(JsonNode value, String prefix, MultivaluedMap<String, String> params) {
|
||||
if (value.isArray()) {
|
||||
for (int index = 0; index < value.size(); index++) {
|
||||
flatten(value.get(index), prefix + ".member." + (index + 1), params);
|
||||
}
|
||||
} else if (value.isObject()) {
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
flatten(field.getValue(), prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(), params);
|
||||
}
|
||||
} else {
|
||||
params.putSingle(prefix, value.asText());
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectNode metricMathRequest() throws Exception {
|
||||
return (ObjectNode) MAPPER.readTree("""
|
||||
{"AlarmName":"metric-math-round-trip","EvaluationPeriods":2,"Threshold":5,
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -40,6 +43,26 @@ final class CloudWatchTestRequests {
|
||||
.formParams(queryParameters(operation, body)).post("/");
|
||||
}
|
||||
|
||||
static MultivaluedMap<String, String> toQuery(JsonNode value) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
flatten(value, "", params);
|
||||
return params;
|
||||
}
|
||||
|
||||
private static void flatten(JsonNode value, String prefix, MultivaluedMap<String, String> params) {
|
||||
if (value.isArray()) {
|
||||
for (int index = 0; index < value.size(); index++) {
|
||||
flatten(value.get(index), prefix + ".member." + (index + 1), params);
|
||||
}
|
||||
} else if (value.isObject()) {
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
flatten(field.getValue(), prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(), params);
|
||||
}
|
||||
} else {
|
||||
params.putSingle(prefix, value.asText());
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> queryParameters(String operation, Map<String, ?> body) {
|
||||
Map<String, Object> parameters = new LinkedHashMap<>();
|
||||
parameters.put("Action", operation);
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.MetricDatum;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.Statistic;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.StatisticSet;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudWatchWeightedSummaryIntegrationTest {
|
||||
@Test
|
||||
void sdkWeightedSummaryIsCountedOnce() {
|
||||
String namespace = "WeightedSummary/" + UUID.randomUUID();
|
||||
Instant timestamp = Instant.now().minusSeconds(60);
|
||||
try (CloudWatchClient client = AwsTestClients.create(CloudWatchClient.builder(), "test", Region.US_EAST_1)) {
|
||||
client.putMetricData(request -> request.namespace(namespace).metricData(MetricDatum.builder()
|
||||
.metricName("Latency").timestamp(timestamp).values(7.0, 11.0).counts(3.0, 2.0)
|
||||
.statisticValues(StatisticSet.builder().sampleCount(5.0).sum(43.0)
|
||||
.minimum(7.0).maximum(11.0).build()).build()));
|
||||
Datapoint point = client.getMetricStatistics(request -> request.namespace(namespace)
|
||||
.metricName("Latency").startTime(timestamp.minusSeconds(1)).endTime(timestamp.plusSeconds(1))
|
||||
.period(60).statistics(Statistic.SAMPLE_COUNT, Statistic.SUM, Statistic.MINIMUM,
|
||||
Statistic.MAXIMUM, Statistic.AVERAGE)).datapoints().getFirst();
|
||||
assertEquals(5.0, point.sampleCount());
|
||||
assertEquals(43.0, point.sum());
|
||||
assertEquals(7.0, point.minimum());
|
||||
assertEquals(11.0, point.maximum());
|
||||
assertEquals(8.6, point.average());
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class CloudWatchWeightedSummaryTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final Instant START = Instant.now().minusSeconds(60);
|
||||
private final InMemoryStorage<String, MetricDatum> store = new InMemoryStorage<>();
|
||||
private final CloudWatchMetricsService service = new CloudWatchMetricsService(
|
||||
store, new InMemoryStorage<>(), new RegionResolver(REGION, "123456789012"));
|
||||
private final CloudWatchMetricsJsonHandler json = new CloudWatchMetricsJsonHandler(
|
||||
service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), MAPPER);
|
||||
private final CloudWatchMetricsQueryHandler query = new CloudWatchMetricsQueryHandler(
|
||||
service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class));
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void statisticValuesBesideValuesAreAcceptedAndTheDistributionIsCountedOnce(boolean useQuery) {
|
||||
publish(useQuery, weighted());
|
||||
CloudWatchMetricsService.Datapoint point = service.getMetricStatistics(
|
||||
"Example/Weighted", "Latency", List.of(), START.minusSeconds(1), START.plusSeconds(1),
|
||||
60, List.of("SampleCount", "Sum", "Minimum", "Maximum"), "Milliseconds", REGION).getFirst();
|
||||
assertEquals(5, point.sampleCount());
|
||||
assertEquals(43, point.sum());
|
||||
assertEquals(7, point.minimum());
|
||||
assertEquals(11, point.maximum());
|
||||
assertEquals(8.6, point.average());
|
||||
assertEquals(2, store.keys().size());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void scalarValueStillConflictsWithWeightedValues(boolean useQuery) {
|
||||
ObjectNode datum = weighted();
|
||||
datum.remove("StatisticValues");
|
||||
datum.put("Value", 7);
|
||||
AwsException error = assertThrows(AwsException.class, () -> publish(useQuery, datum));
|
||||
assertEquals("InvalidParameterCombination", error.getErrorCode());
|
||||
assertTrue(store.keys().isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void malformedSummaryStillRejectsTheBatchBeforePublication(boolean useQuery) {
|
||||
ObjectNode datum = weighted();
|
||||
((ObjectNode) datum.get("StatisticValues")).remove("Maximum");
|
||||
AwsException error = assertThrows(AwsException.class, () -> publish(useQuery, datum));
|
||||
assertEquals("MissingParameter", error.getErrorCode());
|
||||
assertTrue(store.keys().isEmpty());
|
||||
}
|
||||
|
||||
private static ObjectNode weighted() {
|
||||
ObjectNode datum = MAPPER.createObjectNode().put("MetricName", "Latency").put("Unit", "Milliseconds")
|
||||
.put("Timestamp", START.toString());
|
||||
datum.putArray("Values").add(7).add(11);
|
||||
datum.putArray("Counts").add(3).add(2);
|
||||
datum.putObject("StatisticValues").put("SampleCount", 5).put("Sum", 43)
|
||||
.put("Minimum", 7).put("Maximum", 11);
|
||||
return datum;
|
||||
}
|
||||
|
||||
private void publish(boolean useQuery, ObjectNode datum) {
|
||||
ObjectNode request = MAPPER.createObjectNode().put("Namespace", "Example/Weighted");
|
||||
request.putArray("MetricData").add(datum);
|
||||
MultivaluedMap<String, String> params = CloudWatchTestRequests.toQuery(request);
|
||||
try (Response response = useQuery ? query.handle("PutMetricData", params, REGION)
|
||||
: json.handle("PutMetricData", request, REGION)) {
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user