Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudwatch): implement the dashboard operations on both protocols (#2888)
Allen Sanborne8eb4f2ff003
diff --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 88e6db23a2..599702879e 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@@ -498,7 +498,8 @@ public class AwsQueryController {private static final Set<String> CLOUDWATCH_ACTIONS = Set.of("PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData","PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState",- "ListTagsForResource", "TagResource", "UntagResource"+ "ListTagsForResource", "TagResource", "UntagResource",+ "PutDashboard", "GetDashboard", "ListDashboards", "DeleteDashboards");private static final Set<String> ELASTIC_BEANSTALK_ACTIONS = Set.of(diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsService.javanew file mode 100644index 0000000000..976a43f4df--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsService.java@@ -0,0 +1,213 @@+package io.github.hectorvent.floci.services.cloudwatch.dashboards;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.DeserializationFeature;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.ObjectReader;+import io.github.hectorvent.floci.core.common.AwsException;+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.dashboards.model.Dashboard;+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;++/**+ * CloudWatch dashboards. Dashboards are pure metadata: the DashboardBody is an opaque JSON+ * document that AWS stores and hands back verbatim, so there is no backing behaviour here.+ */+@ApplicationScoped+public class CloudWatchDashboardsService {++ private static final Logger LOG = Logger.getLogger(CloudWatchDashboardsService.class);++ // FAIL_ON_TRAILING_TOKENS matters here: without it a body of "{} garbage" parses as the+ // leading object and the rest is silently dropped, so a document AWS rejects would be stored.+ /** AWS's documented ceiling for PutDashboard's Tags. */+ private static final int MAX_TAGS = 50;++ private static final ObjectReader JSON = new ObjectMapper()+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)+ .readerFor(JsonNode.class);++ private final StorageBackend<String, Dashboard> dashboardStore;+ private final RegionResolver regionResolver;++ @Inject+ public CloudWatchDashboardsService(StorageFactory storageFactory, RegionResolver regionResolver) {+ this.dashboardStore = storageFactory.create("cloudwatchmetrics", "cwdashboards.json",+ new TypeReference<Map<String, Dashboard>>() {});+ 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 CloudWatchDashboardsService(StorageBackend<String, Dashboard> dashboardStore,+ RegionResolver regionResolver) {+ this.dashboardStore = dashboardStore;+ this.regionResolver = regionResolver;+ }++ /** Creates the dashboard, or replaces it wholesale when the name is already taken. */+ public Dashboard putDashboard(String dashboardName, String dashboardBody, String region) {+ return putDashboard(dashboardName, dashboardBody, Map.of(), region);+ }++ /**+ * Creates the dashboard, or replaces it wholesale when the name is already taken.+ *+ * <p>Tags apply on create only, as AWS documents: a Put that replaces an existing dashboard+ * keeps the tags that dashboard already had rather than taking the ones on this request, so+ * an update cannot quietly retag a resource through an operation that is not a tag operation.+ */+ public Dashboard putDashboard(String dashboardName, String dashboardBody,+ Map<String, String> tags, String region) {+ if (dashboardName == null || dashboardName.isBlank()) {+ throw new AwsException("InvalidParameterValue", "DashboardName is required.", 400);+ }+ if (dashboardBody == null) {+ throw new AwsException("InvalidParameterValue", "DashboardBody is required.", 400);+ }+ validateDashboardBody(dashboardBody);++ Dashboard existing = dashboardStore.get(key(region, dashboardName)).orElse(null);+ Dashboard dashboard = new Dashboard(dashboardName,+ regionResolver.buildArn("cloudwatch", region, "dashboard/" + dashboardName),+ dashboardBody);+ dashboard.setLastModified(Instant.now().getEpochSecond());+ if (existing != null) {+ dashboard.setTags(new LinkedHashMap<>(existing.getTags()));+ } else if (tags != null && !tags.isEmpty()) {+ if (tags.size() > MAX_TAGS) {+ throw new AwsException("InvalidParameterInput",+ "A dashboard can have at most " + MAX_TAGS + " tags.", 400);+ }+ dashboard.setTags(new LinkedHashMap<>(tags));+ }++ // put() overwrites, which is exactly PutDashboard's semantics: an existing name is+ // replaced in full rather than merged.+ dashboardStore.put(key(region, dashboardName), dashboard);+ LOG.debugv("PutDashboard: {0} in {1}", dashboardName, region);+ return dashboard;+ }++ /**+ * The body is stored opaquely, but it is not accepted blindly: AWS parses it and answers+ * InvalidParameterInput when it is not a JSON object, so a client that sends a malformed+ * document gets an error rather than a success and a dashboard that renders as nothing.+ */+ private static void validateDashboardBody(String dashboardBody) {+ JsonNode parsed;+ try {+ parsed = JSON.readValue(dashboardBody);+ } catch (JsonProcessingException e) {+ throw new AwsException("InvalidParameterInput",+ "The dashboard body is invalid: " + e.getOriginalMessage(), 400);+ }+ if (parsed == null || !parsed.isObject()) {+ throw new AwsException("InvalidParameterInput",+ "The dashboard body is invalid: it must be a JSON object.", 400);+ }+ }++ public Dashboard getDashboard(String dashboardName, String region) {+ return dashboardStore.get(key(region, dashboardName))+ .orElseThrow(() -> notFound(dashboardName));+ }++ public List<Dashboard> listDashboards(String dashboardNamePrefix, String region) {+ String keyPrefix = region + "::";+ List<Dashboard> all = dashboardStore.scan(k -> k.startsWith(keyPrefix));+ if (dashboardNamePrefix != null && !dashboardNamePrefix.isBlank()) {+ all = new ArrayList<>(all.stream()+ .filter(d -> d.getDashboardName().startsWith(dashboardNamePrefix))+ .toList());+ }+ all.sort(Comparator.comparing(Dashboard::getDashboardName));+ return all;+ }++ /**+ * Deletes as many of the named dashboards as it can, then reports the first name that was not+ * there. AWS documents this as best effort, verbatim: "If there is an error during this call,+ * the operation attempts to delete as many dashboards as possible." So a batch naming one+ * missing dashboard still deletes the others, rather than leaving every one of them in place.+ *+ * <p>Whether a missing name errors at all is the part that is not settled: DeleteDashboards'+ * own Errors list does not name ResourceNotFound the way GetDashboard's does, which hints at a+ * silent skip but does not establish one. Reporting it is the conservative reading, since a+ * caller that names a dashboard which is not there has a problem worth hearing about, and it+ * is the smaller departure from what this already did.+ */+ public void deleteDashboards(List<String> dashboardNames, String region) {+ if (dashboardNames == null || dashboardNames.isEmpty()) {+ throw new AwsException("InvalidParameterValue", "DashboardNames is required.", 400);+ }+ String firstMissing = null;+ for (String name : dashboardNames) {+ if (dashboardStore.get(key(region, name)).isEmpty()) {+ if (firstMissing == null) {+ firstMissing = name;+ }+ continue;+ }+ dashboardStore.delete(key(region, name));+ }+ LOG.debugv("DeleteDashboards: {0} in {1}", dashboardNames, region);+ if (firstMissing != null) {+ throw notFound(firstMissing);+ }+ }++ /**+ * Whether an ARN names a dashboard. 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 isDashboardArn(String resourceArn) {+ return resourceArn != null && resourceArn.contains(":dashboard/");+ }++ public Map<String, String> listTagsForResource(String resourceArn, String region) {+ return findByArn(resourceArn, region).map(Dashboard::getTags).orElse(Map.of());+ }++ public void tagResource(String resourceArn, Map<String, String> tags, String region) {+ findByArn(resourceArn, region).ifPresent(dashboard -> {+ dashboard.getTags().putAll(tags);+ dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);+ });+ }++ public void untagResource(String resourceArn, List<String> tagKeys, String region) {+ findByArn(resourceArn, region).ifPresent(dashboard -> {+ tagKeys.forEach(dashboard.getTags()::remove);+ dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);+ });+ }++ private java.util.Optional<Dashboard> findByArn(String resourceArn, String region) {+ return dashboardStore.scan(k -> k.startsWith(region + "::")).stream()+ .filter(d -> d.getDashboardArn() != null && d.getDashboardArn().equals(resourceArn))+ .findFirst();+ }++ private static String key(String region, String dashboardName) {+ return region + "::" + dashboardName;+ }++ private static AwsException notFound(String dashboardName) {+ return new AwsException("ResourceNotFound",+ "Dashboard does not exist: " + dashboardName, 404);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/model/Dashboard.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/model/Dashboard.javanew file mode 100644index 0000000000..e96879181d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/model/Dashboard.java@@ -0,0 +1,55 @@+package io.github.hectorvent.floci.services.cloudwatch.dashboards.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.Map;++/**+ * A CloudWatch dashboard. AWS stores the body as an opaque JSON document and returns it+ * verbatim, so nothing here interprets the widget structure.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class Dashboard {++ private String dashboardName;+ private String dashboardArn;+ private String dashboardBody;+ private long lastModified;+ private Map<String, String> tags = new LinkedHashMap<>();++ public Dashboard() {+ this.lastModified = Instant.now().getEpochSecond();+ }++ public Dashboard(String dashboardName, String dashboardArn, String dashboardBody) {+ this();+ this.dashboardName = dashboardName;+ this.dashboardArn = dashboardArn;+ this.dashboardBody = dashboardBody;+ }++ public String getDashboardName() { return dashboardName; }+ public void setDashboardName(String dashboardName) { this.dashboardName = dashboardName; }++ public String getDashboardArn() { return dashboardArn; }+ public void setDashboardArn(String dashboardArn) { this.dashboardArn = dashboardArn; }++ public String getDashboardBody() { return dashboardBody; }+ public void setDashboardBody(String dashboardBody) { this.dashboardBody = dashboardBody; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); }++ public long getLastModified() { return lastModified; }+ public void setLastModified(long lastModified) { this.lastModified = lastModified; }++ /** Byte length of the body, which is what ListDashboards reports as Size. */+ public long getSize() {+ return dashboardBody == null ? 0 : dashboardBody.getBytes(StandardCharsets.UTF_8).length;+ }+}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 a6f97a696f..a42bcd61f9 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,6 +5,8 @@ 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.services.cloudwatch.dashboards.CloudWatchDashboardsService;+import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;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,11 +29,15 @@ public class CloudWatchMetricsJsonHandler {private static final Logger LOG = Logger.getLogger(CloudWatchMetricsJsonHandler.class);private final CloudWatchMetricsService metricsService;+ private final CloudWatchDashboardsService dashboardsService;private final ObjectMapper objectMapper;@Inject- public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService, ObjectMapper objectMapper) {+ public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService,+ CloudWatchDashboardsService dashboardsService,+ ObjectMapper objectMapper) {this.metricsService = metricsService;+ this.dashboardsService = dashboardsService;this.objectMapper = objectMapper;}@@ -49,6 +55,10 @@ public class CloudWatchMetricsJsonHandler {case "TagResource" -> handleTagResource(request, region);case "UntagResource" -> handleUntagResource(request, region);case "GetMetricData" -> handleGetMetricData(request, region);+ case "PutDashboard" -> handlePutDashboard(request, region);+ case "GetDashboard" -> handleGetDashboard(request, region);+ case "ListDashboards" -> handleListDashboards(request, region);+ case "DeleteDashboards" -> handleDeleteDashboards(request, region);default -> Response.status(400).entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch JSON.")).build();@@ -233,7 +243,9 @@ 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 = metricsService.listTagsForResource(arn, region);+ Map<String, String> tags = CloudWatchDashboardsService.isDashboardArn(arn)+ ? dashboardsService.listTagsForResource(arn, region)+ : 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();@@ -248,7 +260,11 @@ public class CloudWatchMetricsJsonHandler {if (tagsNode.isArray()) {tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));}- metricsService.tagResource(arn, tags, region);+ if (CloudWatchDashboardsService.isDashboardArn(arn)) {+ dashboardsService.tagResource(arn, tags, region);+ } else {+ metricsService.tagResource(arn, tags, region);+ }return Response.ok(objectMapper.createObjectNode()).build();}@@ -261,7 +277,11 @@ public class CloudWatchMetricsJsonHandler {if (keysNode.isArray()) {keysNode.forEach(k -> keys.add(k.asText()));}- metricsService.untagResource(arn, keys, region);+ if (CloudWatchDashboardsService.isDashboardArn(arn)) {+ dashboardsService.untagResource(arn, keys, region);+ } else {+ metricsService.untagResource(arn, keys, region);+ }return Response.ok(objectMapper.createObjectNode()).build();}@@ -322,6 +342,65 @@ public class CloudWatchMetricsJsonHandler {return Response.ok(response).build();}+ // ──────────────────────────── Dashboards ────────────────────────────++ private Response handlePutDashboard(JsonNode request, String region) {+ Map<String, String> tags = new LinkedHashMap<>();+ JsonNode tagsNode = request.path("Tags");+ if (tagsNode.isArray()) {+ tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));+ }+ dashboardsService.putDashboard(+ request.path("DashboardName").asText(null),+ request.path("DashboardBody").asText(null),+ tags,+ region);+ // DashboardValidationMessages is optional on the response shape, but AWS always+ // sends the list. It stays empty here: the body is stored opaquely, so nothing+ // inspects it and no validation warning can be produced.+ ObjectNode response = objectMapper.createObjectNode();+ response.putArray("DashboardValidationMessages");+ return Response.ok(response).build();+ }++ private Response handleGetDashboard(JsonNode request, String region) {+ Dashboard dashboard = dashboardsService.getDashboard(+ request.path("DashboardName").asText(null), region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("DashboardArn", dashboard.getDashboardArn());+ response.put("DashboardName", dashboard.getDashboardName());+ response.put("DashboardBody", dashboard.getDashboardBody());+ return Response.ok(response).build();+ }++ private Response handleListDashboards(JsonNode request, String region) {+ String prefix = request.has("DashboardNamePrefix")+ ? request.path("DashboardNamePrefix").asText() : null;+ List<Dashboard> dashboards = dashboardsService.listDashboards(prefix, region);++ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode entries = response.putArray("DashboardEntries");+ for (Dashboard d : dashboards) {+ ObjectNode node = entries.addObject();+ node.put("DashboardName", d.getDashboardName());+ node.put("DashboardArn", d.getDashboardArn());+ node.put("LastModified", d.getLastModified());+ node.put("Size", d.getSize());+ }+ return Response.ok(response).build();+ }++ private Response handleDeleteDashboards(JsonNode request, String region) {+ List<String> names = new ArrayList<>();+ JsonNode namesNode = request.path("DashboardNames");+ if (namesNode.isArray()) {+ namesNode.forEach(n -> names.add(n.asText()));+ }+ dashboardsService.deleteDashboards(names, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }+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 223bcc3c9a..41b8dfefa0 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@@ -3,6 +3,8 @@ 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.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.metrics.model.Dimension;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;@@ -24,10 +26,13 @@ public class CloudWatchMetricsQueryHandler {private static final Logger LOG = Logger.getLogger(CloudWatchMetricsQueryHandler.class);private CloudWatchMetricsService metricsService;+ private final CloudWatchDashboardsService dashboardsService;@Inject- public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService) {+ public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService,+ CloudWatchDashboardsService dashboardsService) {this.metricsService = metricsService;+ this.dashboardsService = dashboardsService;}public Response handle(String action, MultivaluedMap<String, String> params, String region) {@@ -44,6 +49,10 @@ public class CloudWatchMetricsQueryHandler {case "ListTagsForResource" -> handleListTagsForResource(params, region);case "TagResource" -> handleTagResource(params, region);case "UntagResource" -> handleUntagResource(params, region);+ case "PutDashboard" -> handlePutDashboard(params, region);+ case "GetDashboard" -> handleGetDashboard(params, region);+ case "ListDashboards" -> handleListDashboards(params, region);+ case "DeleteDashboards" -> handleDeleteDashboards(params, region);default -> AwsQueryResponse.error("UnsupportedOperation","Operation " + action + " is not supported by CloudWatch Query.", AwsNamespaces.CW, 400);};@@ -254,7 +263,9 @@ public class CloudWatchMetricsQueryHandler {private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {String arn = params.getFirst("ResourceARN");- Map<String, String> tags = metricsService.listTagsForResource(arn, region);+ Map<String, String> tags = CloudWatchDashboardsService.isDashboardArn(arn)+ ? dashboardsService.listTagsForResource(arn, region)+ : 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");@@ -269,7 +280,11 @@ public class CloudWatchMetricsQueryHandler {if (key == null) break;tags.put(key, params.getFirst("Tags.member." + i + ".Value"));}- metricsService.tagResource(arn, tags, region);+ if (CloudWatchDashboardsService.isDashboardArn(arn)) {+ dashboardsService.tagResource(arn, tags, region);+ } else {+ metricsService.tagResource(arn, tags, region);+ }return Response.ok(AwsQueryResponse.envelopeNoResult("TagResource", null)).build();}@@ -281,10 +296,75 @@ public class CloudWatchMetricsQueryHandler {if (key == null) break;keys.add(key);}- metricsService.untagResource(arn, keys, region);+ if (CloudWatchDashboardsService.isDashboardArn(arn)) {+ dashboardsService.untagResource(arn, keys, region);+ } else {+ metricsService.untagResource(arn, keys, region);+ }return Response.ok(AwsQueryResponse.envelopeNoResult("UntagResource", null)).build();}+ // ──────────────────────────── Dashboards ────────────────────────────++ private Response handlePutDashboard(MultivaluedMap<String, String> params, String region) {+ 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"));+ }+ dashboardsService.putDashboard(params.getFirst("DashboardName"),+ params.getFirst("DashboardBody"), tags, region);+ // DashboardValidationMessages is optional on the response shape, but AWS always+ // sends the list. It stays empty: the body is stored opaquely, so nothing here+ // inspects it and no validation warning can be produced.+ String xml = new XmlBuilder()+ .start("DashboardValidationMessages").end("DashboardValidationMessages")+ .build();+ return Response.ok(AwsQueryResponse.envelope("PutDashboard", null, xml)).build();+ }++ private Response handleGetDashboard(MultivaluedMap<String, String> params, String region) {+ Dashboard dashboard = dashboardsService.getDashboard(params.getFirst("DashboardName"), region);+ String xml = new XmlBuilder()+ .elem("DashboardArn", dashboard.getDashboardArn())+ .elem("DashboardName", dashboard.getDashboardName())+ .elem("DashboardBody", dashboard.getDashboardBody())+ .build();+ return Response.ok(AwsQueryResponse.envelope("GetDashboard", null, xml)).build();+ }++ private Response handleListDashboards(MultivaluedMap<String, String> params, String region) {+ List<Dashboard> dashboards =+ dashboardsService.listDashboards(params.getFirst("DashboardNamePrefix"), region);++ DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;+ var xml = new XmlBuilder().start("DashboardEntries");+ for (Dashboard d : dashboards) {+ xml.start("member")+ .elem("DashboardName", d.getDashboardName())+ .elem("DashboardArn", d.getDashboardArn())+ .elem("LastModified", fmt.format(Instant.ofEpochSecond(d.getLastModified())))+ .elem("Size", d.getSize())+ .end("member");+ }+ xml.end("DashboardEntries");+ return Response.ok(AwsQueryResponse.envelope("ListDashboards", null, xml.build())).build();+ }++ private Response handleDeleteDashboards(MultivaluedMap<String, String> params, String region) {+ List<String> names = new ArrayList<>();+ for (int i = 1; ; i++) {+ String name = params.getFirst("DashboardNames.member." + i);+ if (name == null) break;+ names.add(name);+ }+ dashboardsService.deleteDashboards(names, region);+ return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteDashboards", null)).build();+ }+// ──────────────────────────── Parsing Helpers ────────────────────────────private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.javanew file mode 100644index 0000000000..39809bfc5e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsIntegrationTest.java@@ -0,0 +1,226 @@+package io.github.hectorvent.floci.services.cloudwatch.dashboards;++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.not;++/**+ * The dashboard operations reach the emulator over the Query protocol - that is what the+ * Terraform AWS provider speaks to CloudWatch, and the route that used to answer+ * "Operation PutDashboard is not supported by CloudWatch Query".+ */+@QuarkusTest+class CloudWatchDashboardsIntegrationTest {++ 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";++ @BeforeAll+ static void registerJsonParser() {+ RestAssured.registerParser(JSON_1_0, Parser.JSON);+ }++ // 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 final String BODY =+ "{\"widgets\":[{\"type\":\"metric\",\"properties\":{\"title\":\"a > b\"}}]}";++ private void putDashboard(String name, String body) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "PutDashboard")+ .formParam("DashboardName", name)+ .formParam("DashboardBody", body)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .contentType("application/xml");+ }++ @Test+ void putThenGetReturnsTheBodyVerbatim() {+ putDashboard("query-round-trip", BODY);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "GetDashboard")+ .formParam("DashboardName", "query-round-trip")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", equalTo(BODY))+ .body("GetDashboardResponse.GetDashboardResult.DashboardArn",+ containsString(":dashboard/query-round-trip"));+ }++ @Test+ void getUnknownDashboardReturnsResourceNotFound() {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "GetDashboard")+ .formParam("DashboardName", "no-such-dashboard")+ .when()+ .post("/")+ .then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));+ }++ @Test+ void listDashboardsHonoursTheNamePrefix() {+ putDashboard("prefixed-one", BODY);+ putDashboard("prefixed-two", BODY);+ putDashboard("unprefixed", BODY);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "ListDashboards")+ .formParam("DashboardNamePrefix", "prefixed-")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName",+ hasItem("prefixed-one"))+ .body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName",+ not(hasItem("unprefixed")));+ }++ @Test+ void deleteDashboardsRemovesEveryNamedDashboard() {+ putDashboard("delete-a", BODY);+ putDashboard("delete-b", BODY);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "DeleteDashboards")+ .formParam("DashboardNames.member.1", "delete-a")+ .formParam("DashboardNames.member.2", "delete-b")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "GetDashboard")+ .formParam("DashboardName", "delete-a")+ .when()+ .post("/")+ .then()+ .statusCode(404);+ }++ // The AWS CLI and SDK v3 send the same operations as JSON with an X-Amz-Target header,+ // which the emulator dispatches to CloudWatchMetricsJsonHandler instead.+ @Test+ void theSameOperationsAreServedOverTheJsonProtocol() {+ json("PutDashboard", "{\"DashboardName\": \"json-round-trip\", \"DashboardBody\": \"{}\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ json("GetDashboard", "{\"DashboardName\": \"json-round-trip\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DashboardBody", equalTo("{}"));+ }+ /**+ * Tags supplied on PutDashboard have to be readable afterwards, and CloudWatch's tag+ * operations take one ARN for every resource it owns, so the handler has to route a dashboard+ * ARN to the dashboards service rather than the alarm store that answered before.+ */+ @Test+ void tagsSuppliedOnPutAreReadableThroughListTagsForResource() {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "PutDashboard")+ .formParam("DashboardName", "tagged")+ .formParam("DashboardBody", BODY)+ .formParam("Tags.member.1.Key", "team")+ .formParam("Tags.member.1.Value", "platform")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ String arn = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "GetDashboard")+ .formParam("DashboardName", "tagged")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("GetDashboardResponse.GetDashboardResult.DashboardArn");++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "ListTagsForResource")+ .formParam("ResourceARN", arn)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<Key>team</Key>"))+ .body(containsString("<Value>platform</Value>"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "UntagResource")+ .formParam("ResourceARN", arn)+ .formParam("TagKeys.member.1", "team")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CW_SCOPE)+ .formParam("Action", "ListTagsForResource")+ .formParam("ResourceARN", arn)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(not(containsString("<Key>team</Key>")));+ }++}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.javanew file mode 100644index 0000000000..be2c481888--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/dashboards/CloudWatchDashboardsServiceTest.java@@ -0,0 +1,164 @@+package io.github.hectorvent.floci.services.cloudwatch.dashboards;++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.model.Dashboard;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++class CloudWatchDashboardsServiceTest {++ private static final String REGION = "us-east-1";+ private static final String BODY = "{\"widgets\":[{\"type\":\"metric\",\"width\":6}]}";++ private CloudWatchDashboardsService service;++ @BeforeEach+ void setUp() {+ service = new CloudWatchDashboardsService(+ new InMemoryStorage<>(),+ new RegionResolver(REGION, "000000000000")+ );+ }++ @Test+ void putAndGetReturnsBodyVerbatim() {+ service.putDashboard("ops", BODY, REGION);++ Dashboard dashboard = service.getDashboard("ops", REGION);+ assertEquals(BODY, dashboard.getDashboardBody());+ assertEquals("ops", dashboard.getDashboardName());+ assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:dashboard/ops",+ dashboard.getDashboardArn());+ }++ @Test+ void putOnExistingNameOverwrites() {+ service.putDashboard("ops", BODY, REGION);+ service.putDashboard("ops", "{\"widgets\":[]}", REGION);++ assertEquals("{\"widgets\":[]}", service.getDashboard("ops", REGION).getDashboardBody());+ assertEquals(1, service.listDashboards(null, REGION).size());+ }++ @Test+ void getMissingDashboardThrowsResourceNotFound() {+ AwsException e = assertThrows(AwsException.class, () -> service.getDashboard("nope", REGION));+ assertEquals("ResourceNotFound", e.getErrorCode());+ }++ @Test+ void putRejectsNullBody() {+ assertThrows(AwsException.class, () -> service.putDashboard("ops", null, REGION));+ }++ @Test+ void putRejectsAMalformedBody() {+ AwsException e = assertThrows(AwsException.class,+ () -> service.putDashboard("ops", "{\"widgets\": [", REGION));+ assertEquals("InvalidParameterInput", e.getErrorCode());+ assertEquals(400, e.getHttpStatus());+ }++ /** A leading object followed by anything else is still a malformed document, not a dashboard. */+ @Test+ void putRejectsABodyWithTrailingContentAfterTheObject() {+ AwsException e = assertThrows(AwsException.class,+ () -> service.putDashboard("ops", "{\"widgets\": []} and then some", REGION));+ assertEquals("InvalidParameterInput", e.getErrorCode());+ }++ /** A body that parses but is not an object is equally unusable as a dashboard. */+ @Test+ void putRejectsABodyThatIsNotAJsonObject() {+ AwsException e = assertThrows(AwsException.class,+ () -> service.putDashboard("ops", "[]", REGION));+ assertEquals("InvalidParameterInput", e.getErrorCode());+ }++ @Test+ void listDashboardsFiltersByNamePrefix() {+ service.putDashboard("prod-api", BODY, REGION);+ service.putDashboard("prod-web", BODY, REGION);+ service.putDashboard("staging-api", BODY, REGION);++ List<Dashboard> filtered = service.listDashboards("prod-", REGION);+ assertEquals(List.of("prod-api", "prod-web"),+ filtered.stream().map(Dashboard::getDashboardName).toList());+ assertEquals(3, service.listDashboards(null, REGION).size());+ }++ @Test+ void listDashboardsIsScopedToRegion() {+ service.putDashboard("ops", BODY, REGION);+ service.putDashboard("ops", BODY, "eu-west-1");++ assertEquals(1, service.listDashboards(null, REGION).size());+ assertEquals(1, service.listDashboards(null, "eu-west-1").size());+ }++ @Test+ void deleteDashboardsRemovesEveryNamedDashboard() {+ service.putDashboard("a", BODY, REGION);+ service.putDashboard("b", BODY, REGION);+ service.putDashboard("c", BODY, REGION);++ service.deleteDashboards(List.of("a", "b"), REGION);++ assertEquals(List.of("c"),+ service.listDashboards(null, REGION).stream().map(Dashboard::getDashboardName).toList());+ }++ @Test+ void tagsGivenOnCreateAreReadableByArn() {+ service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);+ String arn = service.getDashboard("ops", REGION).getDashboardArn();++ assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));+ assertTrue(CloudWatchDashboardsService.isDashboardArn(arn));+ }++ /**+ * AWS documents Tags on PutDashboard as create-only, so replacing a dashboard keeps the tags+ * it already had: an update must not be able to retag a resource sideways.+ */+ @Test+ void tagsOnAReplacingPutDoNotOverwriteTheExistingOnes() {+ service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);+ String arn = service.getDashboard("ops", REGION).getDashboardArn();++ service.putDashboard("ops", BODY, java.util.Map.of("team", "someone-else"), REGION);++ assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));+ }++ @Test+ void tagAndUntagResourceReachDashboards() {+ service.putDashboard("ops", BODY, REGION);+ String arn = service.getDashboard("ops", REGION).getDashboardArn();++ service.tagResource(arn, java.util.Map.of("env", "dev"), REGION);+ assertEquals(java.util.Map.of("env", "dev"), service.listTagsForResource(arn, REGION));++ service.untagResource(arn, List.of("env"), REGION);+ assertEquals(java.util.Map.of(), service.listTagsForResource(arn, REGION));+ }++ @Test+ void deleteDashboardsIsBestEffortWhenOneNameIsMissing() {+ service.putDashboard("a", BODY, REGION);+ service.putDashboard("b", BODY, REGION);++ AwsException e = assertThrows(AwsException.class,+ () -> service.deleteDashboards(List.of("a", "missing", "b"), REGION));+ assertEquals("ResourceNotFound", e.getErrorCode());+ // AWS attempts to delete as many dashboards as possible, so the two that existed are+ // gone even though the batch errored, and a name after the missing one is still tried.+ assertEquals(0, service.listDashboards(null, REGION).size());+ }+}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 45aeb38d80..b5f4ae5c0b 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@@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;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 jakarta.ws.rs.core.Response;import java.math.BigDecimal;import java.time.Instant;@@ -41,7 +42,11 @@ class CloudWatchMetricsJsonHandlerTest {new InMemoryStorage<>(),new RegionResolver(REGION, "000000000000"));- handler = new CloudWatchMetricsJsonHandler(service, MAPPER);+ CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(+ new InMemoryStorage<>(),+ new RegionResolver(REGION, "000000000000")+ );+ handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, 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 4ff265e1ab..b75390ee7a 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,5 +1,6 @@package io.github.hectorvent.floci.services.cloudwatch.metrics;+import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.MultivaluedMap;@@ -24,7 +25,9 @@ class CloudWatchMetricsQueryHandlerTest {private static final String REGION = "us-east-1";private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);- private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metricsService);+ // The alarm cases below never reach a dashboard operation; the handler simply routes both.+ private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(+ metricsService, mock(CloudWatchDashboardsService.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 46ccb069f1..98b7528e40 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@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;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.metrics.model.MetricAlarm;import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.MultivaluedMap;@@ -31,8 +32,10 @@ class CloudWatchMetricsTagsTest {new InMemoryStorage<>(),new RegionResolver("us-east-1", "000000000000"));- queryHandler = new CloudWatchMetricsQueryHandler(service);- jsonHandler = new CloudWatchMetricsJsonHandler(service, objectMapper);+ CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(+ new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));+ queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService);+ jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, objectMapper);}@Test