Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudwatch): store and serve metric stream definitions (#3214)
lex005b7c2c4a6201
diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.mdindex 6142fce2d0..c0a5e234e3 100644--- a/docs/services/cloudwatch.md+++ b/docs/services/cloudwatch.md@@ -191,6 +191,15 @@ aws logs put-retention-policy \| `DescribeAlarms` | List alarms || `DeleteAlarms` | Delete alarms || `SetAlarmState` | Manually set alarm state |+| `PutMetricStream` | Create or update a metric stream definition |+| `GetMetricStream` | Read a metric stream definition |+| `ListMetricStreams` | List metric streams |+| `DeleteMetricStream` | Delete a metric stream |+| `StartMetricStreams` | Move metric streams to `running` |+| `StopMetricStreams` | Move metric streams to `stopped` |++Metric streams are stored as definitions with their `running` or `stopped` state. Floci never+delivers metrics to the Firehose delivery stream a metric stream names.### Examplesdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.javaindex fb1e9d9b00..0cb0bd9300 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java@@ -503,7 +503,9 @@ public class AwsQueryController {"PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData","PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState","ListTagsForResource", "TagResource", "UntagResource",- "PutDashboard", "GetDashboard", "ListDashboards", "DeleteDashboards"+ "PutDashboard", "GetDashboard", "ListDashboards", "DeleteDashboards",+ "PutMetricStream", "GetMetricStream", "ListMetricStreams", "DeleteMetricStream",+ "StartMetricStreams", "StopMetricStreams");private static final Set<String> ELASTIC_BEANSTALK_ACTIONS = Set.of(diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.javaindex a42bcd61f9..1b28439c50 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java@@ -5,8 +5,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;@@ -30,14 +35,17 @@ public class CloudWatchMetricsJsonHandler {private static final Logger LOG = Logger.getLogger(CloudWatchMetricsJsonHandler.class);private final CloudWatchMetricsService metricsService;private final CloudWatchDashboardsService dashboardsService;+ private final CloudWatchMetricStreamsService metricStreamsService;private final ObjectMapper objectMapper;@Injectpublic CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService,CloudWatchDashboardsService dashboardsService,+ CloudWatchMetricStreamsService metricStreamsService,ObjectMapper objectMapper) {this.metricsService = metricsService;this.dashboardsService = dashboardsService;+ this.metricStreamsService = metricStreamsService;this.objectMapper = objectMapper;}@@ -59,6 +67,12 @@ public class CloudWatchMetricsJsonHandler {case "GetDashboard" -> handleGetDashboard(request, region);case "ListDashboards" -> handleListDashboards(request, region);case "DeleteDashboards" -> handleDeleteDashboards(request, region);+ case "PutMetricStream" -> handlePutMetricStream(request, region);+ case "GetMetricStream" -> handleGetMetricStream(request, region);+ case "ListMetricStreams" -> handleListMetricStreams(request, region);+ case "DeleteMetricStream" -> handleDeleteMetricStream(request, region);+ case "StartMetricStreams" -> handleStartMetricStreams(request, region);+ case "StopMetricStreams" -> handleStopMetricStreams(request, region);default -> Response.status(400).entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch JSON.")).build();@@ -243,9 +257,14 @@ public class CloudWatchMetricsJsonHandler {String arn = request.has("ResourceARN") ? request.path("ResourceARN").asText() : request.path("ResourceArn").asText();if (arn.isEmpty()) arn = request.path("resourceArn").asText();- Map<String, String> tags = CloudWatchDashboardsService.isDashboardArn(arn)- ? dashboardsService.listTagsForResource(arn, region)- : metricsService.listTagsForResource(arn, region);+ Map<String, String> tags;+ if (CloudWatchDashboardsService.isDashboardArn(arn)) {+ tags = dashboardsService.listTagsForResource(arn, region);+ } else if (CloudWatchMetricStreamsService.isMetricStreamArn(arn)) {+ tags = metricStreamsService.listTagsForResource(arn, region);+ } else {+ tags = metricsService.listTagsForResource(arn, region);+ }ArrayNode tagsArray = objectMapper.createArrayNode();tags.forEach((k, v) -> tagsArray.addObject().put("Key", k).put("Value", v));return Response.ok(objectMapper.createObjectNode().set("Tags", tagsArray)).build();@@ -262,6 +281,8 @@ public class CloudWatchMetricsJsonHandler {}if (CloudWatchDashboardsService.isDashboardArn(arn)) {dashboardsService.tagResource(arn, tags, region);+ } else if (CloudWatchMetricStreamsService.isMetricStreamArn(arn)) {+ metricStreamsService.tagResource(arn, tags, region);} else {metricsService.tagResource(arn, tags, region);}@@ -279,6 +300,8 @@ public class CloudWatchMetricsJsonHandler {}if (CloudWatchDashboardsService.isDashboardArn(arn)) {dashboardsService.untagResource(arn, keys, region);+ } else if (CloudWatchMetricStreamsService.isMetricStreamArn(arn)) {+ metricStreamsService.untagResource(arn, keys, region);} else {metricsService.untagResource(arn, keys, region);}@@ -401,6 +424,161 @@ public class CloudWatchMetricsJsonHandler {return Response.ok(objectMapper.createObjectNode()).build();}+ // ──────────────────────────── Metric Streams ────────────────────────────++ private Response handlePutMetricStream(JsonNode request, String region) {+ MetricStream stream = new MetricStream();+ stream.setName(request.path("Name").asText(null));+ stream.setFirehoseArn(request.path("FirehoseArn").asText(null));+ stream.setRoleArn(request.path("RoleArn").asText(null));+ stream.setOutputFormat(request.path("OutputFormat").asText(null));+ stream.setIncludeLinkedAccountsMetrics(request.path("IncludeLinkedAccountsMetrics").asBoolean(false));+ stream.setIncludeFilters(parseStreamFiltersJson(request.path("IncludeFilters")));+ stream.setExcludeFilters(parseStreamFiltersJson(request.path("ExcludeFilters")));+ stream.setStatisticsConfigurations(parseStatisticsConfigurationsJson(request.path("StatisticsConfigurations")));+ JsonNode tagsNode = request.path("Tags");+ if (tagsNode.isArray()) {+ Map<String, String> tags = new LinkedHashMap<>();+ tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));+ stream.setTags(tags);+ }++ MetricStream stored = metricStreamsService.putMetricStream(stream, region);+ return Response.ok(objectMapper.createObjectNode().put("Arn", stored.getArn())).build();+ }++ private Response handleGetMetricStream(JsonNode request, String region) {+ MetricStream stream = metricStreamsService.getMetricStream(request.path("Name").asText(null), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.put("Arn", stream.getArn());+ response.put("Name", stream.getName());+ response.put("FirehoseArn", stream.getFirehoseArn());+ response.put("RoleArn", stream.getRoleArn());+ response.put("State", stream.getState());+ response.put("OutputFormat", stream.getOutputFormat());+ response.put("CreationDate", stream.getCreationDate());+ response.put("LastUpdateDate", stream.getLastUpdateDate());+ response.put("IncludeLinkedAccountsMetrics", stream.isIncludeLinkedAccountsMetrics());+ if (!stream.getIncludeFilters().isEmpty()) {+ response.set("IncludeFilters", streamFiltersNode(stream.getIncludeFilters()));+ }+ if (!stream.getExcludeFilters().isEmpty()) {+ response.set("ExcludeFilters", streamFiltersNode(stream.getExcludeFilters()));+ }+ if (!stream.getStatisticsConfigurations().isEmpty()) {+ response.set("StatisticsConfigurations",+ statisticsConfigurationsNode(stream.getStatisticsConfigurations()));+ }+ return Response.ok(response).build();+ }++ private Response handleListMetricStreams(JsonNode request, String region) {+ Integer maxResults = request.hasNonNull("MaxResults") ? request.path("MaxResults").asInt() : null;+ PaginatedResult<MetricStream> page = metricStreamsService.listMetricStreams(+ maxResults, request.path("NextToken").asText(null), region);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode entries = response.putArray("Entries");+ for (MetricStream stream : page.items()) {+ ObjectNode entry = entries.addObject();+ entry.put("Arn", stream.getArn());+ entry.put("Name", stream.getName());+ entry.put("FirehoseArn", stream.getFirehoseArn());+ entry.put("State", stream.getState());+ entry.put("OutputFormat", stream.getOutputFormat());+ entry.put("CreationDate", stream.getCreationDate());+ entry.put("LastUpdateDate", stream.getLastUpdateDate());+ }+ if (page.nextToken() != null) {+ response.put("NextToken", page.nextToken());+ }+ return Response.ok(response).build();+ }++ private Response handleDeleteMetricStream(JsonNode request, String region) {+ metricStreamsService.deleteMetricStream(request.path("Name").asText(null), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleStartMetricStreams(JsonNode request, String region) {+ metricStreamsService.startMetricStreams(parseNamesJson(request.path("Names")), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleStopMetricStreams(JsonNode request, String region) {+ metricStreamsService.stopMetricStreams(parseNamesJson(request.path("Names")), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private List<String> parseNamesJson(JsonNode node) {+ List<String> names = new ArrayList<>();+ if (node.isArray()) {+ node.forEach(n -> names.add(n.asText()));+ }+ return names;+ }++ private ArrayNode streamFiltersNode(List<MetricStreamFilter> filters) {+ ArrayNode array = objectMapper.createArrayNode();+ for (MetricStreamFilter filter : filters) {+ ObjectNode node = array.addObject();+ node.put("Namespace", filter.getNamespace());+ if (!filter.getMetricNames().isEmpty()) {+ ArrayNode metricNames = node.putArray("MetricNames");+ filter.getMetricNames().forEach(metricNames::add);+ }+ }+ return array;+ }++ private ArrayNode statisticsConfigurationsNode(List<MetricStreamStatisticsConfiguration> configurations) {+ ArrayNode array = objectMapper.createArrayNode();+ for (MetricStreamStatisticsConfiguration configuration : configurations) {+ ObjectNode node = array.addObject();+ ArrayNode includeMetrics = node.putArray("IncludeMetrics");+ for (var metric : configuration.getIncludeMetrics()) {+ includeMetrics.addObject()+ .put("Namespace", metric.namespace())+ .put("MetricName", metric.metricName());+ }+ ArrayNode additionalStatistics = node.putArray("AdditionalStatistics");+ configuration.getAdditionalStatistics().forEach(additionalStatistics::add);+ }+ return array;+ }++ private List<MetricStreamFilter> parseStreamFiltersJson(JsonNode node) {+ List<MetricStreamFilter> filters = new ArrayList<>();+ if (!node.isArray()) {+ return filters;+ }+ for (JsonNode entry : node) {+ List<String> metricNames = new ArrayList<>();+ entry.path("MetricNames").forEach(n -> metricNames.add(n.asText()));+ filters.add(new MetricStreamFilter(entry.path("Namespace").asText(null), metricNames));+ }+ return filters;+ }++ private List<MetricStreamStatisticsConfiguration> parseStatisticsConfigurationsJson(JsonNode node) {+ List<MetricStreamStatisticsConfiguration> configurations = new ArrayList<>();+ if (!node.isArray()) {+ return configurations;+ }+ for (JsonNode entry : node) {+ MetricStreamStatisticsConfiguration configuration = new MetricStreamStatisticsConfiguration();+ List<MetricStreamStatisticsConfiguration.IncludeMetric> includeMetrics = new ArrayList<>();+ entry.path("IncludeMetrics").forEach(m -> includeMetrics.add(+ new MetricStreamStatisticsConfiguration.IncludeMetric(+ m.path("Namespace").asText(null), m.path("MetricName").asText(null))));+ configuration.setIncludeMetrics(includeMetrics);+ List<String> additionalStatistics = new ArrayList<>();+ entry.path("AdditionalStatistics").forEach(s -> additionalStatistics.add(s.asText()));+ configuration.setAdditionalStatistics(additionalStatistics);+ configurations.add(configuration);+ }+ return configurations;+ }+private List<MetricDatum> parseMetricDataJson(JsonNode node) {List<MetricDatum> datums = new ArrayList<>();if (!node.isArray()) return datums;diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.javaindex 9f6067389f..982f4e89ae 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java@@ -2,9 +2,15 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.AwsQueryResponse;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;import io.github.hectorvent.floci.core.common.XmlBuilder;import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;@@ -27,12 +33,15 @@ public class CloudWatchMetricsQueryHandler {private CloudWatchMetricsService metricsService;private final CloudWatchDashboardsService dashboardsService;+ private final CloudWatchMetricStreamsService metricStreamsService;@Injectpublic CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService,- CloudWatchDashboardsService dashboardsService) {+ CloudWatchDashboardsService dashboardsService,+ CloudWatchMetricStreamsService metricStreamsService) {this.metricsService = metricsService;this.dashboardsService = dashboardsService;+ this.metricStreamsService = metricStreamsService;}public Response handle(String action, MultivaluedMap<String, String> params, String region) {@@ -53,6 +62,12 @@ public class CloudWatchMetricsQueryHandler {case "GetDashboard" -> handleGetDashboard(params, region);case "ListDashboards" -> handleListDashboards(params, region);case "DeleteDashboards" -> handleDeleteDashboards(params, region);+ case "PutMetricStream" -> handlePutMetricStream(params, region);+ case "GetMetricStream" -> handleGetMetricStream(params, region);+ case "ListMetricStreams" -> handleListMetricStreams(params, region);+ case "DeleteMetricStream" -> handleDeleteMetricStream(params, region);+ case "StartMetricStreams" -> handleStartMetricStreams(params, region);+ case "StopMetricStreams" -> handleStopMetricStreams(params, region);default -> AwsQueryResponse.error("UnsupportedOperation","Operation " + action + " is not supported by CloudWatch Query.", AwsNamespaces.CW, 400);};@@ -263,9 +278,14 @@ public class CloudWatchMetricsQueryHandler {private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {String arn = params.getFirst("ResourceARN");- Map<String, String> tags = CloudWatchDashboardsService.isDashboardArn(arn)- ? dashboardsService.listTagsForResource(arn, region)- : metricsService.listTagsForResource(arn, region);+ Map<String, String> tags;+ if (CloudWatchDashboardsService.isDashboardArn(arn)) {+ tags = dashboardsService.listTagsForResource(arn, region);+ } else if (CloudWatchMetricStreamsService.isMetricStreamArn(arn)) {+ tags = metricStreamsService.listTagsForResource(arn, region);+ } else {+ tags = metricsService.listTagsForResource(arn, region);+ }XmlBuilder xml = new XmlBuilder().start("Tags");tags.forEach((k, v) -> xml.start("member").elem("Key", k).elem("Value", v).end("member"));xml.end("Tags");@@ -282,6 +302,8 @@ public class CloudWatchMetricsQueryHandler {}if (CloudWatchDashboardsService.isDashboardArn(arn)) {dashboardsService.tagResource(arn, tags, region);+ } else if (CloudWatchMetricStreamsService.isMetricStreamArn(arn)) {+ metricStreamsService.tagResource(arn, tags, region);} else {metricsService.tagResource(arn, tags, region);}@@ -301,6 +323,8 @@ public class CloudWatchMetricsQueryHandler {}if (CloudWatchDashboardsService.isDashboardArn(arn)) {dashboardsService.untagResource(arn, keys, region);+ } else if (CloudWatchMetricStreamsService.isMetricStreamArn(arn)) {+ metricStreamsService.untagResource(arn, keys, region);} else {metricsService.untagResource(arn, keys, region);}@@ -368,6 +392,201 @@ public class CloudWatchMetricsQueryHandler {return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteDashboards", null)).build();}+ // ──────────────────────────── Metric Streams ────────────────────────────++ private Response handlePutMetricStream(MultivaluedMap<String, String> params, String region) {+ MetricStream stream = new MetricStream();+ stream.setName(params.getFirst("Name"));+ stream.setFirehoseArn(params.getFirst("FirehoseArn"));+ stream.setRoleArn(params.getFirst("RoleArn"));+ stream.setOutputFormat(params.getFirst("OutputFormat"));+ stream.setIncludeLinkedAccountsMetrics(+ Boolean.parseBoolean(params.getFirst("IncludeLinkedAccountsMetrics")));+ stream.setIncludeFilters(parseStreamFilters(params, "IncludeFilters"));+ stream.setExcludeFilters(parseStreamFilters(params, "ExcludeFilters"));+ stream.setStatisticsConfigurations(parseStatisticsConfigurations(params));+ Map<String, String> tags = new LinkedHashMap<>();+ for (int i = 1; ; i++) {+ String key = params.getFirst("Tags.member." + i + ".Key");+ if (key == null) {+ break;+ }+ tags.put(key, params.getFirst("Tags.member." + i + ".Value"));+ }+ stream.setTags(tags);++ MetricStream stored = metricStreamsService.putMetricStream(stream, region);+ String xml = new XmlBuilder().elem("Arn", stored.getArn()).build();+ return Response.ok(AwsQueryResponse.envelope("PutMetricStream", null, xml)).build();+ }++ private Response handleGetMetricStream(MultivaluedMap<String, String> params, String region) {+ MetricStream stream = metricStreamsService.getMetricStream(params.getFirst("Name"), region);+ DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;+ XmlBuilder xml = new XmlBuilder()+ .elem("Arn", stream.getArn())+ .elem("Name", stream.getName())+ .elem("FirehoseArn", stream.getFirehoseArn())+ .elem("RoleArn", stream.getRoleArn())+ .elem("State", stream.getState())+ .elem("OutputFormat", stream.getOutputFormat())+ .elem("CreationDate", fmt.format(Instant.ofEpochSecond(stream.getCreationDate())))+ .elem("LastUpdateDate", fmt.format(Instant.ofEpochSecond(stream.getLastUpdateDate())))+ .elem("IncludeLinkedAccountsMetrics", stream.isIncludeLinkedAccountsMetrics());+ appendStreamFilters(xml, "IncludeFilters", stream.getIncludeFilters());+ appendStreamFilters(xml, "ExcludeFilters", stream.getExcludeFilters());+ appendStatisticsConfigurations(xml, stream.getStatisticsConfigurations());+ return Response.ok(AwsQueryResponse.envelope("GetMetricStream", null, xml.build())).build();+ }++ private Response handleListMetricStreams(MultivaluedMap<String, String> params, String region) {+ PaginatedResult<MetricStream> page = metricStreamsService.listMetricStreams(+ Pagination.parseMaxResults(params.getFirst("MaxResults"), "InvalidParameterValue"),+ params.getFirst("NextToken"), region);+ DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;+ XmlBuilder xml = new XmlBuilder().start("Entries");+ for (MetricStream stream : page.items()) {+ xml.start("member")+ .elem("Arn", stream.getArn())+ .elem("Name", stream.getName())+ .elem("FirehoseArn", stream.getFirehoseArn())+ .elem("State", stream.getState())+ .elem("OutputFormat", stream.getOutputFormat())+ .elem("CreationDate", fmt.format(Instant.ofEpochSecond(stream.getCreationDate())))+ .elem("LastUpdateDate", fmt.format(Instant.ofEpochSecond(stream.getLastUpdateDate())))+ .end("member");+ }+ xml.end("Entries");+ if (page.nextToken() != null) {+ xml.elem("NextToken", page.nextToken());+ }+ return Response.ok(AwsQueryResponse.envelope("ListMetricStreams", null, xml.build())).build();+ }++ private Response handleDeleteMetricStream(MultivaluedMap<String, String> params, String region) {+ metricStreamsService.deleteMetricStream(params.getFirst("Name"), region);+ return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteMetricStream", null)).build();+ }++ private Response handleStartMetricStreams(MultivaluedMap<String, String> params, String region) {+ metricStreamsService.startMetricStreams(parseNames(params), region);+ return Response.ok(AwsQueryResponse.envelopeEmptyResult("StartMetricStreams", null)).build();+ }++ private Response handleStopMetricStreams(MultivaluedMap<String, String> params, String region) {+ metricStreamsService.stopMetricStreams(parseNames(params), region);+ return Response.ok(AwsQueryResponse.envelopeEmptyResult("StopMetricStreams", null)).build();+ }++ private List<String> parseNames(MultivaluedMap<String, String> params) {+ List<String> names = new ArrayList<>();+ for (int i = 1; ; i++) {+ String name = params.getFirst("Names.member." + i);+ if (name == null) {+ break;+ }+ names.add(name);+ }+ return names;+ }++ private void appendStreamFilters(XmlBuilder xml, String element, List<MetricStreamFilter> filters) {+ if (filters.isEmpty()) {+ return;+ }+ xml.start(element);+ for (MetricStreamFilter filter : filters) {+ xml.start("member").elem("Namespace", filter.getNamespace());+ if (!filter.getMetricNames().isEmpty()) {+ xml.start("MetricNames");+ for (String metricName : filter.getMetricNames()) {+ xml.elem("member", metricName);+ }+ xml.end("MetricNames");+ }+ xml.end("member");+ }+ xml.end(element);+ }++ private void appendStatisticsConfigurations(XmlBuilder xml,+ List<MetricStreamStatisticsConfiguration> configurations) {+ if (configurations.isEmpty()) {+ return;+ }+ xml.start("StatisticsConfigurations");+ for (MetricStreamStatisticsConfiguration configuration : configurations) {+ xml.start("member").start("IncludeMetrics");+ for (var metric : configuration.getIncludeMetrics()) {+ xml.start("member")+ .elem("Namespace", metric.namespace())+ .elem("MetricName", metric.metricName())+ .end("member");+ }+ xml.end("IncludeMetrics").start("AdditionalStatistics");+ for (String stat : configuration.getAdditionalStatistics()) {+ xml.elem("member", stat);+ }+ xml.end("AdditionalStatistics").end("member");+ }+ xml.end("StatisticsConfigurations");+ }++ private List<MetricStreamFilter> parseStreamFilters(MultivaluedMap<String, String> params, String prefix) {+ List<MetricStreamFilter> filters = new ArrayList<>();+ for (int i = 1; ; i++) {+ String base = prefix + ".member." + i;+ String namespace = params.getFirst(base + ".Namespace");+ if (namespace == null) {+ break;+ }+ List<String> metricNames = new ArrayList<>();+ for (int j = 1; ; j++) {+ String metricName = params.getFirst(base + ".MetricNames.member." + j);+ if (metricName == null) {+ break;+ }+ metricNames.add(metricName);+ }+ filters.add(new MetricStreamFilter(namespace, metricNames));+ }+ return filters;+ }++ private List<MetricStreamStatisticsConfiguration> parseStatisticsConfigurations(+ MultivaluedMap<String, String> params) {+ List<MetricStreamStatisticsConfiguration> configurations = new ArrayList<>();+ for (int i = 1; ; i++) {+ String base = "StatisticsConfigurations.member." + i;+ if (params.getFirst(base + ".IncludeMetrics.member.1.Namespace") == null+ && params.getFirst(base + ".AdditionalStatistics.member.1") == null) {+ break;+ }+ MetricStreamStatisticsConfiguration configuration = new MetricStreamStatisticsConfiguration();+ List<MetricStreamStatisticsConfiguration.IncludeMetric> includeMetrics = new ArrayList<>();+ for (int j = 1; ; j++) {+ String namespace = params.getFirst(base + ".IncludeMetrics.member." + j + ".Namespace");+ if (namespace == null) {+ break;+ }+ includeMetrics.add(new MetricStreamStatisticsConfiguration.IncludeMetric(namespace,+ params.getFirst(base + ".IncludeMetrics.member." + j + ".MetricName")));+ }+ configuration.setIncludeMetrics(includeMetrics);+ List<String> additionalStatistics = new ArrayList<>();+ for (int j = 1; ; j++) {+ String stat = params.getFirst(base + ".AdditionalStatistics.member." + j);+ if (stat == null) {+ break;+ }+ additionalStatistics.add(stat);+ }+ configuration.setAdditionalStatistics(additionalStatistics);+ configurations.add(configuration);+ }+ return configurations;+ }+// ──────────────────────────── Parsing Helpers ────────────────────────────private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsService.javanew file mode 100644index 0000000000..4f3ba3c23c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsService.java@@ -0,0 +1,236 @@+package io.github.hectorvent.floci.services.cloudwatch.metricstreams;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;++/**+ * CloudWatch metric streams. A stream is pure metadata here: Floci stores the definition and+ * its running or stopped state and never delivers metrics to the Firehose delivery stream it+ * names, so there is no backing behaviour behind the record.+ */+@ApplicationScoped+public class CloudWatchMetricStreamsService {++ private static final Logger LOG = Logger.getLogger(CloudWatchMetricStreamsService.class);++ /** The OutputFormat values PutMetricStream documents. */+ private static final Set<String> OUTPUT_FORMATS = Set.of("json", "opentelemetry0.7", "opentelemetry1.0");++ /** ListMetricStreams documents MaxResults as 1 to 500. */+ private static final int MAX_PAGE = 500;++ private final StorageBackend<String, MetricStream> streamStore;+ private final RegionResolver regionResolver;++ @Inject+ public CloudWatchMetricStreamsService(StorageFactory storageFactory, RegionResolver regionResolver) {+ this.streamStore = storageFactory.create("cloudwatchmetrics", "cwmetricstreams.json",+ new TypeReference<Map<String, MetricStream>>() {});+ this.regionResolver = regionResolver;+ }++ // Public rather than package-private so handler tests in the metrics package can build+ // the service over an InMemoryStorage without standing up Quarkus.+ public CloudWatchMetricStreamsService(StorageBackend<String, MetricStream> streamStore,+ RegionResolver regionResolver) {+ this.streamStore = streamStore;+ this.regionResolver = regionResolver;+ }++ /**+ * Creates the stream, or updates the definition when the name is already taken.+ *+ * <p>An update keeps the creation date, the state and the tags of the existing stream. AWS+ * documents Tags on PutMetricStream as applying to a new stream only, so a Put that updates+ * an existing one ignores the tags on the request.+ */+ public MetricStream putMetricStream(MetricStream stream, String region) {+ requireParameter(stream.getName(), "Name");+ requireParameter(stream.getFirehoseArn(), "FirehoseArn");+ requireParameter(stream.getRoleArn(), "RoleArn");+ requireParameter(stream.getOutputFormat(), "OutputFormat");+ if (!OUTPUT_FORMATS.contains(stream.getOutputFormat())) {+ throw new AwsException("InvalidParameterValue",+ "OutputFormat must be one of json, opentelemetry0.7 or opentelemetry1.0.", 400);+ }+ if (!stream.getIncludeFilters().isEmpty() && !stream.getExcludeFilters().isEmpty()) {+ throw new AwsException("InvalidParameterCombination",+ "IncludeFilters and ExcludeFilters cannot both be specified.", 400);+ }+ validateFilters(stream.getIncludeFilters(), "IncludeFilters");+ validateFilters(stream.getExcludeFilters(), "ExcludeFilters");+ validateStatisticsConfigurations(stream.getStatisticsConfigurations());++ long now = Instant.now().getEpochSecond();+ MetricStream existing = streamStore.get(key(region, stream.getName())).orElse(null);+ if (existing != null) {+ stream.setCreationDate(existing.getCreationDate());+ stream.setState(existing.getState());+ stream.setTags(new LinkedHashMap<>(existing.getTags()));+ } else {+ stream.setCreationDate(now);+ stream.setState(MetricStream.STATE_RUNNING);+ }+ stream.setLastUpdateDate(now);+ stream.setArn(regionResolver.buildArn("cloudwatch", region, "metric-stream/" + stream.getName()));+ streamStore.put(key(region, stream.getName()), stream);+ LOG.debugv("PutMetricStream: {0} in {1}", stream.getName(), region);+ return stream;+ }++ public MetricStream getMetricStream(String name, String region) {+ requireParameter(name, "Name");+ return streamStore.get(key(region, name)).orElseThrow(() -> notFound(name));+ }++ /** Deleting a stream that is not there is a no-op, which is how AWS answers it. */+ public void deleteMetricStream(String name, String region) {+ requireParameter(name, "Name");+ streamStore.delete(key(region, name));+ LOG.debugv("DeleteMetricStream: {0} in {1}", name, region);+ }++ public List<MetricStream> listMetricStreams(String region) {+ return streamStore.scan(k -> k.startsWith(region + "::")).stream()+ .sorted(Comparator.comparing(MetricStream::getName))+ .toList();+ }++ /**+ * One page of the region's streams in name order. The token is the shared opaque cursor,+ * so a page stays resumable when streams are added or removed between requests.+ */+ public PaginatedResult<MetricStream> listMetricStreams(Integer maxResults, String nextToken, String region) {+ return Pagination.paginate(listMetricStreams(region), MetricStream::getName,+ maxResults, nextToken, MAX_PAGE, "InvalidNextToken");+ }++ public void startMetricStreams(List<String> names, String region) {+ setState(names, MetricStream.STATE_RUNNING, region);+ }++ public void stopMetricStreams(List<String> names, String region) {+ setState(names, MetricStream.STATE_STOPPED, region);+ }++ /**+ * Every named stream is resolved before any is changed, so a batch that names a missing+ * stream fails as a whole instead of leaving the earlier names already switched. The model+ * declares ResourceNotFoundException on GetMetricStream alone, so an unknown name here is+ * InvalidParameterValue.+ */+ private void setState(List<String> names, String state, String region) {+ if (names == null || names.isEmpty()) {+ throw new AwsException("MissingParameter", "The parameter Names is required.", 400);+ }+ List<MetricStream> streams = new ArrayList<>();+ for (String name : names) {+ streams.add(streamStore.get(key(region, name)).orElseThrow(() ->+ new AwsException("InvalidParameterValue",+ "Metric stream " + name + " does not exist.", 400)));+ }+ long now = Instant.now().getEpochSecond();+ for (MetricStream stream : streams) {+ stream.setState(state);+ stream.setLastUpdateDate(now);+ streamStore.put(key(region, stream.getName()), stream);+ }+ LOG.debugv("Metric streams {0} in {1} are now {2}", names, region, state);+ }++ private static void validateFilters(List<MetricStreamFilter> filters, String element) {+ for (MetricStreamFilter filter : filters) {+ if (filter.getNamespace() == null || filter.getNamespace().isBlank()) {+ throw new AwsException("MissingParameter",+ "Each member of " + element + " requires a Namespace.", 400);+ }+ }+ }++ private static void validateStatisticsConfigurations(List<MetricStreamStatisticsConfiguration> configurations) {+ for (MetricStreamStatisticsConfiguration configuration : configurations) {+ if (configuration.getIncludeMetrics().isEmpty()) {+ throw new AwsException("InvalidParameterValue",+ "Each member of StatisticsConfigurations requires at least one IncludeMetrics entry.", 400);+ }+ if (configuration.getAdditionalStatistics().isEmpty()) {+ throw new AwsException("InvalidParameterValue",+ "Each member of StatisticsConfigurations requires at least one AdditionalStatistics entry.", 400);+ }+ for (var metric : configuration.getIncludeMetrics()) {+ if (metric.namespace() == null || metric.namespace().isBlank()+ || metric.metricName() == null || metric.metricName().isBlank()) {+ throw new AwsException("MissingParameter",+ "Each IncludeMetrics entry requires a Namespace and a MetricName.", 400);+ }+ }+ }+ }++ /**+ * Whether an ARN names a metric stream. CloudWatch's tag operations take one ARN for every+ * taggable resource it owns, so the handler needs to know which service should answer.+ */+ public static boolean isMetricStreamArn(String resourceArn) {+ return resourceArn != null && resourceArn.contains(":metric-stream/");+ }++ public Map<String, String> listTagsForResource(String resourceArn, String region) {+ return findByArn(resourceArn, region).map(MetricStream::getTags).orElse(Map.of());+ }++ public void tagResource(String resourceArn, Map<String, String> tags, String region) {+ findByArn(resourceArn, region).ifPresent(stream -> {+ stream.getTags().putAll(tags);+ streamStore.put(key(region, stream.getName()), stream);+ });+ }++ public void untagResource(String resourceArn, List<String> tagKeys, String region) {+ findByArn(resourceArn, region).ifPresent(stream -> {+ tagKeys.forEach(stream.getTags()::remove);+ streamStore.put(key(region, stream.getName()), stream);+ });+ }++ private Optional<MetricStream> findByArn(String resourceArn, String region) {+ return streamStore.scan(k -> k.startsWith(region + "::")).stream()+ .filter(s -> resourceArn.equals(s.getArn()))+ .findFirst();+ }++ private static void requireParameter(String value, String name) {+ if (value == null || value.isBlank()) {+ throw new AwsException("MissingParameter", "The parameter " + name + " is required.", 400);+ }+ }++ private static String key(String region, String name) {+ return region + "::" + name;+ }++ private static AwsException notFound(String name) {+ return new AwsException("ResourceNotFoundException",+ "Metric stream " + name + " does not exist.", 404);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStream.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStream.javanew file mode 100644index 0000000000..ab5cca4513--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStream.java@@ -0,0 +1,87 @@+package io.github.hectorvent.floci.services.cloudwatch.metricstreams.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * A CloudWatch metric stream. Floci stores the definition and reports its state; no metric+ * data is ever delivered to the configured Firehose delivery stream.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class MetricStream {++ public static final String STATE_RUNNING = "running";+ public static final String STATE_STOPPED = "stopped";++ private String name;+ private String arn;+ private String firehoseArn;+ private String roleArn;+ private String outputFormat;+ private String state = STATE_RUNNING;+ private long creationDate;+ private long lastUpdateDate;+ private boolean includeLinkedAccountsMetrics;+ private List<MetricStreamFilter> includeFilters = new ArrayList<>();+ private List<MetricStreamFilter> excludeFilters = new ArrayList<>();+ private List<MetricStreamStatisticsConfiguration> statisticsConfigurations = new ArrayList<>();+ private Map<String, String> tags = new LinkedHashMap<>();++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getFirehoseArn() { return firehoseArn; }+ public void setFirehoseArn(String firehoseArn) { this.firehoseArn = firehoseArn; }++ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }++ public String getOutputFormat() { return outputFormat; }+ public void setOutputFormat(String outputFormat) { this.outputFormat = outputFormat; }++ public String getState() { return state; }+ public void setState(String state) { this.state = state; }++ public long getCreationDate() { return creationDate; }+ public void setCreationDate(long creationDate) { this.creationDate = creationDate; }++ public long getLastUpdateDate() { return lastUpdateDate; }+ public void setLastUpdateDate(long lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; }++ public boolean isIncludeLinkedAccountsMetrics() { return includeLinkedAccountsMetrics; }+ public void setIncludeLinkedAccountsMetrics(boolean includeLinkedAccountsMetrics) {+ this.includeLinkedAccountsMetrics = includeLinkedAccountsMetrics;+ }++ public List<MetricStreamFilter> getIncludeFilters() { return includeFilters; }+ public void setIncludeFilters(List<MetricStreamFilter> includeFilters) {+ this.includeFilters = includeFilters != null ? includeFilters : new ArrayList<>();+ }++ public List<MetricStreamFilter> getExcludeFilters() { return excludeFilters; }+ public void setExcludeFilters(List<MetricStreamFilter> excludeFilters) {+ this.excludeFilters = excludeFilters != null ? excludeFilters : new ArrayList<>();+ }++ public List<MetricStreamStatisticsConfiguration> getStatisticsConfigurations() {+ return statisticsConfigurations;+ }+ public void setStatisticsConfigurations(List<MetricStreamStatisticsConfiguration> statisticsConfigurations) {+ this.statisticsConfigurations = statisticsConfigurations != null+ ? statisticsConfigurations : new ArrayList<>();+ }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) {+ this.tags = tags != null ? tags : new LinkedHashMap<>();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStreamFilter.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStreamFilter.javanew file mode 100644index 0000000000..45247b838b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStreamFilter.java@@ -0,0 +1,32 @@+package io.github.hectorvent.floci.services.cloudwatch.metricstreams.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.List;++/** One entry of a metric stream's {@code IncludeFilters} or {@code ExcludeFilters}. */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class MetricStreamFilter {++ private String namespace;+ private List<String> metricNames = new ArrayList<>();++ public MetricStreamFilter() {+ }++ public MetricStreamFilter(String namespace, List<String> metricNames) {+ this.namespace = namespace;+ this.metricNames = metricNames != null ? metricNames : new ArrayList<>();+ }++ public String getNamespace() { return namespace; }+ public void setNamespace(String namespace) { this.namespace = namespace; }++ public List<String> getMetricNames() { return metricNames; }+ public void setMetricNames(List<String> metricNames) {+ this.metricNames = metricNames != null ? metricNames : new ArrayList<>();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStreamStatisticsConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStreamStatisticsConfiguration.javanew file mode 100644index 0000000000..40f1f822f7--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/model/MetricStreamStatisticsConfiguration.java@@ -0,0 +1,31 @@+package io.github.hectorvent.floci.services.cloudwatch.metricstreams.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.List;++/** One entry of a metric stream's {@code StatisticsConfigurations}. */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class MetricStreamStatisticsConfiguration {++ /** A single {@code IncludeMetrics} entry, a namespace plus a metric name. */+ @RegisterForReflection+ @JsonIgnoreProperties(ignoreUnknown = true)+ public record IncludeMetric(String namespace, String metricName) {}++ private List<IncludeMetric> includeMetrics = new ArrayList<>();+ private List<String> additionalStatistics = new ArrayList<>();++ public List<IncludeMetric> getIncludeMetrics() { return includeMetrics; }+ public void setIncludeMetrics(List<IncludeMetric> includeMetrics) {+ this.includeMetrics = includeMetrics != null ? includeMetrics : new ArrayList<>();+ }++ public List<String> getAdditionalStatistics() { return additionalStatistics; }+ public void setAdditionalStatistics(List<String> additionalStatistics) {+ this.additionalStatistics = additionalStatistics != null ? additionalStatistics : new ArrayList<>();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.javanew file mode 100644index 0000000000..e7d71a04b6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricStreamsHandlerTest.java@@ -0,0 +1,231 @@+package io.github.hectorvent.floci.services.cloudwatch.metrics;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;+import jakarta.ws.rs.core.MultivaluedHashMap;+import jakarta.ws.rs.core.MultivaluedMap;+import jakarta.ws.rs.core.Response;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;++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;++/**+ * Both CloudWatch handlers must serve the metric stream operations with the same semantics,+ * since the Terraform provider speaks Query and the CLI and SDK v3 speak JSON.+ */+class CloudWatchMetricStreamsHandlerTest {++ private static final String REGION = "us-east-1";+ private static final ObjectMapper MAPPER = new ObjectMapper();++ private CloudWatchMetricStreamsService streamsService;+ private CloudWatchMetricsQueryHandler queryHandler;+ private CloudWatchMetricsJsonHandler jsonHandler;++ @BeforeEach+ void setUp() {+ RegionResolver resolver = new RegionResolver(REGION, "000000000000");+ CloudWatchMetricsService metricsService = new CloudWatchMetricsService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), resolver);+ 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);+ }++ private static MultivaluedMap<String, String> putParams(String name) {+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("Name", name);+ params.add("FirehoseArn", "arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics");+ params.add("RoleArn", "arn:aws:iam::000000000000:role/metric-stream-role");+ params.add("OutputFormat", "json");+ params.add("ExcludeFilters.member.1.Namespace", "AWS/S3");+ params.add("ExcludeFilters.member.1.MetricNames.member.1", "BucketSizeBytes");+ params.add("StatisticsConfigurations.member.1.IncludeMetrics.member.1.Namespace", "AWS/EC2");+ params.add("StatisticsConfigurations.member.1.IncludeMetrics.member.1.MetricName", "CPUUtilization");+ params.add("StatisticsConfigurations.member.1.AdditionalStatistics.member.1", "p99");+ return params;+ }++ private String query(String action, MultivaluedMap<String, String> params) {+ Response response = queryHandler.handle(action, params, REGION);+ assertEquals(200, response.getStatus());+ return (String) response.getEntity();+ }++ @Test+ void queryPutParsesTheNestedMembersAndAnswersWithTheArn() {+ String xml = query("PutMetricStream", putParams("stream-a"));++ assertTrue(xml.contains("<PutMetricStreamResult>"));+ assertTrue(xml.contains("<Arn>arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/stream-a</Arn>"));++ MetricStream stored = streamsService.getMetricStream("stream-a", REGION);+ assertEquals("AWS/S3", stored.getExcludeFilters().get(0).getNamespace());+ assertEquals(List.of("BucketSizeBytes"), stored.getExcludeFilters().get(0).getMetricNames());+ assertEquals("CPUUtilization",+ stored.getStatisticsConfigurations().get(0).getIncludeMetrics().get(0).metricName());+ assertEquals(List.of("p99"), stored.getStatisticsConfigurations().get(0).getAdditionalStatistics());+ }++ @Test+ void queryGetRendersFiltersAndStatisticsConfigurations() {+ query("PutMetricStream", putParams("stream-b"));++ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("Name", "stream-b");+ String xml = query("GetMetricStream", params);++ assertTrue(xml.contains("<GetMetricStreamResult>"));+ assertTrue(xml.contains("<Name>stream-b</Name>"));+ assertTrue(xml.contains("<State>running</State>"));+ assertTrue(xml.contains("<IncludeLinkedAccountsMetrics>false</IncludeLinkedAccountsMetrics>"));+ assertTrue(xml.contains("<ExcludeFilters><member><Namespace>AWS/S3</Namespace>"+ + "<MetricNames><member>BucketSizeBytes</member></MetricNames></member></ExcludeFilters>"));+ assertTrue(xml.contains("<AdditionalStatistics><member>p99</member></AdditionalStatistics>"));+ assertFalse(xml.contains("<IncludeFilters>"));+ }++ @Test+ void queryListStopStartAndDeleteRoundTrip() {+ query("PutMetricStream", putParams("stream-c"));+ query("PutMetricStream", putParams("stream-d"));++ String list = query("ListMetricStreams", new MultivaluedHashMap<>());+ assertTrue(list.contains("<Entries><member><Arn>"));+ assertTrue(list.contains("<Name>stream-c</Name>"));+ assertTrue(list.contains("<Name>stream-d</Name>"));++ MultivaluedMap<String, String> names = new MultivaluedHashMap<>();+ names.add("Names.member.1", "stream-c");+ names.add("Names.member.2", "stream-d");+ assertTrue(query("StopMetricStreams", names).contains("<StopMetricStreamsResult"));+ assertEquals(MetricStream.STATE_STOPPED, streamsService.getMetricStream("stream-d", REGION).getState());+ assertTrue(query("StartMetricStreams", names).contains("<StartMetricStreamsResult"));+ assertEquals(MetricStream.STATE_RUNNING, streamsService.getMetricStream("stream-d", REGION).getState());++ MultivaluedMap<String, String> delete = new MultivaluedHashMap<>();+ delete.add("Name", "stream-c");+ assertTrue(query("DeleteMetricStream", delete).contains("<DeleteMetricStreamResult"));+ assertEquals(1, streamsService.listMetricStreams(REGION).size());+ }++ @Test+ void bothProtocolsPageTheListWithMaxResultsAndNextToken() throws Exception {+ query("PutMetricStream", putParams("page-a"));+ query("PutMetricStream", putParams("page-b"));+ query("PutMetricStream", putParams("page-c"));++ MultivaluedMap<String, String> first = new MultivaluedHashMap<>();+ first.add("MaxResults", "2");+ String xml = query("ListMetricStreams", first);+ assertTrue(xml.contains("<Name>page-a</Name>"));+ assertTrue(xml.contains("<Name>page-b</Name>"));+ assertFalse(xml.contains("<Name>page-c</Name>"));+ String token = xml.substring(xml.indexOf("<NextToken>") + "<NextToken>".length(), xml.indexOf("</NextToken>"));++ JsonNode second = MAPPER.valueToTree(jsonHandler.handle("ListMetricStreams",+ MAPPER.readTree("{\"MaxResults\": 2, \"NextToken\": \"" + token + "\"}"), REGION).getEntity());+ assertEquals(1, second.path("Entries").size());+ assertEquals("page-c", second.path("Entries").get(0).path("Name").asText());+ assertFalse(second.has("NextToken"));++ // The Query controller renders AwsException as the XML error envelope.+ AwsException bad = assertThrows(AwsException.class,+ () -> queryHandler.handle("ListMetricStreams", withToken("not base64!"), REGION));+ assertEquals("InvalidNextToken", bad.getErrorCode());+ }++ private static MultivaluedMap<String, String> withToken(String token) {+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("NextToken", token);+ return params;+ }++ @Test+ void queryTagOperationsRouteAMetricStreamArn() {+ MultivaluedMap<String, String> params = putParams("stream-e");+ params.add("Tags.member.1.Key", "team");+ params.add("Tags.member.1.Value", "platform");+ query("PutMetricStream", params);+ String arn = streamsService.getMetricStream("stream-e", REGION).getArn();++ MultivaluedMap<String, String> tag = new MultivaluedHashMap<>();+ tag.add("ResourceARN", arn);+ tag.add("Tags.member.1.Key", "owner");+ tag.add("Tags.member.1.Value", "ops");+ query("TagResource", tag);++ MultivaluedMap<String, String> list = new MultivaluedHashMap<>();+ list.add("ResourceARN", arn);+ String xml = query("ListTagsForResource", list);+ assertTrue(xml.contains("<Key>team</Key><Value>platform</Value>"));+ assertTrue(xml.contains("<Key>owner</Key><Value>ops</Value>"));++ MultivaluedMap<String, String> untag = new MultivaluedHashMap<>();+ untag.add("ResourceARN", arn);+ untag.add("TagKeys.member.1", "team");+ query("UntagResource", untag);+ assertFalse(query("ListTagsForResource", list).contains("<Key>team</Key>"));+ }++ @Test+ void jsonHandlerRoundTripsAStream() throws Exception {+ JsonNode request = MAPPER.readTree("""+ {+ "Name": "json-stream",+ "FirehoseArn": "arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics",+ "RoleArn": "arn:aws:iam::000000000000:role/metric-stream-role",+ "OutputFormat": "opentelemetry1.0",+ "IncludeLinkedAccountsMetrics": true,+ "IncludeFilters": [{"Namespace": "AWS/Lambda", "MetricNames": ["Errors"]}],+ "StatisticsConfigurations": [+ {"IncludeMetrics": [{"Namespace": "AWS/EC2", "MetricName": "CPUUtilization"}],+ "AdditionalStatistics": ["p99"]}+ ],+ "Tags": [{"Key": "team", "Value": "platform"}]+ }+ """);+ JsonNode put = MAPPER.valueToTree(jsonHandler.handle("PutMetricStream", request, REGION).getEntity());+ assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/json-stream", put.path("Arn").asText());++ JsonNode get = MAPPER.valueToTree(jsonHandler.handle("GetMetricStream",+ MAPPER.readTree("{\"Name\": \"json-stream\"}"), REGION).getEntity());+ assertEquals("json-stream", get.path("Name").asText());+ assertEquals("running", get.path("State").asText());+ assertEquals("opentelemetry1.0", get.path("OutputFormat").asText());+ assertTrue(get.path("IncludeLinkedAccountsMetrics").asBoolean());+ assertTrue(get.path("CreationDate").isNumber());+ assertEquals("AWS/Lambda", get.path("IncludeFilters").get(0).path("Namespace").asText());+ assertEquals("Errors", get.path("IncludeFilters").get(0).path("MetricNames").get(0).asText());+ assertFalse(get.has("ExcludeFilters"));+ assertEquals("p99",+ get.path("StatisticsConfigurations").get(0).path("AdditionalStatistics").get(0).asText());++ JsonNode tags = MAPPER.valueToTree(jsonHandler.handle("ListTagsForResource",+ MAPPER.readTree("{\"ResourceARN\": \"" + put.path("Arn").asText() + "\"}"), REGION).getEntity());+ assertEquals("team", tags.path("Tags").get(0).path("Key").asText());++ jsonHandler.handle("StopMetricStreams", MAPPER.readTree("{\"Names\": [\"json-stream\"]}"), REGION);+ JsonNode list = MAPPER.valueToTree(jsonHandler.handle("ListMetricStreams",+ MAPPER.createObjectNode(), REGION).getEntity());+ assertEquals(1, list.path("Entries").size());+ assertEquals("stopped", list.path("Entries").get(0).path("State").asText());++ jsonHandler.handle("DeleteMetricStream", MAPPER.readTree("{\"Name\": \"json-stream\"}"), REGION);+ assertTrue(streamsService.listMetricStreams(REGION).isEmpty());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.javaindex b5f4ae5c0b..58bdd50007 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java@@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;import jakarta.ws.rs.core.Response;import java.math.BigDecimal;import java.time.Instant;@@ -46,7 +47,9 @@ class CloudWatchMetricsJsonHandlerTest {new InMemoryStorage<>(),new RegionResolver(REGION, "000000000000"));- handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, MAPPER);+ CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService(+ new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));+ handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, MAPPER);}/**diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.javaindex b75390ee7a..ae958af8b6 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.cloudwatch.metrics;import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.MultivaluedMap;@@ -27,7 +28,8 @@ class CloudWatchMetricsQueryHandlerTest {private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);// The alarm cases below never reach a dashboard operation; the handler simply routes both.private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(- metricsService, mock(CloudWatchDashboardsService.class));+ metricsService, mock(CloudWatchDashboardsService.class),+ mock(CloudWatchMetricStreamsService.class));@Testvoid putMetricAlarmDefaultsActionsEnabledToTrueWhenOmitted() {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.javaindex e5c585e115..4112eb7202 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.MultivaluedMap;@@ -34,8 +35,10 @@ class CloudWatchMetricsTagsTest {);CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));- queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService);- jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, objectMapper);+ 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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsIntegrationTest.javanew file mode 100644index 0000000000..c37c672d4b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsIntegrationTest.java@@ -0,0 +1,300 @@+package io.github.hectorvent.floci.services.cloudwatch.metricstreams;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.RestAssured;+import io.restassured.config.EncoderConfig;+import io.restassured.http.ContentType;+import io.restassured.parsing.Parser;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.not;++/**+ * Metric streams reach the emulator over the Query protocol from the Terraform AWS provider+ * and over JSON with an X-Amz-Target header from the CLI and SDK v3. Both routes are covered.+ */+@QuarkusTest+class CloudWatchMetricStreamsIntegrationTest {++ private static final String CW_SCOPE =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/monitoring/aws4_request";++ private static final String JSON_1_0 = "application/x-amz-json-1.0";++ private static final String FIREHOSE_ARN =+ "arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics";+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/metric-stream-role";++ @BeforeAll+ static void registerJsonParser() {+ RestAssured.registerParser(JSON_1_0, Parser.JSON);+ }++ private static RequestSpecification query(String action) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", action);+ }++ // RestAssured has no built-in serializer for the x-amz-json content types; send raw text.+ private static RequestSpecification json(String target, String body) {+ return given()+ .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()+ .encodeContentTypeAs(JSON_1_0, ContentType.TEXT)))+ .contentType(JSON_1_0)+ .header("X-Amz-Target", "GraniteServiceVersion20100801." + target)+ .body(body);+ }++ private static String putStream(String name) {+ return query("PutMetricStream")+ .formParam("Name", name)+ .formParam("FirehoseArn", FIREHOSE_ARN)+ .formParam("RoleArn", ROLE_ARN)+ .formParam("OutputFormat", "json")+ .formParam("ExcludeFilters.member.1.Namespace", "AWS/S3")+ .formParam("ExcludeFilters.member.1.MetricNames.member.1", "BucketSizeBytes")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .contentType("application/xml")+ .body("PutMetricStreamResponse.PutMetricStreamResult.Arn",+ equalTo("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/" + name))+ .extract().path("PutMetricStreamResponse.PutMetricStreamResult.Arn");+ }++ @Test+ void putThenGetReturnsTheDefinition() {+ putStream("query-round-trip");++ query("GetMetricStream")+ .formParam("Name", "query-round-trip")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetMetricStreamResponse.GetMetricStreamResult.Name", equalTo("query-round-trip"))+ .body("GetMetricStreamResponse.GetMetricStreamResult.FirehoseArn", equalTo(FIREHOSE_ARN))+ .body("GetMetricStreamResponse.GetMetricStreamResult.RoleArn", equalTo(ROLE_ARN))+ .body("GetMetricStreamResponse.GetMetricStreamResult.State", equalTo("running"))+ .body("GetMetricStreamResponse.GetMetricStreamResult.OutputFormat", equalTo("json"))+ .body("GetMetricStreamResponse.GetMetricStreamResult.CreationDate", containsString("T"))+ .body("GetMetricStreamResponse.GetMetricStreamResult.ExcludeFilters.member.Namespace",+ equalTo("AWS/S3"))+ .body("GetMetricStreamResponse.GetMetricStreamResult.ExcludeFilters.member.MetricNames.member",+ equalTo("BucketSizeBytes"));+ }++ @Test+ void getUnknownStreamReturnsResourceNotFoundException() {+ query("GetMetricStream")+ .formParam("Name", "no-such-stream")+ .when()+ .post("/")+ .then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"));+ }++ @Test+ void stoppingAnUnknownStreamIsInvalidParameterValue() {+ query("StopMetricStreams")+ .formParam("Names.member.1", "no-such-stream")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));+ }++ @Test+ void putWithoutARoleIsMissingParameter() {+ query("PutMetricStream")+ .formParam("Name", "incomplete")+ .formParam("FirehoseArn", FIREHOSE_ARN)+ .formParam("OutputFormat", "json")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("MissingParameter"));+ }++ @Test+ void listStopStartAndDeleteOverQuery() {+ putStream("lifecycle-one");+ putStream("lifecycle-two");++ query("ListMetricStreams")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ListMetricStreamsResponse.ListMetricStreamsResult.Entries.member.Name",+ hasItem("lifecycle-one"))+ .body("ListMetricStreamsResponse.ListMetricStreamsResult.Entries.member.Name",+ hasItem("lifecycle-two"));++ query("StopMetricStreams")+ .formParam("Names.member.1", "lifecycle-one")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ query("GetMetricStream")+ .formParam("Name", "lifecycle-one")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetMetricStreamResponse.GetMetricStreamResult.State", equalTo("stopped"));++ query("StartMetricStreams")+ .formParam("Names.member.1", "lifecycle-one")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ query("GetMetricStream")+ .formParam("Name", "lifecycle-one")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetMetricStreamResponse.GetMetricStreamResult.State", equalTo("running"));++ query("DeleteMetricStream")+ .formParam("Name", "lifecycle-one")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ query("GetMetricStream")+ .formParam("Name", "lifecycle-one")+ .when()+ .post("/")+ .then()+ .statusCode(404);+ }++ @Test+ void listPagesOverBothProtocols() {+ putStream("paged-a");+ putStream("paged-b");++ String token = query("ListMetricStreams")+ .formParam("MaxResults", "1")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ListMetricStreamsResponse.ListMetricStreamsResult.NextToken", notNullValue())+ .extract().path("ListMetricStreamsResponse.ListMetricStreamsResult.NextToken");++ json("ListMetricStreams", "{\"MaxResults\": 1, \"NextToken\": \"" + token + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Entries", hasSize(1));++ query("ListMetricStreams")+ .formParam("NextToken", "not base64!")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidNextToken"));+ }++ @Test+ void tagsSuppliedOnPutAreReadableThroughListTagsForResource() {+ String arn = query("PutMetricStream")+ .formParam("Name", "tagged")+ .formParam("FirehoseArn", FIREHOSE_ARN)+ .formParam("RoleArn", ROLE_ARN)+ .formParam("OutputFormat", "json")+ .formParam("Tags.member.1.Key", "team")+ .formParam("Tags.member.1.Value", "platform")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("PutMetricStreamResponse.PutMetricStreamResult.Arn");++ query("ListTagsForResource")+ .formParam("ResourceARN", arn)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<Key>team</Key>"))+ .body(containsString("<Value>platform</Value>"));++ query("UntagResource")+ .formParam("ResourceARN", arn)+ .formParam("TagKeys.member.1", "team")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ query("ListTagsForResource")+ .formParam("ResourceARN", arn)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(not(containsString("<Key>team</Key>")));+ }++ @Test+ void theSameOperationsAreServedOverTheJsonProtocol() {+ json("PutMetricStream", "{\"Name\": \"json-round-trip\", \"FirehoseArn\": \"" + FIREHOSE_ARN+ + "\", \"RoleArn\": \"" + ROLE_ARN + "\", \"OutputFormat\": \"opentelemetry1.0\","+ + " \"IncludeFilters\": [{\"Namespace\": \"AWS/Lambda\", \"MetricNames\": [\"Errors\"]}]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Arn", equalTo("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/json-round-trip"));++ json("GetMetricStream", "{\"Name\": \"json-round-trip\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Name", equalTo("json-round-trip"))+ .body("State", equalTo("running"))+ .body("OutputFormat", equalTo("opentelemetry1.0"))+ .body("IncludeFilters[0].Namespace", equalTo("AWS/Lambda"))+ .body("IncludeFilters[0].MetricNames[0]", equalTo("Errors"));++ json("ListMetricStreams", "{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Entries.Name", hasItem("json-round-trip"));++ json("GetMetricStream", "{\"Name\": \"json-missing\"}")+ .when()+ .post("/")+ .then()+ .statusCode(404)+ .body("__type", containsString("ResourceNotFoundException"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsServiceTest.javanew file mode 100644index 0000000000..6648f466d4--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metricstreams/CloudWatchMetricStreamsServiceTest.java@@ -0,0 +1,235 @@+package io.github.hectorvent.floci.services.cloudwatch.metricstreams;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;+import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class CloudWatchMetricStreamsServiceTest {++ private static final String REGION = "us-east-1";++ private CloudWatchMetricStreamsService service;++ @BeforeEach+ void setUp() {+ service = new CloudWatchMetricStreamsService(+ new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));+ }++ private static MetricStream stream(String name) {+ MetricStream stream = new MetricStream();+ stream.setName(name);+ stream.setFirehoseArn("arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics");+ stream.setRoleArn("arn:aws:iam::000000000000:role/metric-stream-role");+ stream.setOutputFormat("json");+ return stream;+ }++ @Test+ void putStoresTheDefinitionRunningWithAnArn() {+ MetricStream stored = service.putMetricStream(stream("ops"), REGION);++ assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/ops", stored.getArn());+ assertEquals(MetricStream.STATE_RUNNING, stored.getState());+ assertTrue(stored.getCreationDate() > 0);+ assertEquals(stored.getCreationDate(), stored.getLastUpdateDate());+ assertEquals("json", service.getMetricStream("ops", REGION).getOutputFormat());+ }++ @Test+ void putOnExistingNameUpdatesTheDefinitionAndKeepsCreationStateAndTags() {+ MetricStream first = stream("ops");+ first.setTags(new LinkedHashMap<>(Map.of("env", "dev")));+ long createdAt = service.putMetricStream(first, REGION).getCreationDate();+ service.stopMetricStreams(List.of("ops"), REGION);++ MetricStream update = stream("ops");+ update.setOutputFormat("opentelemetry1.0");+ update.setTags(new LinkedHashMap<>(Map.of("env", "prod")));+ service.putMetricStream(update, REGION);++ MetricStream stored = service.getMetricStream("ops", REGION);+ assertEquals(createdAt, stored.getCreationDate());+ assertEquals("opentelemetry1.0", stored.getOutputFormat());+ assertEquals(MetricStream.STATE_STOPPED, stored.getState());+ assertEquals("dev", stored.getTags().get("env"));+ assertEquals(1, service.listMetricStreams(REGION).size());+ }++ @Test+ void putRequiresTheDocumentedParameters() {+ MetricStream missingRole = stream("ops");+ missingRole.setRoleArn(null);+ AwsException e = assertThrows(AwsException.class, () -> service.putMetricStream(missingRole, REGION));+ assertEquals("MissingParameter", e.getErrorCode());+ assertEquals(400, e.getHttpStatus());++ MetricStream badFormat = stream("ops");+ badFormat.setOutputFormat("csv");+ assertEquals("InvalidParameterValue",+ assertThrows(AwsException.class, () -> service.putMetricStream(badFormat, REGION)).getErrorCode());+ }++ @Test+ void putRejectsIncludeAndExcludeFiltersTogether() {+ MetricStream both = stream("ops");+ both.setIncludeFilters(List.of(new MetricStreamFilter("AWS/EC2", List.of())));+ both.setExcludeFilters(List.of(new MetricStreamFilter("AWS/S3", List.of())));++ AwsException e = assertThrows(AwsException.class, () -> service.putMetricStream(both, REGION));+ assertEquals("InvalidParameterCombination", e.getErrorCode());+ }++ @Test+ void getMissingStreamThrowsResourceNotFoundException() {+ AwsException e = assertThrows(AwsException.class, () -> service.getMetricStream("nope", REGION));+ assertEquals("ResourceNotFoundException", e.getErrorCode());+ assertEquals(404, e.getHttpStatus());+ }++ @Test+ void listIsScopedToTheRegionAndSortedByName() {+ service.putMetricStream(stream("zeta"), REGION);+ service.putMetricStream(stream("alpha"), REGION);+ service.putMetricStream(stream("other-region"), "eu-west-1");++ List<MetricStream> streams = service.listMetricStreams(REGION);+ assertEquals(List.of("alpha", "zeta"), streams.stream().map(MetricStream::getName).toList());+ }++ @Test+ void stopAndStartToggleTheState() {+ service.putMetricStream(stream("ops"), REGION);++ service.stopMetricStreams(List.of("ops"), REGION);+ assertEquals(MetricStream.STATE_STOPPED, service.getMetricStream("ops", REGION).getState());++ service.startMetricStreams(List.of("ops"), REGION);+ assertEquals(MetricStream.STATE_RUNNING, service.getMetricStream("ops", REGION).getState());+ }++ @Test+ void stopRequiresNamesAndReportsAMissingStream() {+ assertEquals("MissingParameter",+ assertThrows(AwsException.class, () -> service.stopMetricStreams(List.of(), REGION)).getErrorCode());+ // The model declares ResourceNotFoundException on GetMetricStream alone.+ assertEquals("InvalidParameterValue",+ assertThrows(AwsException.class, () -> service.stopMetricStreams(List.of("nope"), REGION)).getErrorCode());+ }++ @Test+ void aBatchNamingAMissingStreamChangesNothing() {+ service.putMetricStream(stream("ops"), REGION);++ AwsException e = assertThrows(AwsException.class,+ () -> service.stopMetricStreams(List.of("ops", "nope"), REGION));++ assertEquals("InvalidParameterValue", e.getErrorCode());+ assertEquals(MetricStream.STATE_RUNNING, service.getMetricStream("ops", REGION).getState());+ }++ @Test+ void putRejectsAFilterWithoutANamespace() {+ MetricStream bad = stream("ops");+ bad.setExcludeFilters(List.of(new MetricStreamFilter(null, List.of("Errors"))));++ AwsException e = assertThrows(AwsException.class, () -> service.putMetricStream(bad, REGION));+ assertEquals("MissingParameter", e.getErrorCode());+ assertThrows(AwsException.class, () -> service.getMetricStream("ops", REGION));+ }++ @Test+ void putRejectsAnIncompleteStatisticsConfiguration() {+ MetricStreamStatisticsConfiguration noMetrics = new MetricStreamStatisticsConfiguration();+ noMetrics.setAdditionalStatistics(List.of("p99"));+ MetricStream first = stream("ops");+ first.setStatisticsConfigurations(List.of(noMetrics));+ assertEquals("InvalidParameterValue",+ assertThrows(AwsException.class, () -> service.putMetricStream(first, REGION)).getErrorCode());++ MetricStreamStatisticsConfiguration noStatistics = new MetricStreamStatisticsConfiguration();+ noStatistics.setIncludeMetrics(List.of(+ new MetricStreamStatisticsConfiguration.IncludeMetric("AWS/EC2", "CPUUtilization")));+ MetricStream second = stream("ops");+ second.setStatisticsConfigurations(List.of(noStatistics));+ assertEquals("InvalidParameterValue",+ assertThrows(AwsException.class, () -> service.putMetricStream(second, REGION)).getErrorCode());++ MetricStreamStatisticsConfiguration blankMetric = new MetricStreamStatisticsConfiguration();+ blankMetric.setIncludeMetrics(List.of(+ new MetricStreamStatisticsConfiguration.IncludeMetric("AWS/EC2", null)));+ blankMetric.setAdditionalStatistics(List.of("p99"));+ MetricStream third = stream("ops");+ third.setStatisticsConfigurations(List.of(blankMetric));+ assertEquals("MissingParameter",+ assertThrows(AwsException.class, () -> service.putMetricStream(third, REGION)).getErrorCode());+ assertTrue(service.listMetricStreams(REGION).isEmpty());+ }++ @Test+ void listPagesInNameOrderWithAnOpaqueToken() {+ for (String name : List.of("c", "a", "b")) {+ service.putMetricStream(stream(name), REGION);+ }++ PaginatedResult<MetricStream> first = service.listMetricStreams(2, null, REGION);+ assertEquals(List.of("a", "b"), first.items().stream().map(MetricStream::getName).toList());+ assertNotNull(first.nextToken());++ PaginatedResult<MetricStream> second = service.listMetricStreams(2, first.nextToken(), REGION);+ assertEquals(List.of("c"), second.items().stream().map(MetricStream::getName).toList());+ assertNull(second.nextToken());++ assertEquals("InvalidNextToken",+ assertThrows(AwsException.class,+ () -> service.listMetricStreams(2, "not base64!", REGION)).getErrorCode());+ assertEquals("InvalidNextToken",+ assertThrows(AwsException.class,+ () -> service.listMetricStreams(0, null, REGION)).getErrorCode());+ }++ @Test+ void deleteRemovesTheStreamAndToleratesAMissingOne() {+ service.putMetricStream(stream("ops"), REGION);++ service.deleteMetricStream("ops", REGION);+ service.deleteMetricStream("ops", REGION);++ assertTrue(service.listMetricStreams(REGION).isEmpty());+ }++ @Test+ void tagsRoundTripByArn() {+ MetricStream tagged = stream("ops");+ tagged.setTags(new LinkedHashMap<>(Map.of("team", "platform")));+ String arn = service.putMetricStream(tagged, REGION).getArn();++ assertTrue(CloudWatchMetricStreamsService.isMetricStreamArn(arn));+ assertFalse(CloudWatchMetricStreamsService.isMetricStreamArn(+ "arn:aws:cloudwatch:us-east-1:000000000000:alarm:ops"));+ assertEquals("platform", service.listTagsForResource(arn, REGION).get("team"));++ service.tagResource(arn, Map.of("owner", "ops"), REGION);+ assertEquals("ops", service.listTagsForResource(arn, REGION).get("owner"));++ service.untagResource(arn, List.of("team"), REGION);+ assertFalse(service.listTagsForResource(arn, REGION).containsKey("team"));+ }+}