From 00230a3612ddef7c0dd05bf94b3fe807f766fa6e Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:58:23 -0400 Subject: [PATCH] feat(cloudwatch): start, read, update and stop OTel enrichment (#10130) Add StartOTelEnrichment, GetOTelEnrichment, UpdateOTelEnrichment and StopOTelEnrichment over Query, JSON 1.0 and CBOR, with one configuration per account and Region as the user guide scopes it. Floci stores the configuration; enriching vended metrics comes next. Resource tag enrichment, the default, needs ObservabilityAdmin's resource tags for telemetry running in the Region: a start without it is the modeled ValidationError with the API reference's sentence, as AWS quotes no message. EnableTagEnrichment false needs nothing. A start while running changes nothing, an update replaces both filter lists as a pair and keeps the stored tag setting it omits, and an update while stopped is AWS's ResourceNotFoundException "OTel enrichment is not enabled for this account". A stopped enrichment reads as its status alone. Filters are validated as the model gives them, every violation listed in AWS's form, then against the 100 selectors allowed across both lists. A selector naming metrics without a namespace is refused as a null namespace over Query too, for metric streams as well, rather than read as no selector. Over JSON, a filter list sent as something else is refused with the deserializer's SerializationException, and EnableTagEnrichment sent as a string is read as the boolean it names or refused, so a malformed update changes nothing. Over Query, a filter name XML cannot carry is written as U+FFFD, for metric streams too. Part of #7030. --- .../test/CloudWatchOTelEnrichmentTest.java | 63 +++++ docs/services/cloudwatch.md | 42 +++ docs/services/index.md | 2 +- docs/services/observabilityadmin.md | 1 + .../metrics/CloudWatchMetricsJsonHandler.java | 85 +++++- .../CloudWatchMetricsQueryHandler.java | 70 ++++- .../metrics/OTelEnrichmentService.java | 199 ++++++++++++++ .../metrics/model/OTelEnrichment.java | 26 ++ .../CloudWatchAlarmQueryHandlerTest.java | 8 +- ...WatchDescribeAlarmsFiltersHandlerTest.java | 2 +- ...udWatchMetricFilterQueryNamespaceTest.java | 2 +- .../CloudWatchMetricMathAlarmTest.java | 4 +- .../CloudWatchMetricStreamsHandlerTest.java | 4 +- .../CloudWatchMetricsJsonHandlerTest.java | 2 +- .../CloudWatchMetricsQueryHandlerTest.java | 2 +- .../metrics/CloudWatchMetricsTagsTest.java | 4 +- ...oudWatchOTelEnrichmentIntegrationTest.java | 256 ++++++++++++++++++ .../metrics/CloudWatchPromQlAlarmTest.java | 4 +- .../CloudWatchWeightedSummaryTest.java | 4 +- .../metrics/OTelEnrichmentServiceTest.java | 228 ++++++++++++++++ 20 files changed, 977 insertions(+), 31 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchOTelEnrichmentTest.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentService.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/model/OTelEnrichment.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchOTelEnrichmentIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentServiceTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchOTelEnrichmentTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchOTelEnrichmentTest.java new file mode 100644 index 0000000000..5af117f6ba --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchOTelEnrichmentTest.java @@ -0,0 +1,63 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; +import software.amazon.awssdk.services.cloudwatch.model.GetOTelEnrichmentResponse; +import software.amazon.awssdk.services.cloudwatch.model.OTelEnrichmentMetricSelector; +import software.amazon.awssdk.services.cloudwatch.model.OTelEnrichmentStatus; +import software.amazon.awssdk.services.cloudwatch.model.ResourceNotFoundException; +import software.amazon.awssdk.services.observabilityadmin.ObservabilityAdminClient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudWatch OTel enrichment") +class CloudWatchOTelEnrichmentTest { + + // An account of its own: test classes run concurrently, and another one toggles resource tags for telemetry in + // the default account. + private static final StaticCredentialsProvider ACCOUNT = + StaticCredentialsProvider.create(AwsBasicCredentials.create("747474747474", "test")); + + @Test + @DisplayName("starts tag enrichment once resource tags for telemetry run, updates and stops it") + void enrichmentLifecycle() { + try (CloudWatchClient cloudWatch = CloudWatchClient.builder().endpointOverride(TestFixtures.endpoint()) + .region(TestFixtures.region()).credentialsProvider(ACCOUNT).build(); + ObservabilityAdminClient admin = ObservabilityAdminClient.builder() + .endpointOverride(TestFixtures.endpoint()) + .region(TestFixtures.region()).credentialsProvider(ACCOUNT).build()) { + assertThat(cloudWatch.getOTelEnrichment(request -> { }).status()).isEqualTo(OTelEnrichmentStatus.STOPPED); + assertThatThrownBy(() -> cloudWatch.startOTelEnrichment(request -> { })) + .isInstanceOf(CloudWatchException.class) + .satisfies(e -> assertThat(((CloudWatchException) e).statusCode()).isEqualTo(400)); + + admin.startTelemetryEnrichment(request -> { }); + try { + cloudWatch.startOTelEnrichment(request -> request.includeFilters(OTelEnrichmentMetricSelector.builder() + .namespace("AWS/EC2").metricNames("CPUUtilization").build())); + GetOTelEnrichmentResponse running = cloudWatch.getOTelEnrichment(request -> { }); + assertThat(running.status()).isEqualTo(OTelEnrichmentStatus.RUNNING); + assertThat(running.includeFilters()).singleElement() + .satisfies(filter -> assertThat(filter.namespace()).isEqualTo("AWS/EC2")); + + cloudWatch.updateOTelEnrichment(request -> request.includeFilters(OTelEnrichmentMetricSelector.builder() + .namespace("AWS/Lambda").build())); + assertThat(cloudWatch.getOTelEnrichment(request -> { }).includeFilters()).singleElement() + .satisfies(filter -> assertThat(filter.namespace()).isEqualTo("AWS/Lambda")); + } finally { + cloudWatch.stopOTelEnrichment(request -> { }); + admin.stopTelemetryEnrichment(request -> { }); + } + + assertThat(cloudWatch.getOTelEnrichment(request -> { }).status()).isEqualTo(OTelEnrichmentStatus.STOPPED); + assertThatThrownBy(() -> cloudWatch.updateOTelEnrichment(request -> { })) + .isInstanceOf(ResourceNotFoundException.class) + .hasMessageContaining("OTel enrichment is not enabled for this account"); + } + } +} diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 375c7c667e..90b1326707 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -557,6 +557,10 @@ returns HTTP 404. | `DeleteMetricStream` | Delete a metric stream | | `StartMetricStreams` | Move metric streams to `running` | | `StopMetricStreams` | Move metric streams to `stopped` | +| `StartOTelEnrichment` | Start OTel enrichment in the Region (see [OTel enrichment](#otel-enrichment)) | +| `GetOTelEnrichment` | Read the Region's OTel enrichment status and configuration | +| `UpdateOTelEnrichment` | Replace the filters and tag setting of running OTel enrichment | +| `StopOTelEnrichment` | Stop OTel enrichment in the Region | | `PutDashboard` | Create a dashboard, or replace its body when the name is taken (tags apply on create only) | | `GetDashboard` | Read a dashboard body and ARN | | `ListDashboards` | List dashboards, optionally by name prefix | @@ -912,6 +916,44 @@ series' value and the number as the threshold, as the guide asks of a PromQL ala scaling. Floci runs no Lambda alarm actions and sends no EventBridge alarm events, for PromQL alarms as for the others. +### OTel enrichment {#otel-enrichment} + +`StartOTelEnrichment`, `GetOTelEnrichment`, `UpdateOTelEnrichment` and `StopOTelEnrichment` keep one +enrichment configuration per account and Region, as the user guide scopes it, over Query, JSON and +CBOR. Floci stores the configuration only: vended metrics are not enriched with resource labels yet. + +Resource tag enrichment is the default (`EnableTagEnrichment` omitted or `true`), and it reads tags +through [resource tags for telemetry](observabilityadmin.md), which must run in the same Region first. +Without it `StartOTelEnrichment` answers `ValidationError` (400) with `Before calling this operation, you +must enable resource tags on telemetry for your account.`, the API reference's own sentence, as AWS +documents the prerequisite but no message for it. `EnableTagEnrichment` `false` needs nothing. +`UpdateOTelEnrichment` does not check the prerequisite, which AWS documents for the start only, and +stopping resource tags for telemetry leaves running enrichment as it is. + +A start while enrichment runs changes nothing and answers the running configuration. An update +replaces `IncludeFilters` and `ExcludeFilters` as a pair, so a list it leaves out is cleared, and keeps +the stored `EnableTagEnrichment` when it leaves that out; while enrichment is stopped it answers +`ResourceNotFoundException` (404) `OTel enrichment is not enabled for this account`, as AWS does. A +stop drops the configuration, and a stop while stopped changes nothing. While stopped, +`GetOTelEnrichment` answers `Status` `Stopped` alone; while running it adds the filters, `CreatedAt`, +`UpdatedAt` and `EnableTagEnrichment`, an empty filter list being left out. + +A selector's `Namespace` must be 1 to 255 characters and not start with a colon, its `MetricNames` +1 to 255 characters each, and each list holds at most 100 entries, refused with AWS's +`1 validation error detected: Value ':Bad' at 'includeFilters.1.member.namespace' failed to satisfy +constraint: Member must satisfy regular expression pattern: [^:].*` form. More than 100 selectors +across both lists is refused with `A maximum of 100 filters is allowed across IncludeFilters and +ExcludeFilters combined.`, the documentation's sentence, as AWS's answer is not recorded. A selector +naming metrics without a `Namespace` is refused as a null namespace, over Query as over JSON and CBOR, +rather than read as no selector. Over JSON, a filter list or `MetricNames` sent as a structure or a +scalar is refused with `SerializationException` (`Start of structure or map found where not expected.`, +`Expected list or null`), and `EnableTagEnrichment` sent as a string is read as the boolean it names +(`"false"`, `"no"`, `"0"` and the like) or refused with `STRING_VALUE can not be converted to an +Boolean`, as the JSON deserializers recorded elsewhere in Floci answer: CloudWatch's own wording is not +recorded, and a malformed update changes nothing. Over Query, a +character in a namespace or metric name that XML 1.0 cannot carry is written as U+FFFD, here and in +`GetMetricStream`'s filters. + ### Composite alarm evaluation A composite alarm is evaluated when it is created, when `PutCompositeAlarm` updates it, and when diff --git a/docs/services/index.md b/docs/services/index.md index ede625fc26..6c34573714 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -64,7 +64,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 | | [CloudWatch Observability Admin](observabilityadmin.md) | `POST /StartTelemetryEnrichment`, `POST /StopTelemetryEnrichment`, `POST /GetTelemetryEnrichmentStatus` | REST JSON | 3 | | [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 54 | -| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 26 | +| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 30 | | [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 | | [X-Ray](xray.md) | `/TraceSegments`, `/Traces`, `/TraceSummaries`, `/ServiceGraph`, `/TraceGraph`, `/GetSamplingRules`, `/CreateSamplingRule`, `/SamplingTargets`, `/TelemetryRecords`, `/TagResource`, `/UntagResource`, `/ListTagsForResource` | REST JSON | 14 | | [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 25 | diff --git a/docs/services/observabilityadmin.md b/docs/services/observabilityadmin.md index beea0d4cb4..084dee21fe 100644 --- a/docs/services/observabilityadmin.md +++ b/docs/services/observabilityadmin.md @@ -18,6 +18,7 @@ Floci implements the REST JSON API of CloudWatch Observability Admin for the res - Starting the feature has Resource Explorer create "an AWS index and managed view that indexes and discovers resources and tags in your account", as the CloudWatch user guide's "Resource tags for telemetry" says. The index is a `LOCAL` one, created only when the Region has none, and the view includes the `tags` property. `resource-explorer-2` serves the view: `GetManagedView` answers it and `ListManagedViews` lists it. - AWS documents the view but not its name, so Floci names it `AWSManagedViewForResourceTagsForTelemetry`, in the form of the one managed view the Resource Explorer guide names, `AWSManagedViewForSSM`. Its ARN is `arn::resource-explorer-2:::managed-view/AWSManagedViewForResourceTagsForTelemetry/`. Its `TrustedService` is `telemetry-enablement.observabilityadmin.amazonaws.com`, the principal of the service-linked role whose policy (`AWSObservabilityAdminTelemetryEnablementServiceRolePolicy`) grants the feature `resource-explorer-2:CreateManagedView`. - The view outlives a stop: a feature stopped and started again answers the view its first start created. +- CloudWatch's `StartOTelEnrichment` with resource tag enrichment needs the feature running in the same Region; see [OTel enrichment](cloudwatch.md#otel-enrichment). Stopping the feature leaves CloudWatch enrichment that already runs as it is. - `GetTelemetryEnrichmentStatus` for a feature never started in the Region answers `ResourceNotFoundException` (404), the operation's modeled answer before the first start. Stopping a feature that is stopped, or was never started, answers `Stopped` and changes nothing, so a feature never started still reads as never started. - Floci changes the feature's state at once, so it is never caught between `Running` and `Stopped`, is never `Impaired`, and no request answers `ConflictException`. diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index 3cebfc46ed..edd340448e 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -3,6 +3,7 @@ package io.floci.aws.services.cloudwatch.metrics; import io.floci.aws.core.common.AwsErrorResponse; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.common.JsonBooleanCoercion; import io.floci.aws.core.common.JsonNodes; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; @@ -17,6 +18,7 @@ import io.floci.aws.services.cloudwatch.metrics.model.CompositeAlarm; import io.floci.aws.services.cloudwatch.metrics.model.Dimension; import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm; import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum; +import io.floci.aws.services.cloudwatch.metrics.model.OTelEnrichment; import io.floci.aws.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService; import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStream; import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter; @@ -76,16 +78,19 @@ public class CloudWatchMetricsJsonHandler { private final CloudWatchDashboardsService dashboardsService; private final CloudWatchMetricStreamsService metricStreamsService; private final ObjectMapper objectMapper; + private final OTelEnrichmentService otelEnrichment; @Inject public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService, CloudWatchDashboardsService dashboardsService, CloudWatchMetricStreamsService metricStreamsService, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, + OTelEnrichmentService otelEnrichment) { this.metricsService = metricsService; this.dashboardsService = dashboardsService; this.metricStreamsService = metricStreamsService; this.objectMapper = objectMapper; + this.otelEnrichment = otelEnrichment; } public Response handle(String action, JsonNode request, String region) { @@ -117,6 +122,10 @@ public class CloudWatchMetricsJsonHandler { case "DeleteMetricStream" -> handleDeleteMetricStream(request, region); case "StartMetricStreams" -> handleStartMetricStreams(request, region); case "StopMetricStreams" -> handleStopMetricStreams(request, region); + case "GetOTelEnrichment" -> handleGetOTelEnrichment(region); + case "StartOTelEnrichment" -> handleStartOTelEnrichment(request, region); + case "UpdateOTelEnrichment" -> handleUpdateOTelEnrichment(request, region); + case "StopOTelEnrichment" -> handleStopOTelEnrichment(region); default -> Response.status(400) .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch JSON.")) .build(); @@ -923,6 +932,57 @@ public class CloudWatchMetricsJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + private Response handleGetOTelEnrichment(String region) { + ObjectNode response = objectMapper.createObjectNode(); + // A stopped enrichment answers its status alone: AWS omits the rest while it is stopped. + otelEnrichment.get(region).ifPresentOrElse(running -> { + response.put("Status", "Running"); + otelEnrichmentNode(response, running); + }, () -> response.put("Status", "Stopped")); + return Response.ok(response).build(); + } + + private Response handleStartOTelEnrichment(JsonNode request, String region) { + OTelEnrichment started = otelEnrichment.start(region, parseStreamFiltersJson(request.path("IncludeFilters")), + parseStreamFiltersJson(request.path("ExcludeFilters")), optionalBoolean(request, "EnableTagEnrichment")); + return Response.ok(otelEnrichmentNode(objectMapper.createObjectNode(), started)).build(); + } + + private Response handleUpdateOTelEnrichment(JsonNode request, String region) { + OTelEnrichment updated = otelEnrichment.update(region, parseStreamFiltersJson(request.path("IncludeFilters")), + parseStreamFiltersJson(request.path("ExcludeFilters")), optionalBoolean(request, "EnableTagEnrichment")); + return Response.ok(otelEnrichmentNode(objectMapper.createObjectNode(), updated)).build(); + } + + private Response handleStopOTelEnrichment(String region) { + otelEnrichment.stop(region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + /** The members a running enrichment answers with, an empty filter list being left out as AWS omits it. */ + private ObjectNode otelEnrichmentNode(ObjectNode response, OTelEnrichment enrichment) { + if (!enrichment.includeFilters().isEmpty()) { + response.set("IncludeFilters", streamFiltersNode(enrichment.includeFilters())); + } + if (!enrichment.excludeFilters().isEmpty()) { + response.set("ExcludeFilters", streamFiltersNode(enrichment.excludeFilters())); + } + response.put("CreatedAt", EpochSeconds.fromMillis(enrichment.createdAt().toEpochMilli())); + response.put("UpdatedAt", EpochSeconds.fromMillis(enrichment.updatedAt().toEpochMilli())); + response.put("EnableTagEnrichment", enrichment.enableTagEnrichment()); + return response; + } + + /** + * A boolean member, null when absent: a string naming a boolean is read as one and any other value refused, as + * AWS's JSON deserializer reads a boolean member. + */ + private static Boolean optionalBoolean(JsonNode request, String member) { + JsonNode value = request.path(member); + return value.isMissingNode() || value.isNull() ? null + : JsonBooleanCoercion.fromJson(value, "NUMBER_VALUE can not be converted to a Boolean"); + } + private List parseNamesJson(JsonNode node) { List names = new ArrayList<>(); if (node.isArray()) { @@ -962,17 +1022,30 @@ public class CloudWatchMetricsJsonHandler { private List parseStreamFiltersJson(JsonNode node) { List filters = new ArrayList<>(); - if (!node.isArray()) { - return filters; - } - for (JsonNode entry : node) { + for (JsonNode entry : listMember(node)) { List metricNames = new ArrayList<>(); - entry.path("MetricNames").forEach(n -> metricNames.add(JsonNodes.asText(n))); + listMember(entry.path("MetricNames")).forEach(n -> metricNames.add(JsonNodes.asText(n))); filters.add(new MetricStreamFilter(JsonNodes.asText(entry.path("Namespace"), null), metricNames)); } return filters; } + /** + * A list member's elements, none when it is absent. A structure or a scalar where the list belongs is refused + * with the {@code SerializationException} AWS's JSON deserializer answers, worded as {@code RequestShapeCheck}'s + * services record it, rather than read as an empty list. + */ + private static Iterable listMember(JsonNode node) { + if (node.isMissingNode() || node.isNull()) { + return List.of(); + } + if (node.isArray()) { + return node; + } + throw new AwsException("SerializationException", node.isObject() + ? "Start of structure or map found where not expected." : "Expected list or null", 400); + } + private List parseStatisticsConfigurationsJson(JsonNode node) { List configurations = new ArrayList<>(); if (!node.isArray()) { diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java index 4c61d9a451..a958722c2d 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java @@ -19,6 +19,7 @@ import io.floci.aws.services.cloudwatch.metrics.model.CompositeAlarm; import io.floci.aws.services.cloudwatch.metrics.model.Dimension; import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm; import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum; +import io.floci.aws.services.cloudwatch.metrics.model.OTelEnrichment; import io.floci.aws.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService; import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStream; import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter; @@ -57,14 +58,17 @@ public class CloudWatchMetricsQueryHandler { private CloudWatchMetricsService metricsService; private final CloudWatchDashboardsService dashboardsService; private final CloudWatchMetricStreamsService metricStreamsService; + private final OTelEnrichmentService otelEnrichment; @Inject public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService, CloudWatchDashboardsService dashboardsService, - CloudWatchMetricStreamsService metricStreamsService) { + CloudWatchMetricStreamsService metricStreamsService, + OTelEnrichmentService otelEnrichment) { this.metricsService = metricsService; this.dashboardsService = dashboardsService; this.metricStreamsService = metricStreamsService; + this.otelEnrichment = otelEnrichment; } public Response handle(String action, MultivaluedMap params, String region) { @@ -96,6 +100,10 @@ public class CloudWatchMetricsQueryHandler { case "DeleteMetricStream" -> handleDeleteMetricStream(params, region); case "StartMetricStreams" -> handleStartMetricStreams(params, region); case "StopMetricStreams" -> handleStopMetricStreams(params, region); + case "GetOTelEnrichment" -> handleGetOTelEnrichment(region); + case "StartOTelEnrichment" -> handleStartOTelEnrichment(params, region); + case "UpdateOTelEnrichment" -> handleUpdateOTelEnrichment(params, region); + case "StopOTelEnrichment" -> handleStopOTelEnrichment(region); default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch Query.", AwsNamespaces.CW, 400); }; @@ -646,6 +654,47 @@ public class CloudWatchMetricsQueryHandler { return Response.ok(AwsQueryResponse.envelopeEmptyResult("StopMetricStreams", null)).build(); } + private Response handleGetOTelEnrichment(String region) { + // A stopped enrichment answers its status alone: AWS omits the rest while it is stopped. + XmlBuilder xml = otelEnrichment.get(region) + .map(running -> otelEnrichmentXml(new XmlBuilder().elem("Status", "Running"), running)) + .orElseGet(() -> new XmlBuilder().elem("Status", "Stopped")); + return Response.ok(AwsQueryResponse.envelope("GetOTelEnrichment", AwsNamespaces.CW, xml.build())).build(); + } + + private Response handleStartOTelEnrichment(MultivaluedMap params, String region) { + OTelEnrichment started = otelEnrichment.start(region, parseStreamFilters(params, "IncludeFilters"), + parseStreamFilters(params, "ExcludeFilters"), optionalBoolean(params, "EnableTagEnrichment")); + return Response.ok(AwsQueryResponse.envelope("StartOTelEnrichment", AwsNamespaces.CW, + otelEnrichmentXml(new XmlBuilder(), started).build())).build(); + } + + private Response handleUpdateOTelEnrichment(MultivaluedMap params, String region) { + OTelEnrichment updated = otelEnrichment.update(region, parseStreamFilters(params, "IncludeFilters"), + parseStreamFilters(params, "ExcludeFilters"), optionalBoolean(params, "EnableTagEnrichment")); + return Response.ok(AwsQueryResponse.envelope("UpdateOTelEnrichment", AwsNamespaces.CW, + otelEnrichmentXml(new XmlBuilder(), updated).build())).build(); + } + + private Response handleStopOTelEnrichment(String region) { + otelEnrichment.stop(region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult("StopOTelEnrichment", AwsNamespaces.CW)).build(); + } + + /** The members a running enrichment answers with, an empty filter list being left out as AWS omits it. */ + private XmlBuilder otelEnrichmentXml(XmlBuilder xml, OTelEnrichment enrichment) { + appendStreamFilters(xml, "IncludeFilters", enrichment.includeFilters()); + appendStreamFilters(xml, "ExcludeFilters", enrichment.excludeFilters()); + return xml.elem("CreatedAt", DateTimeFormatter.ISO_INSTANT.format(enrichment.createdAt())) + .elem("UpdatedAt", DateTimeFormatter.ISO_INSTANT.format(enrichment.updatedAt())) + .elem("EnableTagEnrichment", enrichment.enableTagEnrichment()); + } + + private static Boolean optionalBoolean(MultivaluedMap params, String member) { + String value = params.getFirst(member); + return value == null ? null : Boolean.parseBoolean(value); + } + private List parseNames(MultivaluedMap params) { List names = new ArrayList<>(); for (int i = 1; ; i++) { @@ -658,17 +707,21 @@ public class CloudWatchMetricsQueryHandler { return names; } + /** + * The filters of a metric stream or of OTel enrichment. A character in a name that XML 1.0 cannot carry, which + * nothing refuses, is written as U+FFFD so the response stays well-formed. + */ private void appendStreamFilters(XmlBuilder xml, String element, List filters) { if (filters.isEmpty()) { return; } xml.start(element); for (MetricStreamFilter filter : filters) { - xml.start("member").elem("Namespace", filter.getNamespace()); + xml.start("member").elem("Namespace", XmlBuilder.cleaned(filter.getNamespace())); if (!filter.getMetricNames().isEmpty()) { xml.start("MetricNames"); for (String metricName : filter.getMetricNames()) { - xml.elem("member", metricName); + xml.elem("member", XmlBuilder.cleaned(metricName)); } xml.end("MetricNames"); } @@ -700,14 +753,16 @@ public class CloudWatchMetricsQueryHandler { xml.end("StatisticsConfigurations"); } + /** + * The filters a list carries, up to the first member carrying neither a namespace nor a metric name. A member + * naming metrics without a namespace is a filter all the same, its namespace null, so the operation refuses it + * rather than the list reading as empty. + */ private List parseStreamFilters(MultivaluedMap params, String prefix) { List filters = new ArrayList<>(); for (int i = 1; ; i++) { String base = prefix + ".member." + i; String namespace = params.getFirst(base + ".Namespace"); - if (namespace == null) { - break; - } List metricNames = new ArrayList<>(); for (int j = 1; ; j++) { String metricName = params.getFirst(base + ".MetricNames.member." + j); @@ -716,6 +771,9 @@ public class CloudWatchMetricsQueryHandler { } metricNames.add(metricName); } + if (namespace == null && metricNames.isEmpty()) { + break; + } filters.add(new MetricStreamFilter(namespace, metricNames)); } return filters; diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentService.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentService.java new file mode 100644 index 0000000000..e49667c114 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentService.java @@ -0,0 +1,199 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import io.floci.aws.core.common.AwsException; +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.StorageFactory; +import io.floci.aws.services.cloudwatch.metrics.model.OTelEnrichment; +import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter; +import io.floci.aws.services.observabilityadmin.ObservabilityAdminService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import tools.jackson.core.type.TypeReference; + +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * CloudWatch's OTel enrichment of vended metrics, one per account and Region: the user guide's "Each operation applies + * to your account and is scoped to a single AWS Region." Floci changes state at once, so a start or stop is visible + * to the next request. + * + *

Resource tag enrichment, the default, reads the tags through ObservabilityAdmin's resource tags for telemetry, + * which the account must run in the Region first: "Before calling this operation, you must enable resource tags on + * telemetry for your account." Enrichment without tags has no prerequisite. + */ +@ApplicationScoped +public class OTelEnrichmentService implements Resettable { + /** "A maximum of 100 filters is allowed across IncludeFilters and ExcludeFilters combined." */ + static final int MAX_FILTERS = 100; + /** The model's bound on each list, the selectors and the metric names of one selector alike. */ + private static final int MAX_LIST_SIZE = 100; + private static final int MAX_NAME_LENGTH = 255; + /** The pattern the model gives a namespace, as AWS writes it in a refusal. */ + private static final String NAMESPACE_PATTERN = "[^:].*"; + /** + * The refusal of a start with resource tag enrichment before resource tags on telemetry runs. AWS documents the + * prerequisite and models no error for the operation but ValidationError, and quotes no message, so this one is + * the API reference's own sentence. + */ + static final String TAGS_ON_TELEMETRY_REQUIRED = + "Before calling this operation, you must enable resource tags on telemetry for your account."; + /** The refusal of an update while enrichment is stopped, as AWS answers it. */ + static final String NOT_ENABLED = "OTel enrichment is not enabled for this account"; + + private final AccountAwareStorageBackend enrichments; + private final ObservabilityAdminService observabilityAdmin; + private final Clock clock; + + @Inject + public OTelEnrichmentService(StorageFactory storageFactory, ObservabilityAdminService observabilityAdmin) { + this(storageFactory.create("cloudwatchmetrics", "cw-otel-enrichment.json", + new TypeReference>() {}), observabilityAdmin, Clock.systemUTC()); + } + + OTelEnrichmentService(AccountAwareStorageBackend enrichments, + ObservabilityAdminService observabilityAdmin, Clock clock) { + this.enrichments = enrichments; + this.observabilityAdmin = observabilityAdmin; + this.clock = clock; + } + + /** + * Starts enrichment in {@code region} with the filters and tag setting given, a {@code null} tag setting being + * its default, {@code true}. A start while enrichment runs "has no effect and does not modify the filters or the + * tag enrichment setting that are applied", so once the request itself is valid it answers the running + * configuration. + */ + public synchronized OTelEnrichment start(String region, List includeFilters, + List excludeFilters, Boolean enableTagEnrichment) { + validate(includeFilters, excludeFilters); + Optional running = enrichments.get(region); + if (running.isPresent()) { + return running.get(); + } + boolean tags = enableTagEnrichment == null || enableTagEnrichment; + if (tags && !observabilityAdmin.telemetryEnrichmentRunning(region)) { + throw new AwsException("ValidationError", TAGS_ON_TELEMETRY_REQUIRED, 400); + } + Instant now = clock.instant(); + OTelEnrichment started = new OTelEnrichment(copy(includeFilters), copy(excludeFilters), tags, now, now); + enrichments.put(region, started); + return started; + } + + /** + * Replaces the filters of the enrichment running in {@code region}, both lists as a pair: "a request that + * specifies only IncludeFilters also clears the stored ExcludeFilters". A {@code null} tag setting keeps the + * stored one. Enrichment that is not running answers {@code ResourceNotFoundException}, whether it was stopped or + * never started. + */ + public synchronized OTelEnrichment update(String region, List includeFilters, + List excludeFilters, Boolean enableTagEnrichment) { + validate(includeFilters, excludeFilters); + OTelEnrichment running = enrichments.get(region) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", NOT_ENABLED, 404)); + boolean tags = enableTagEnrichment == null ? running.enableTagEnrichment() : enableTagEnrichment; + OTelEnrichment updated = new OTelEnrichment(copy(includeFilters), copy(excludeFilters), tags, + running.createdAt(), clock.instant()); + enrichments.put(region, updated); + return updated; + } + + /** + * Stops enrichment in {@code region}, dropping its configuration: the next start stores its own. Stopping + * enrichment that is stopped, or was never started, changes nothing, as AWS answers both alike. + */ + public synchronized void stop(String region) { + enrichments.delete(region); + } + + /** The enrichment running in {@code region}, empty while it is stopped. */ + public Optional get(String region) { + return enrichments.get(region); + } + + @Override + public void clear() { + enrichments.clear(); + } + + /** + * Refuses filters breaking the model's constraints with every violation at once, as AWS lists them, then filters + * over the combined bound, which the model cannot express. + */ + private static void validate(List includeFilters, List excludeFilters) { + List violations = new ArrayList<>(); + violations(includeFilters, "includeFilters", violations); + violations(excludeFilters, "excludeFilters", violations); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationError(violations); + } + if (size(includeFilters) + size(excludeFilters) > MAX_FILTERS) { + throw new AwsException("ValidationError", "A maximum of " + MAX_FILTERS + + " filters is allowed across IncludeFilters and ExcludeFilters combined.", 400); + } + } + + /** + * The violations of one list, its members named as AWS names them, {@code includeFilters.1.member.namespace}. + */ + private static void violations(List filters, String path, List violations) { + if (filters == null) { + return; + } + addIfPresent(violations, SmithyValidationErrors.sizeOutOfRange(path, filters.size(), 0, MAX_LIST_SIZE)); + for (int i = 0; i < filters.size(); i++) { + String member = path + "." + (i + 1) + ".member"; + String namespace = filters.get(i).getNamespace(); + if (namespace == null) { + violations.add(SmithyValidationErrors.notNull(member + ".namespace")); + } else { + addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(member + ".namespace", namespace, + 1, MAX_NAME_LENGTH)); + if (namespace.isEmpty() || namespace.charAt(0) == ':') { + violations.add(SmithyValidationErrors.pattern(member + ".namespace", namespace, + NAMESPACE_PATTERN)); + } + } + List metricNames = filters.get(i).getMetricNames(); + addIfPresent(violations, SmithyValidationErrors.sizeOutOfRange(member + ".metricNames", + metricNames.size(), 0, MAX_LIST_SIZE)); + for (int j = 0; j < metricNames.size(); j++) { + String name = metricNames.get(j); + String namePath = member + ".metricNames." + (j + 1) + ".member"; + if (name == null) { + violations.add(SmithyValidationErrors.notNull(namePath)); + } else { + addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(namePath, name, 1, + MAX_NAME_LENGTH)); + } + } + } + } + + private static void addIfPresent(List violations, String violation) { + if (violation != null) { + violations.add(violation); + } + } + + private static int size(List filters) { + return filters == null ? 0 : filters.size(); + } + + /** The filters as stored: copies, so a caller's later change to one reaches nothing stored. */ + private static List copy(List filters) { + if (filters == null) { + return List.of(); + } + return filters.stream() + .map(filter -> new MetricStreamFilter(filter.getNamespace(), new ArrayList<>(filter.getMetricNames()))) + .toList(); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/OTelEnrichment.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/OTelEnrichment.java new file mode 100644 index 0000000000..d30bab4c18 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/OTelEnrichment.java @@ -0,0 +1,26 @@ +package io.floci.aws.services.cloudwatch.metrics.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; + +/** + * The OTel enrichment running in one Region of an account: the filters and the tag enrichment setting its start or + * last update stored. A stopped enrichment keeps nothing, because the next start is the one that stores them. + * + *

The selectors have the shape of a metric stream's filters, a namespace and optionally the metric names in it, + * so they are kept as {@link MetricStreamFilter}. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public record OTelEnrichment(List includeFilters, List excludeFilters, + boolean enableTagEnrichment, Instant createdAt, Instant updatedAt) { + + public OTelEnrichment { + includeFilters = includeFilters == null ? List.of() : List.copyOf(includeFilters); + excludeFilters = excludeFilters == null ? List.of() : List.copyOf(excludeFilters); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java index 5ed44d7a58..fc058dda52 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java @@ -28,7 +28,7 @@ class CloudWatchAlarmQueryHandlerTest { String region = "us-east-1"; CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(region, "123456789012")); - CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null); MultivaluedMap request = new MultivaluedHashMap<>(); request.putSingle("AlarmName", "shared"); request.putSingle("AlarmRule", "FALSE"); @@ -68,7 +68,7 @@ class CloudWatchAlarmQueryHandlerTest { String region = "us-east-1"; CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(region, "123456789012")); - CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null); MultivaluedMap put = new MultivaluedHashMap<>(); put.putSingle("AlarmName", "query-history"); handler.handle("PutMetricAlarm", put, region); @@ -122,7 +122,7 @@ class CloudWatchAlarmQueryHandlerTest { String region = "us-east-1"; CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(region, "123456789012")); - CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null); MultivaluedMap put = new MultivaluedHashMap<>(); put.putSingle("AlarmName", "p99-query"); put.putSingle("Namespace", "AWS/ApplicationELB"); @@ -161,7 +161,7 @@ class CloudWatchAlarmQueryHandlerTest { String region = "us-east-1"; CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(region, "123456789012")); - CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null); MultivaluedMap put = new MultivaluedHashMap<>(); put.putSingle("AlarmName", "both-stats-query"); put.putSingle("Namespace", "AWS/ApplicationELB"); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java index 6e93a99a2d..75f67bb8b0 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java @@ -32,7 +32,7 @@ class CloudWatchDescribeAlarmsFiltersHandlerTest { regionResolver); private final CloudWatchMetricsJsonHandler handler = new CloudWatchMetricsJsonHandler(service, new CloudWatchDashboardsService(new InMemoryStorage<>(), regionResolver), - new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regionResolver), MAPPER); + new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regionResolver), MAPPER, null); @Test void anAlarmIsNeverListedAsItsOwnChildOrParent() { diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricFilterQueryNamespaceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricFilterQueryNamespaceTest.java index fb4535a0d1..189b015acc 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricFilterQueryNamespaceTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricFilterQueryNamespaceTest.java @@ -18,7 +18,7 @@ class CloudWatchMetricFilterQueryNamespaceTest { void metricFilterReadApisUseTheCloudWatchQueryNamespace(String action) throws Exception { CloudWatchMetricsService metrics = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000")); - CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metrics, null, null); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metrics, null, null, null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("Namespace", "MetricFilters"); params.putSingle("MetricName", "Count"); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricMathAlarmTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricMathAlarmTest.java index cc9b1e7c1b..6f64953b66 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricMathAlarmTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricMathAlarmTest.java @@ -48,8 +48,8 @@ class CloudWatchMetricMathAlarmTest { RegionResolver resolver = new RegionResolver(REGION, "000000000000"); CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), alarmStore, resolver); CloudWatchDashboardsService dashboards = new CloudWatchDashboardsService(new InMemoryStorage<>(), resolver); - jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboards, null, MAPPER); - queryHandler = new CloudWatchMetricsQueryHandler(service, dashboards, null); + jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboards, null, MAPPER, null); + queryHandler = new CloudWatchMetricsQueryHandler(service, dashboards, null, null); } @ParameterizedTest diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.java index 5fa6067060..a02d616d6e 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.java @@ -43,8 +43,8 @@ class CloudWatchMetricStreamsHandlerTest { CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(new InMemoryStorage<>(), resolver); streamsService = new CloudWatchMetricStreamsService(new InMemoryStorage<>(), resolver); - queryHandler = new CloudWatchMetricsQueryHandler(metricsService, dashboardsService, streamsService); - jsonHandler = new CloudWatchMetricsJsonHandler(metricsService, dashboardsService, streamsService, MAPPER); + queryHandler = new CloudWatchMetricsQueryHandler(metricsService, dashboardsService, streamsService, null); + jsonHandler = new CloudWatchMetricsJsonHandler(metricsService, dashboardsService, streamsService, MAPPER, null); } private static MultivaluedMap putParams(String name) { diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java index a9e3ad890a..85187edd15 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java @@ -111,7 +111,7 @@ class CloudWatchMetricsJsonHandlerTest { ); CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService( new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); - handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, MAPPER); + handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, MAPPER, null); } /** diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java index 8babd736fd..50042468bf 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java @@ -48,7 +48,7 @@ class CloudWatchMetricsQueryHandlerTest { // The alarm cases below never reach a dashboard operation; the handler simply routes both. private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler( metricsService, mock(CloudWatchDashboardsService.class), - mock(CloudWatchMetricStreamsService.class)); + mock(CloudWatchMetricStreamsService.class), null); @ParameterizedTest @ValueSource(booleans = {false, true}) diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java index a7c2574f74..bc39331991 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java @@ -39,8 +39,8 @@ class CloudWatchMetricsTagsTest { new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000")); CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService( new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000")); - queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService, metricStreamsService); - jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, objectMapper); + queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService, metricStreamsService, null); + jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, objectMapper, null); } @Test diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchOTelEnrichmentIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchOTelEnrichmentIntegrationTest.java new file mode 100644 index 0000000000..ee9b37a3bf --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchOTelEnrichmentIntegrationTest.java @@ -0,0 +1,256 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import io.floci.aws.core.common.JacksonConfig; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * OTel enrichment over the three wires CloudWatch speaks, with resource tags on telemetry run through ObservabilityAdmin + * as its prerequisite, in one Region of one account. + */ +@QuarkusTest +class CloudWatchOTelEnrichmentIntegrationTest { + // An account of its own, so no other test starts or stops enrichment or resource tags on telemetry in it. + private static final String ACCOUNT = "737373737373"; + private static final ObjectMapper CBOR = JacksonConfig.cborMapper(); + + @BeforeAll + static void configureAwsJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void tagEnrichmentStartsOnceResourceTagsOnTelemetryRun() { + String region = "eu-south-2"; + json(region, "GetOTelEnrichment", "{}") + .then().statusCode(200) + .body("Status", equalTo("Stopped")) + .body("$", not(hasKey("UpdatedAt"))); + + json(region, "StartOTelEnrichment", "{}") + .then().statusCode(400) + .header("x-amzn-query-error", "ValidationError;Sender") + .body("message", equalTo( + "Before calling this operation, you must enable resource tags on telemetry for your account.")); + + observabilityAdmin(region, "/StartTelemetryEnrichment").then().statusCode(202); + json(region, "StartOTelEnrichment", """ + {"IncludeFilters":[{"Namespace":"AWS/EC2","MetricNames":["CPUUtilization"]}], + "ExcludeFilters":[{"Namespace":"AWS/EBS"}]} + """) + .then().statusCode(200) + .body("IncludeFilters[0].Namespace", equalTo("AWS/EC2")) + .body("IncludeFilters[0].MetricNames", contains("CPUUtilization")) + .body("ExcludeFilters[0].Namespace", equalTo("AWS/EBS")) + .body("ExcludeFilters[0]", not(hasKey("MetricNames"))) + .body("EnableTagEnrichment", equalTo(true)) + .body("CreatedAt", notNullValue()) + .body("UpdatedAt", notNullValue()); + json(region, "GetOTelEnrichment", "{}") + .then().statusCode(200) + .body("Status", equalTo("Running")) + .body("IncludeFilters[0].Namespace", equalTo("AWS/EC2")) + .body("EnableTagEnrichment", equalTo(true)); + + json(region, "UpdateOTelEnrichment", "{\"IncludeFilters\":[{\"Namespace\":\"AWS/Lambda\"}]}") + .then().statusCode(200) + .body("IncludeFilters[0].Namespace", equalTo("AWS/Lambda")) + .body("$", not(hasKey("ExcludeFilters"))) + .body("EnableTagEnrichment", equalTo(true)); + + json(region, "StopOTelEnrichment", "{}").then().statusCode(200); + json(region, "GetOTelEnrichment", "{}") + .then().statusCode(200) + .body("Status", equalTo("Stopped")) + .body("$", not(hasKey("IncludeFilters"))) + .body("$", not(hasKey("CreatedAt"))); + json(region, "UpdateOTelEnrichment", "{}") + .then().statusCode(404) + .header("x-amzn-query-error", "ResourceNotFoundException;Sender") + .body("message", equalTo("OTel enrichment is not enabled for this account")); + } + + @Test + void enrichmentWithoutTagsNeedsNothingAndStaysInItsRegionAndAccount() { + String region = "il-central-1"; + json(region, "StartOTelEnrichment", "{\"EnableTagEnrichment\":false}") + .then().statusCode(200) + .body("EnableTagEnrichment", equalTo(false)) + .body("$", not(hasKey("IncludeFilters"))); + + json("me-central-1", "GetOTelEnrichment", "{}").then().statusCode(200).body("Status", equalTo("Stopped")); + given().contentType("application/x-amz-json-1.0") + .header("Authorization", auth("111122223333", region)) + .header("X-Amz-Target", "GraniteServiceVersion20100801.GetOTelEnrichment") + .body("{}").post("/") + .then().statusCode(200).body("Status", equalTo("Stopped")); + + json(region, "StopOTelEnrichment", "{}").then().statusCode(200); + json(region, "StopOTelEnrichment", "{}").then().statusCode(200); + } + + @Test + void aMalformedNamespaceIsRefusedAsAwsWordsIt() { + json("ap-east-2", "StartOTelEnrichment", "{\"IncludeFilters\":[{\"Namespace\":\":Bad\"}]}") + .then().statusCode(400) + .header("x-amzn-query-error", "ValidationError;Sender") + .body("message", equalTo("1 validation error detected: Value ':Bad' at " + + "'includeFilters.1.member.namespace' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: [^:].*")); + } + + @Test + void aSelectorNamingMetricsWithoutANamespaceIsRefusedOverQuery() { + query("il-central-1", Map.of("Action", "StartOTelEnrichment", "EnableTagEnrichment", "false", + "IncludeFilters.member.1.MetricNames.member.1", "CPUUtilization")) + .then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value null at " + + "'includeFilters.1.member.namespace' failed to satisfy constraint: Member must not be null")); + } + + @Test + void aMalformedUpdateKeepsTheRunningConfiguration() { + String region = "eu-south-2"; + json(region, "StartOTelEnrichment", + "{\"EnableTagEnrichment\":false,\"IncludeFilters\":[{\"Namespace\":\"AWS/EC2\"}]}") + .then().statusCode(200); + + json(region, "UpdateOTelEnrichment", "{\"IncludeFilters\":{}}") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("Start of structure or map found where not expected.")); + json(region, "UpdateOTelEnrichment", "{\"IncludeFilters\":[{\"MetricNames\":\"CPUUtilization\"}]}") + .then().statusCode(400) + .body("message", equalTo("Expected list or null")); + json(region, "UpdateOTelEnrichment", "{\"EnableTagEnrichment\":\"maybe\"}") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("STRING_VALUE can not be converted to an Boolean")); + json(region, "GetOTelEnrichment", "{}") + .then().statusCode(200) + .body("IncludeFilters[0].Namespace", equalTo("AWS/EC2")) + .body("EnableTagEnrichment", equalTo(false)); + + json(region, "StopOTelEnrichment", "{}").then().statusCode(200); + } + + @Test + void aTagSettingSentAsAStringIsReadAsTheBooleanItNames() { + String region = "ap-southeast-7"; + json(region, "StartOTelEnrichment", "{\"EnableTagEnrichment\":\"false\"}") + .then().statusCode(200) + .body("EnableTagEnrichment", equalTo(false)); + + json(region, "StopOTelEnrichment", "{}").then().statusCode(200); + } + + @Test + void theQueryWireAnswersTheSameEnrichment() { + String region = "ca-west-1"; + query(region, Map.of("Action", "StartOTelEnrichment", "EnableTagEnrichment", "false", + "IncludeFilters.member.1.Namespace", "AWS/EC2", + "IncludeFilters.member.1.MetricNames.member.1", "CPUUtilization")) + .then().statusCode(200) + .body("StartOTelEnrichmentResponse.StartOTelEnrichmentResult.IncludeFilters.member.Namespace", + equalTo("AWS/EC2")) + .body("StartOTelEnrichmentResponse.StartOTelEnrichmentResult.EnableTagEnrichment", equalTo("false")); + query(region, Map.of("Action", "GetOTelEnrichment")) + .then().statusCode(200) + .body("GetOTelEnrichmentResponse.GetOTelEnrichmentResult.Status", equalTo("Running")) + .body("GetOTelEnrichmentResponse.GetOTelEnrichmentResult.IncludeFilters.member.MetricNames.member", + equalTo("CPUUtilization")); + + query(region, Map.of("Action", "StopOTelEnrichment")).then().statusCode(200); + query(region, Map.of("Action", "UpdateOTelEnrichment")) + .then().statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException")) + .body("ErrorResponse.Error.Message", equalTo("OTel enrichment is not enabled for this account")); + } + + @Test + void aNameXmlCannotCarryIsWrittenCleanedOverQuery() { + String region = "ap-southeast-5"; + query(region, Map.of("Action", "StartOTelEnrichment", "EnableTagEnrichment", "false", + "IncludeFilters.member.1.Namespace", "Ctl\u0001", + "IncludeFilters.member.1.MetricNames.member.1", "M\u0002")) + .then().statusCode(200) + .body("StartOTelEnrichmentResponse.StartOTelEnrichmentResult.IncludeFilters.member.Namespace", + equalTo("Ctl�")) + .body("StartOTelEnrichmentResponse.StartOTelEnrichmentResult.IncludeFilters.member.MetricNames" + + ".member", equalTo("M�")); + json(region, "GetOTelEnrichment", "{}") + .then().statusCode(200) + .body("IncludeFilters[0].Namespace", equalTo("Ctl\u0001")); + + query(region, Map.of("Action", "StopOTelEnrichment")).then().statusCode(200); + } + + @Test + void theCborWireAnswersTimestampsAsTimestamps() throws Exception { + String region = "mx-central-1"; + JsonNode started = CBOR.readTree(cbor(region, "StartOTelEnrichment", Map.of("EnableTagEnrichment", false)) + .then().statusCode(200).extract().asByteArray()); + assertTrue(started.path("CreatedAt").isNumber(), started.toString()); + assertFalse(started.path("EnableTagEnrichment").asBoolean(true), started.toString()); + + JsonNode running = CBOR.readTree(cbor(region, "GetOTelEnrichment", Map.of()) + .then().statusCode(200).extract().asByteArray()); + assertEquals("Running", running.path("Status").asString()); + assertEquals(started.path("CreatedAt").asDouble(), running.path("CreatedAt").asDouble()); + + cbor(region, "StopOTelEnrichment", Map.of()).then().statusCode(200); + } + + private static Response json(String region, String operation, String body) { + return given().contentType("application/x-amz-json-1.0") + .header("Authorization", auth(ACCOUNT, region)) + .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation) + .body(body).post("/"); + } + + private static Response query(String region, Map params) { + return given().contentType("application/x-www-form-urlencoded") + .header("Authorization", auth(ACCOUNT, region)) + .formParams(params).formParam("Version", "2010-08-01") + .post("/"); + } + + private static Response cbor(String region, String operation, Map body) throws Exception { + return given().contentType("application/cbor").accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .header("Authorization", auth(ACCOUNT, region)) + .body(CBOR.writeValueAsBytes(body)) + .post("/service/GraniteServiceVersion20100801/operation/" + operation); + } + + private static Response observabilityAdmin(String region, String path) { + return given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261203/" + region + + "/observabilityadmin/aws4_request, SignedHeaders=host, Signature=abc") + .contentType("application/json").body("{}") + .when().post(path); + } + + private static String auth(String account, String region) { + return "AWS4-HMAC-SHA256 Credential=" + account + "/20261203/" + region + + "/monitoring/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPromQlAlarmTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPromQlAlarmTest.java index 1c5b4dfbec..87ea819c26 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPromQlAlarmTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPromQlAlarmTest.java @@ -69,8 +69,8 @@ class CloudWatchPromQlAlarmTest { service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), regions, new AlarmSnsNotifier(sns, MAPPER)); json = new CloudWatchMetricsJsonHandler(service, new CloudWatchDashboardsService(new InMemoryStorage<>(), - regions), new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regions), MAPPER); - query = new CloudWatchMetricsQueryHandler(service, null, null); + regions), new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regions), MAPPER, null); + query = new CloudWatchMetricsQueryHandler(service, null, null, null); } @Test diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchWeightedSummaryTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchWeightedSummaryTest.java index a53f651687..aa99997836 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchWeightedSummaryTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchWeightedSummaryTest.java @@ -30,9 +30,9 @@ class CloudWatchWeightedSummaryTest { 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); + service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), MAPPER, null); private final CloudWatchMetricsQueryHandler query = new CloudWatchMetricsQueryHandler( - service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class)); + service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), null); @ParameterizedTest @ValueSource(booleans = {false, true}) diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentServiceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentServiceTest.java new file mode 100644 index 0000000000..ee2209aa8a --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OTelEnrichmentServiceTest.java @@ -0,0 +1,228 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.cloudwatch.metrics.model.OTelEnrichment; +import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter; +import io.floci.aws.services.observabilityadmin.ObservabilityAdminService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** OTel enrichment's lifecycle in one Region of an account, and the filters it stores. */ +class OTelEnrichmentServiceTest { + private static final String REGION = "us-east-1"; + + private final ObservabilityAdminService observabilityAdmin = mock(ObservabilityAdminService.class); + private Instant now = Instant.parse("2026-12-03T12:00:00Z"); + /** The time the service reads, which moves only when a test moves it. */ + private final Clock clock = new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + }; + private OTelEnrichmentService service; + + @BeforeEach + void setUp() { + when(observabilityAdmin.telemetryEnrichmentRunning(REGION)).thenReturn(true); + service = new OTelEnrichmentService(AccountAwareStorageBackend.inMemory("000000000000"), observabilityAdmin, + clock); + } + + @Test + void enrichmentNeverStartedIsStopped() { + assertTrue(service.get(REGION).isEmpty()); + } + + @Test + void aStartStoresItsFiltersWithTagEnrichmentByDefault() { + OTelEnrichment started = service.start(REGION, List.of(filter("AWS/EC2", "CPUUtilization")), + List.of(filter("AWS/EBS")), null); + + assertEquals(List.of("AWS/EC2"), namespaces(started.includeFilters())); + assertEquals(List.of("CPUUtilization"), started.includeFilters().getFirst().getMetricNames()); + assertEquals(List.of("AWS/EBS"), namespaces(started.excludeFilters())); + assertTrue(started.enableTagEnrichment()); + assertEquals(now, started.createdAt()); + assertEquals(now, started.updatedAt()); + assertEquals(started, service.get(REGION).orElseThrow()); + } + + @Test + void tagEnrichmentNeedsResourceTagsOnTelemetryAndEnrichmentWithoutTagsDoesNot() { + when(observabilityAdmin.telemetryEnrichmentRunning(REGION)).thenReturn(false); + + AwsException refused = assertThrows(AwsException.class, () -> service.start(REGION, null, null, null)); + assertEquals("ValidationError", refused.getErrorCode()); + assertEquals(400, refused.getHttpStatus()); + assertEquals(OTelEnrichmentService.TAGS_ON_TELEMETRY_REQUIRED, refused.getMessage()); + assertThrows(AwsException.class, () -> service.start(REGION, null, null, true)); + assertTrue(service.get(REGION).isEmpty()); + + assertFalse(service.start(REGION, null, null, false).enableTagEnrichment()); + } + + @Test + void aStartWhileRunningChangesNothing() { + OTelEnrichment first = service.start(REGION, List.of(filter("AWS/EC2")), null, true); + now = now.plus(Duration.ofMinutes(1)); + when(observabilityAdmin.telemetryEnrichmentRunning(REGION)).thenReturn(false); + + OTelEnrichment second = service.start(REGION, List.of(filter("AWS/Lambda")), null, false); + + assertEquals(first, second); + assertEquals(first, service.get(REGION).orElseThrow()); + } + + @Test + void anUpdateReplacesBothListsAndKeepsTheTagSettingItOmits() { + OTelEnrichment started = service.start(REGION, List.of(filter("AWS/EC2")), List.of(filter("AWS/EBS")), false); + now = now.plus(Duration.ofMinutes(1)); + + OTelEnrichment updated = service.update(REGION, List.of(filter("AWS/Lambda")), null, null); + + assertEquals(List.of("AWS/Lambda"), namespaces(updated.includeFilters())); + assertEquals(List.of(), updated.excludeFilters()); + assertFalse(updated.enableTagEnrichment()); + assertEquals(started.createdAt(), updated.createdAt()); + assertEquals(now, updated.updatedAt()); + assertEquals(updated, service.get(REGION).orElseThrow()); + + assertTrue(service.update(REGION, null, null, true).enableTagEnrichment()); + assertEquals(List.of(), service.get(REGION).orElseThrow().includeFilters()); + } + + @Test + void anUpdateWhileStoppedOrNeverStartedIsNotFound() { + AwsException neverStarted = assertThrows(AwsException.class, + () -> service.update(REGION, List.of(filter("AWS/EC2")), null, null)); + assertEquals("ResourceNotFoundException", neverStarted.getErrorCode()); + assertEquals(404, neverStarted.getHttpStatus()); + assertEquals("OTel enrichment is not enabled for this account", neverStarted.getMessage()); + + service.start(REGION, null, null, null); + service.stop(REGION); + AwsException stopped = assertThrows(AwsException.class, + () -> service.update(REGION, List.of(filter("AWS/EC2")), null, null)); + assertEquals(neverStarted.getMessage(), stopped.getMessage()); + } + + @Test + void aStopDropsTheConfigurationAndAStopWhileStoppedChangesNothing() { + service.stop(REGION); + service.start(REGION, List.of(filter("AWS/EC2")), null, false); + + service.stop(REGION); + service.stop(REGION); + + assertTrue(service.get(REGION).isEmpty()); + assertTrue(service.start(REGION, null, null, null).includeFilters().isEmpty()); + } + + @Test + void aNamespaceStartingWithAColonIsRefusedAsAwsWordsItAndChangesNothing() { + service.start(REGION, List.of(filter("Good")), null, null); + + AwsException refused = assertThrows(AwsException.class, + () -> service.update(REGION, List.of(filter(":Bad")), null, null)); + + assertEquals("ValidationError", refused.getErrorCode()); + assertEquals("1 validation error detected: Value ':Bad' at 'includeFilters.1.member.namespace' failed to " + + "satisfy constraint: Member must satisfy regular expression pattern: [^:].*", refused.getMessage()); + assertEquals(List.of("Good"), namespaces(service.get(REGION).orElseThrow().includeFilters())); + } + + @Test + void everyBrokenConstraintIsListedAndValidationComesBeforeNotFound() { + List exclude = List.of(filter("AWS/EC2"), new MetricStreamFilter(null, List.of()), + filter("", "x".repeat(256))); + + AwsException refused = assertThrows(AwsException.class, () -> service.update(REGION, null, exclude, null)); + + assertEquals("4 validation errors detected: " + + "Value null at 'excludeFilters.2.member.namespace' failed to satisfy constraint: " + + "Member must not be null; " + + "Value '' at 'excludeFilters.3.member.namespace' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1; " + + "Value '' at 'excludeFilters.3.member.namespace' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: [^:].*; " + + "Value '" + "x".repeat(256) + "' at 'excludeFilters.3.member.metricNames.1.member' failed to " + + "satisfy constraint: Member must have length less than or equal to 255", refused.getMessage()); + } + + @Test + void aListOverItsBoundIsRefusedAndSoAreMoreThanAHundredSelectorsCombined() { + AwsException tooManyNames = assertThrows(AwsException.class, () -> service.start(REGION, + List.of(filter("AWS/EC2", Collections.nCopies(101, "M").toArray(String[]::new))), null, null)); + assertEquals("1 validation error detected: Value at 'includeFilters.1.member.metricNames' failed to " + + "satisfy constraint: Member must have length less than or equal to 100", tooManyNames.getMessage()); + + AwsException combined = assertThrows(AwsException.class, + () -> service.start(REGION, filters(60), filters(41), null)); + assertEquals("ValidationError", combined.getErrorCode()); + assertEquals("A maximum of 100 filters is allowed across IncludeFilters and ExcludeFilters combined.", + combined.getMessage()); + + assertEquals(100, service.start(REGION, filters(60), filters(40), null).includeFilters().size() + + service.get(REGION).orElseThrow().excludeFilters().size()); + } + + @Test + void eachRegionHasItsOwnEnrichment() { + service.start(REGION, null, null, null); + + assertTrue(service.get("eu-west-1").isEmpty()); + assertThrows(AwsException.class, () -> service.update("eu-west-1", null, null, null)); + } + + @Test + void aStoredFilterIsACopyOfTheRequestsFilter() { + List names = new ArrayList<>(List.of("CPUUtilization")); + service.start(REGION, List.of(new MetricStreamFilter("AWS/EC2", names)), null, null); + + names.add("NetworkIn"); + + assertEquals(List.of("CPUUtilization"), + service.get(REGION).orElseThrow().includeFilters().getFirst().getMetricNames()); + } + + private static MetricStreamFilter filter(String namespace, String... metricNames) { + return new MetricStreamFilter(namespace, new ArrayList<>(List.of(metricNames))); + } + + private static List filters(int count) { + return IntStream.range(0, count).mapToObj(i -> filter("Namespace" + i)).toList(); + } + + private static List namespaces(List filters) { + return filters.stream().map(MetricStreamFilter::getNamespace).toList(); + } +}