diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 1a610ecbdd..da06eddedc 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -162,6 +162,11 @@ software.amazon.awssdk eventbridge + + + software.amazon.awssdk + servicediscovery + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 33d4a1d2ce..ee0de0478f 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -8,7 +8,9 @@ import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.services.eventbridge.EventBridgeClient; +import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; import software.amazon.awssdk.services.kinesis.KinesisClient; @@ -454,6 +456,18 @@ public final class TestFixtures { .build(); } + public static ServiceDiscoveryClient serviceDiscoveryClient() { + return ServiceDiscoveryClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + // DiscoverInstances carries a "data-" host prefix; injecting it would + // rewrite the custom endpoint host (data-) and break resolution. + .overrideConfiguration(o -> o.putAdvancedOption( + SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, Boolean.TRUE)) + .build(); + } + public static SfnClient sfnClient() { return SfnClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudMapTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudMapTest.java new file mode 100644 index 0000000000..f571d418c0 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudMapTest.java @@ -0,0 +1,196 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient; +import software.amazon.awssdk.services.servicediscovery.model.*; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.*; + +/** + * Cloud Map (servicediscovery) validated through the real AWS SDK v2 client. + * Exercises the Phase 1 flow: create namespace → poll operation → create service → + * register instance → discover → deregister → delete. + */ +@DisplayName("Cloud Map") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CloudMapTest { + + private static ServiceDiscoveryClient sd; + private static String namespaceName; + private static String serviceName; + private static String namespaceId; + private static String serviceId; + private static final String INSTANCE_ID = "i-cm-sdk-1"; + + @BeforeAll + static void setup() { + sd = TestFixtures.serviceDiscoveryClient(); + namespaceName = TestFixtures.uniqueName("cm-ns"); + serviceName = TestFixtures.uniqueName("cm-svc"); + } + + @AfterAll + static void cleanup() { + try { + sd.deregisterInstance(r -> r.serviceId(serviceId).instanceId(INSTANCE_ID)); + } catch (Exception ignored) {} + try { + sd.deleteService(r -> r.id(serviceId)); + } catch (Exception ignored) {} + try { + sd.deleteNamespace(r -> r.id(namespaceId)); + } catch (Exception ignored) {} + sd.close(); + } + + private static void awaitSuccess(String operationId) { + for (int i = 0; i < 20; i++) { + GetOperationResponse op = sd.getOperation(r -> r.operationId(operationId)); + if (op.operation().status() == OperationStatus.SUCCESS) { + return; + } + if (op.operation().status() == OperationStatus.FAIL) { + fail("Operation " + operationId + " failed: " + op.operation().errorMessage()); + } + try { Thread.sleep(100); } catch (InterruptedException ignored) {} + } + fail("Operation " + operationId + " did not reach SUCCESS"); + } + + @Test + @Order(1) + void createHttpNamespace() { + CreateHttpNamespaceResponse resp = sd.createHttpNamespace( + r -> r.name(namespaceName).description("floci sdk compat")); + assertThat(resp.operationId()).isNotBlank(); + awaitSuccess(resp.operationId()); + } + + @Test + @Order(2) + void listNamespacesFindsIt() { + ListNamespacesResponse resp = sd.listNamespaces(ListNamespacesRequest.builder().build()); + NamespaceSummary found = resp.namespaces().stream() + .filter(n -> n.name().equals(namespaceName)) + .findFirst().orElseThrow(); + namespaceId = found.id(); + assertThat(namespaceId).startsWith("ns-"); + assertThat(found.type()).isEqualTo(NamespaceType.HTTP); + assertThat(found.arn()).contains("servicediscovery"); + } + + @Test + @Order(3) + void getNamespace() { + GetNamespaceResponse resp = sd.getNamespace(r -> r.id(namespaceId)); + assertThat(resp.namespace().name()).isEqualTo(namespaceName); + assertThat(resp.namespace().properties().httpProperties().httpName()).isEqualTo(namespaceName); + } + + @Test + @Order(4) + void createService() { + CreateServiceResponse resp = sd.createService( + r -> r.name(serviceName).namespaceId(namespaceId).type(ServiceTypeOption.HTTP)); + serviceId = resp.service().id(); + assertThat(serviceId).startsWith("srv-"); + assertThat(resp.service().name()).isEqualTo(serviceName); + assertThat(resp.service().namespaceId()).isEqualTo(namespaceId); + } + + @Test + @Order(5) + void registerInstance() { + RegisterInstanceResponse resp = sd.registerInstance(r -> r + .serviceId(serviceId) + .instanceId(INSTANCE_ID) + .attributes(Map.of("AWS_INSTANCE_IPV4", "10.0.0.7", "AWS_INSTANCE_PORT", "9090"))); + assertThat(resp.operationId()).isNotBlank(); + awaitSuccess(resp.operationId()); + } + + @Test + @Order(6) + void listInstances() { + ListInstancesResponse resp = sd.listInstances(r -> r.serviceId(serviceId)); + assertThat(resp.instances()).hasSize(1); + InstanceSummary summary = resp.instances().get(0); + assertThat(summary.id()).isEqualTo(INSTANCE_ID); + assertThat(summary.attributes()).containsEntry("AWS_INSTANCE_IPV4", "10.0.0.7"); + } + + @Test + @Order(7) + void getInstance() { + GetInstanceResponse resp = sd.getInstance(r -> r.serviceId(serviceId).instanceId(INSTANCE_ID)); + assertThat(resp.instance().id()).isEqualTo(INSTANCE_ID); + assertThat(resp.instance().attributes()).containsEntry("AWS_INSTANCE_PORT", "9090"); + } + + @Test + @Order(8) + void discoverInstances() { + DiscoverInstancesResponse resp = sd.discoverInstances(r -> r + .namespaceName(namespaceName) + .serviceName(serviceName) + .healthStatus(HealthStatusFilter.HEALTHY_OR_ELSE_ALL)); + assertThat(resp.instances()).hasSize(1); + HttpInstanceSummary inst = resp.instances().get(0); + assertThat(inst.instanceId()).isEqualTo(INSTANCE_ID); + assertThat(inst.healthStatus()).isEqualTo(HealthStatus.HEALTHY); + assertThat(resp.instancesRevision()).isNotNull(); + + long revision = sd.discoverInstancesRevision(r -> r + .namespaceName(namespaceName).serviceName(serviceName)).instancesRevision(); + assertThat(revision).isEqualTo(resp.instancesRevision()); + } + + @Test + @Order(9) + void getInstancesHealthStatus() { + GetInstancesHealthStatusResponse resp = sd.getInstancesHealthStatus(r -> r.serviceId(serviceId)); + assertThat(resp.status()).containsEntry(INSTANCE_ID, HealthStatus.HEALTHY); + } + + @Test + @Order(10) + void listOperationsFilteredByNamespace() { + ListOperationsResponse resp = sd.listOperations(r -> r.filters( + OperationFilter.builder() + .name(OperationFilterName.NAMESPACE_ID) + .condition(FilterCondition.EQ) + .values(namespaceId) + .build())); + assertThat(resp.operations()).isNotEmpty(); + } + + @Test + @Order(11) + void deleteServiceWhileInstancesRegisteredFails() { + assertThatThrownBy(() -> sd.deleteService(r -> r.id(serviceId))) + .isInstanceOf(ResourceInUseException.class); + } + + @Test + @Order(12) + void teardown() { + DeregisterInstanceResponse dereg = sd.deregisterInstance( + r -> r.serviceId(serviceId).instanceId(INSTANCE_ID)); + assertThat(dereg.operationId()).isNotBlank(); + awaitSuccess(dereg.operationId()); + + sd.deleteService(r -> r.id(serviceId)); + DeleteNamespaceResponse del = sd.deleteNamespace(r -> r.id(namespaceId)); + assertThat(del.operationId()).isNotBlank(); + } + + @Test + @Order(13) + void getMissingNamespaceThrows() { + assertThatThrownBy(() -> sd.getNamespace(r -> r.id("ns-doesnotexist00000"))) + .isInstanceOf(NamespaceNotFoundException.class); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index fe6f02fcb0..13db3ed8ff 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -322,6 +322,7 @@ public interface EmulatorConfig { ElastiCacheServiceConfig elasticache(); RdsServiceConfig rds(); EventBridgeServiceConfig eventbridge(); + CloudMapServiceConfig cloudmap(); SchedulerServiceConfig scheduler(); CloudWatchLogsServiceConfig cloudwatchlogs(); CloudWatchMetricsServiceConfig cloudwatchmetrics(); @@ -549,6 +550,16 @@ public interface EmulatorConfig { boolean enabled(); } + interface CloudMapServiceConfig { + @WithDefault("true") + boolean enabled(); + + /** Delay before an async operation (CreateNamespace, RegisterInstance, …) + * transitions from PENDING to SUCCESS. 0 = complete immediately. */ + @WithDefault("0") + int operationCompletionDelaySeconds(); + } + interface SchedulerServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index f01017d1a7..cdd72ee890 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.transcribe.TranscribeJsonHandler; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler; import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler; +import io.github.hectorvent.floci.services.cloudmap.CloudMapHandler; import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler; import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler; import io.github.hectorvent.floci.services.kms.KmsJsonHandler; @@ -54,6 +55,7 @@ public class AwsJson11Controller { private final RegionResolver regionResolver; private final SsmJsonHandler ssmJsonHandler; private final EventBridgeHandler eventBridgeHandler; + private final CloudMapHandler cloudMapHandler; private final CloudWatchLogsHandler cloudWatchLogsHandler; private final SecretsManagerJsonHandler secretsManagerJsonHandler; private final KinesisJsonHandler kinesisJsonHandler; @@ -83,6 +85,7 @@ public class AwsJson11Controller { public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog, RegionResolver regionResolver, SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler, + CloudMapHandler cloudMapHandler, CloudWatchLogsHandler cloudWatchLogsHandler, SecretsManagerJsonHandler secretsManagerJsonHandler, KinesisJsonHandler kinesisJsonHandler, @@ -109,6 +112,7 @@ public class AwsJson11Controller { this.regionResolver = regionResolver; this.ssmJsonHandler = ssmJsonHandler; this.eventBridgeHandler = eventBridgeHandler; + this.cloudMapHandler = cloudMapHandler; this.cloudWatchLogsHandler = cloudWatchLogsHandler; this.secretsManagerJsonHandler = secretsManagerJsonHandler; this.kinesisJsonHandler = kinesisJsonHandler; @@ -163,6 +167,7 @@ public class AwsJson11Controller { Response delegated = switch (serviceKey) { case "ssm" -> ssmJsonHandler.handle(action, request, region); case "events" -> eventBridgeHandler.handle(action, request, region); + case "servicediscovery" -> cloudMapHandler.handle(action, request, region); case "logs" -> cloudWatchLogsHandler.handle(action, request, region); case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region); case "kinesis" -> kinesisJsonHandler.handle(action, request, region); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 445d4275f4..41fc672ded 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -98,6 +98,10 @@ public class ResolvedServiceCatalog { "eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), Set.of("AWSEvents."), Set.of("events"), Set.of(), Set.of()), + descriptor("servicediscovery", "cloudmap", config.services().cloudmap().enabled(), true, + "cloudmap", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("Route53AutoNaming_v20170314."), Set.of("servicediscovery"), Set.of(), Set.of()), descriptor("scheduler", "scheduler", config.services().scheduler().enabled(), true, "scheduler", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapHandler.java new file mode 100644 index 0000000000..2835eacf45 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapHandler.java @@ -0,0 +1,429 @@ +package io.github.hectorvent.floci.services.cloudmap; + +import com.fasterxml.jackson.databind.JsonNode; +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.AwsException; +import io.github.hectorvent.floci.core.common.AwsJson11Controller; +import io.github.hectorvent.floci.services.cloudmap.model.Instance; +import io.github.hectorvent.floci.services.cloudmap.model.Namespace; +import io.github.hectorvent.floci.services.cloudmap.model.Operation; +import io.github.hectorvent.floci.services.cloudmap.model.Service; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Cloud Map (servicediscovery) JSON 1.1 handler. Dispatched from + * {@link AwsJson11Controller} under the {@code Route53AutoNaming_v20170314.} target prefix. + */ +@ApplicationScoped +public class CloudMapHandler { + + private static final Logger LOG = Logger.getLogger(CloudMapHandler.class); + + private final CloudMapService service; + private final ObjectMapper objectMapper; + + @Inject + public CloudMapHandler(CloudMapService service, ObjectMapper objectMapper) { + this.service = service; + this.objectMapper = objectMapper; + } + + public Response handle(String action, JsonNode request, String region) { + LOG.debugv("CloudMap action: {0}", action); + try { + return switch (action) { + case "CreateHttpNamespace" -> opResponse(service.createHttpNamespace( + text(request, "Name"), text(request, "CreatorRequestId"), + text(request, "Description"), parseTags(request), region)); + case "CreatePublicDnsNamespace" -> opResponse(service.createPublicDnsNamespace( + text(request, "Name"), text(request, "CreatorRequestId"), + text(request, "Description"), parseTags(request), region)); + case "CreatePrivateDnsNamespace" -> opResponse(service.createPrivateDnsNamespace( + text(request, "Name"), text(request, "Vpc"), text(request, "CreatorRequestId"), + text(request, "Description"), parseTags(request), region)); + case "GetNamespace" -> handleGetNamespace(request); + case "ListNamespaces" -> handleListNamespaces(region); + case "DeleteNamespace" -> opResponse(service.deleteNamespace(text(request, "Id"), region)); + case "GetOperation" -> handleGetOperation(request); + case "ListOperations" -> handleListOperations(request, region); + case "CreateService" -> handleCreateService(request, region); + case "GetService" -> handleGetService(request); + case "ListServices" -> handleListServices(request, region); + case "DeleteService" -> handleDeleteService(request); + case "RegisterInstance" -> opResponse(service.registerInstance( + text(request, "ServiceId"), text(request, "InstanceId"), + text(request, "CreatorRequestId"), parseAttributes(request.path("Attributes")), region)); + case "DeregisterInstance" -> opResponse(service.deregisterInstance( + text(request, "ServiceId"), text(request, "InstanceId"), region)); + case "GetInstance" -> handleGetInstance(request); + case "ListInstances" -> handleListInstances(request); + case "GetInstancesHealthStatus" -> handleGetInstancesHealthStatus(request); + case "DiscoverInstances" -> handleDiscoverInstances(request, region); + case "DiscoverInstancesRevision" -> handleDiscoverInstancesRevision(request, region); + case "TagResource" -> handleTagResource(request); + case "UntagResource" -> handleUntagResource(request); + case "ListTagsForResource" -> handleListTagsForResource(request); + default -> Response.status(400) + .entity(new AwsErrorResponse("UnknownOperationException", + "Operation " + action + " is not supported.")) + .build(); + }; + } catch (AwsException e) { + return Response.status(e.getHttpStatus()) + .entity(new AwsErrorResponse(e.jsonType(), e.getMessage())) + .build(); + } catch (Exception e) { + LOG.errorv("CloudMap error processing action {0}: {1}", action, e.getMessage()); + return Response.status(500) + .entity(new AwsErrorResponse("InternalFailure", e.getMessage())) + .build(); + } + } + + // ──────────────────────────── Namespaces ──────────────────────────── + + private Response handleGetNamespace(JsonNode request) { + Namespace ns = service.getNamespace(text(request, "Id")); + ObjectNode response = objectMapper.createObjectNode(); + response.set("Namespace", buildNamespaceNode(ns)); + return Response.ok(response).build(); + } + + private Response handleListNamespaces(String region) { + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode arr = response.putArray("Namespaces"); + for (Namespace ns : service.listNamespaces(region)) { + arr.add(buildNamespaceNode(ns)); + } + return Response.ok(response).build(); + } + + // ──────────────────────────── Operations ──────────────────────────── + + private Response handleGetOperation(JsonNode request) { + Operation op = service.getOperation(text(request, "OperationId")); + ObjectNode response = objectMapper.createObjectNode(); + response.set("Operation", buildOperationNode(op)); + return Response.ok(response).build(); + } + + private Response handleListOperations(JsonNode request, String region) { + Map> filters = parseFilters(request); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode arr = response.putArray("Operations"); + for (Operation op : service.listOperations(region, filters)) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", op.getId()); + node.put("Status", op.getStatus()); + arr.add(node); + } + return Response.ok(response).build(); + } + + // ──────────────────────────── Services ──────────────────────────── + + private Response handleCreateService(JsonNode request, String region) { + Service created = service.createService( + text(request, "Name"), text(request, "NamespaceId"), text(request, "CreatorRequestId"), + text(request, "Description"), rawJson(request.path("DnsConfig")), + rawJson(request.path("HealthCheckConfig")), rawJson(request.path("HealthCheckCustomConfig")), + text(request, "Type"), parseTags(request), region); + ObjectNode response = objectMapper.createObjectNode(); + response.set("Service", buildServiceNode(created)); + return Response.ok(response).build(); + } + + private Response handleGetService(JsonNode request) { + Service s = service.getService(text(request, "Id")); + ObjectNode response = objectMapper.createObjectNode(); + response.set("Service", buildServiceNode(s)); + return Response.ok(response).build(); + } + + private Response handleListServices(JsonNode request, String region) { + Map> filters = parseFilters(request); + String namespaceId = filters.containsKey("NAMESPACE_ID") && !filters.get("NAMESPACE_ID").isEmpty() + ? filters.get("NAMESPACE_ID").get(0) : null; + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode arr = response.putArray("Services"); + for (Service s : service.listServices(region, namespaceId)) { + arr.add(buildServiceSummaryNode(s)); + } + return Response.ok(response).build(); + } + + private Response handleDeleteService(JsonNode request) { + service.deleteService(text(request, "Id")); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + // ──────────────────────────── Instances ──────────────────────────── + + private Response handleGetInstance(JsonNode request) { + Instance instance = service.getInstance(text(request, "ServiceId"), text(request, "InstanceId")); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode node = response.putObject("Instance"); + node.put("Id", instance.getInstanceId()); + if (instance.getCreatorRequestId() != null) { + node.put("CreatorRequestId", instance.getCreatorRequestId()); + } + node.set("Attributes", attributesNode(instance.getAttributes())); + return Response.ok(response).build(); + } + + private Response handleListInstances(JsonNode request) { + List instances = service.listInstances(text(request, "ServiceId")); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode arr = response.putArray("Instances"); + for (Instance i : instances) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", i.getInstanceId()); + node.set("Attributes", attributesNode(i.getAttributes())); + arr.add(node); + } + return Response.ok(response).build(); + } + + private Response handleGetInstancesHealthStatus(JsonNode request) { + List ids = new ArrayList<>(); + request.path("Instances").forEach(n -> ids.add(n.asText())); + Map status = service.getInstancesHealthStatus(text(request, "ServiceId"), ids); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode statusNode = response.putObject("Status"); + status.forEach(statusNode::put); + return Response.ok(response).build(); + } + + // ──────────────────────────── Discovery ──────────────────────────── + + private Response handleDiscoverInstances(JsonNode request, String region) { + Integer maxResults = request.has("MaxResults") ? request.path("MaxResults").asInt() : null; + CloudMapService.DiscoverResult result = service.discoverInstances( + text(request, "NamespaceName"), text(request, "ServiceName"), + text(request, "HealthStatus"), parseAttributes(request.path("QueryParameters")), + maxResults, region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode arr = response.putArray("Instances"); + for (Instance i : result.instances()) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("InstanceId", i.getInstanceId()); + node.put("NamespaceName", text(request, "NamespaceName")); + node.put("ServiceName", text(request, "ServiceName")); + node.put("HealthStatus", i.getHealthStatus()); + node.set("Attributes", attributesNode(i.getAttributes())); + arr.add(node); + } + response.put("InstancesRevision", result.revision()); + return Response.ok(response).build(); + } + + private Response handleDiscoverInstancesRevision(JsonNode request, String region) { + long revision = service.discoverInstancesRevision( + text(request, "NamespaceName"), text(request, "ServiceName"), region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("InstancesRevision", revision); + return Response.ok(response).build(); + } + + // ──────────────────────────── Tags ──────────────────────────── + + private Response handleTagResource(JsonNode request) { + service.tagResource(text(request, "ResourceARN"), parseTags(request)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleUntagResource(JsonNode request) { + List keys = new ArrayList<>(); + request.path("TagKeys").forEach(k -> keys.add(k.asText())); + service.untagResource(text(request, "ResourceARN"), keys); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListTagsForResource(JsonNode request) { + Map tags = service.listTagsForResource(text(request, "ResourceARN")); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode arr = response.putArray("Tags"); + tags.forEach((k, v) -> { + ObjectNode tagNode = objectMapper.createObjectNode(); + tagNode.put("Key", k); + tagNode.put("Value", v); + arr.add(tagNode); + }); + return Response.ok(response).build(); + } + + // ──────────────────────────── Builders ──────────────────────────── + + private Response opResponse(Operation op) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("OperationId", op.getId()); + return Response.ok(response).build(); + } + + private ObjectNode buildNamespaceNode(Namespace ns) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", ns.getId()); + node.put("Arn", ns.getArn()); + node.put("Name", ns.getName()); + node.put("Type", ns.getType()); + if (ns.getDescription() != null) { + node.put("Description", ns.getDescription()); + } + node.put("ServiceCount", ns.getServiceCount()); + if (ns.getCreateDate() != null) { + node.put("CreateDate", ns.getCreateDate().getEpochSecond()); + } + if (ns.getCreatorRequestId() != null) { + node.put("CreatorRequestId", ns.getCreatorRequestId()); + } + node.set("Properties", buildNamespaceProperties(ns)); + return node; + } + + private ObjectNode buildNamespaceProperties(Namespace ns) { + ObjectNode props = objectMapper.createObjectNode(); + if (!"HTTP".equals(ns.getType())) { + ObjectNode dns = props.putObject("DnsProperties"); + if (ns.getHostedZoneId() != null) { + dns.put("HostedZoneId", ns.getHostedZoneId()); + } + dns.putObject("SOA").put("TTL", 15); + } + props.putObject("HttpProperties").put("HttpName", ns.getName()); + return props; + } + + private ObjectNode buildServiceNode(Service s) { + ObjectNode node = buildServiceSummaryNode(s); + if (s.getNamespaceId() != null) { + node.put("NamespaceId", s.getNamespaceId()); + } + if (s.getCreatorRequestId() != null) { + node.put("CreatorRequestId", s.getCreatorRequestId()); + } + return node; + } + + private ObjectNode buildServiceSummaryNode(Service s) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", s.getId()); + node.put("Arn", s.getArn()); + node.put("Name", s.getName()); + if (s.getType() != null) { + node.put("Type", s.getType()); + } + if (s.getDescription() != null) { + node.put("Description", s.getDescription()); + } + node.put("InstanceCount", s.getInstanceCount()); + setRawJson(node, "DnsConfig", s.getDnsConfig()); + setRawJson(node, "HealthCheckConfig", s.getHealthCheckConfig()); + setRawJson(node, "HealthCheckCustomConfig", s.getHealthCheckCustomConfig()); + if (s.getCreateDate() != null) { + node.put("CreateDate", s.getCreateDate().getEpochSecond()); + } + return node; + } + + private ObjectNode buildOperationNode(Operation op) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", op.getId()); + node.put("Type", op.getType()); + node.put("Status", op.getStatus()); + if (op.getErrorMessage() != null) { + node.put("ErrorMessage", op.getErrorMessage()); + } + if (op.getErrorCode() != null) { + node.put("ErrorCode", op.getErrorCode()); + } + if (op.getCreateDate() != null) { + node.put("CreateDate", op.getCreateDate().getEpochSecond()); + } + if (op.getUpdateDate() != null) { + node.put("UpdateDate", op.getUpdateDate().getEpochSecond()); + } + ObjectNode targets = node.putObject("Targets"); + op.getTargets().forEach(targets::put); + return node; + } + + private ObjectNode attributesNode(Map attributes) { + ObjectNode node = objectMapper.createObjectNode(); + if (attributes != null) { + attributes.forEach(node::put); + } + return node; + } + + // ──────────────────────────── Parsing ──────────────────────────── + + private Map> parseFilters(JsonNode request) { + Map> filters = new LinkedHashMap<>(); + JsonNode filtersNode = request.path("Filters"); + if (filtersNode.isArray()) { + for (JsonNode f : filtersNode) { + String name = f.path("Name").asText(null); + if (name == null) { + continue; + } + List values = new ArrayList<>(); + f.path("Values").forEach(v -> values.add(v.asText())); + filters.put(name, values); + } + } + return filters; + } + + private Map parseAttributes(JsonNode attributesNode) { + Map attributes = new LinkedHashMap<>(); + if (attributesNode != null && attributesNode.isObject()) { + attributesNode.fields().forEachRemaining(e -> attributes.put(e.getKey(), e.getValue().asText())); + } + return attributes; + } + + private Map parseTags(JsonNode request) { + Map tags = new LinkedHashMap<>(); + JsonNode tagsNode = request.path("Tags"); + if (tagsNode.isArray()) { + for (JsonNode tag : tagsNode) { + String key = tag.path("Key").asText(null); + if (key != null) { + tags.put(key, tag.path("Value").asText(null)); + } + } + } + return tags; + } + + private String text(JsonNode request, String field) { + JsonNode node = request.path(field); + return node.isMissingNode() || node.isNull() ? null : node.asText(null); + } + + private String rawJson(JsonNode node) { + return (node != null && node.isObject() && !node.isEmpty()) ? node.toString() : null; + } + + private void setRawJson(ObjectNode target, String field, String rawJson) { + if (rawJson == null) { + return; + } + try { + target.set(field, objectMapper.readTree(rawJson)); + } catch (Exception e) { + LOG.warnv("Failed to parse stored {0} JSON; field omitted. Value: {1}", field, rawJson); + } + } +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java new file mode 100644 index 0000000000..d6957bb420 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java @@ -0,0 +1,556 @@ +package io.github.hectorvent.floci.services.cloudmap; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.cloudmap.model.Instance; +import io.github.hectorvent.floci.services.cloudmap.model.Namespace; +import io.github.hectorvent.floci.services.cloudmap.model.Operation; +import io.github.hectorvent.floci.services.cloudmap.model.Service; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.security.SecureRandom; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Cloud Map (AWS service discovery) business logic. Mirrors the EventBridge service + * pattern: ID-keyed account-aware storage, {@link AwsException} for domain errors. + * Async operations apply their effect synchronously and record an {@link Operation} + * whose status reaches SUCCESS immediately (or after a configurable delay). + */ +@ApplicationScoped +public class CloudMapService { + + private static final Logger LOG = Logger.getLogger(CloudMapService.class); + private static final String ALNUM = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static final SecureRandom RANDOM = new SecureRandom(); + + private final StorageBackend namespaceStore; + private final StorageBackend serviceStore; + private final StorageBackend instanceStore; + private final StorageBackend operationStore; + private final RegionResolver regionResolver; + private final int completionDelaySeconds; + private final ScheduledExecutorService scheduler; + + @Inject + public CloudMapService(StorageFactory storageFactory, EmulatorConfig config, + RegionResolver regionResolver) { + this.namespaceStore = storageFactory.create("cloudmap", "cloudmap-namespaces.json", + new TypeReference>() {}); + this.serviceStore = storageFactory.create("cloudmap", "cloudmap-services.json", + new TypeReference>() {}); + this.instanceStore = storageFactory.create("cloudmap", "cloudmap-instances.json", + new TypeReference>() {}); + this.operationStore = storageFactory.create("cloudmap", "cloudmap-operations.json", + new TypeReference>() {}); + this.regionResolver = regionResolver; + this.completionDelaySeconds = config.services().cloudmap().operationCompletionDelaySeconds(); + this.scheduler = completionDelaySeconds > 0 + ? Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "cloudmap-ops"); + t.setDaemon(true); + return t; + }) + : null; + } + + // ──────────────────────────── Namespaces ──────────────────────────── + + public Operation createHttpNamespace(String name, String creatorRequestId, + String description, Map tags, String region) { + Namespace ns = newNamespace(name, "HTTP", description, creatorRequestId, tags, region); + namespaceStore.put(ns.getId(), ns); + return submitOperation("CREATE_NAMESPACE", "NAMESPACE", ns.getId(), region); + } + + public Operation createPublicDnsNamespace(String name, String creatorRequestId, + String description, Map tags, String region) { + Namespace ns = newNamespace(name, "DNS_PUBLIC", description, creatorRequestId, tags, region); + ns.setHostedZoneId(generateHostedZoneId()); + namespaceStore.put(ns.getId(), ns); + return submitOperation("CREATE_NAMESPACE", "NAMESPACE", ns.getId(), region); + } + + public Operation createPrivateDnsNamespace(String name, String vpc, String creatorRequestId, + String description, Map tags, String region) { + if (vpc == null || vpc.isBlank()) { + throw new AwsException("InvalidInput", "Vpc is required for a private DNS namespace.", 400); + } + Namespace ns = newNamespace(name, "DNS_PRIVATE", description, creatorRequestId, tags, region); + ns.setVpc(vpc); + ns.setHostedZoneId(generateHostedZoneId()); + namespaceStore.put(ns.getId(), ns); + return submitOperation("CREATE_NAMESPACE", "NAMESPACE", ns.getId(), region); + } + + private Namespace newNamespace(String name, String type, String description, + String creatorRequestId, Map tags, String region) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidInput", "Namespace name is required.", 400); + } + boolean exists = scan(namespaceStore).stream() + .anyMatch(n -> region.equals(n.getRegion()) && name.equals(n.getName())); + if (exists) { + throw new AwsException("NamespaceAlreadyExists", + "A namespace named \"" + name + "\" already exists.", 400); + } + Namespace ns = new Namespace(); + ns.setId("ns-" + randomId(20)); + ns.setName(name); + ns.setType(type); + ns.setDescription(description); + ns.setCreatorRequestId(creatorRequestId != null ? creatorRequestId : UUID.randomUUID().toString()); + ns.setCreateDate(Instant.now()); + ns.setRegion(region); + ns.setServiceCount(0); + if (tags != null) { + ns.setTags(tags); + } + ns.setArn(regionResolver.buildArn("servicediscovery", region, "namespace/" + ns.getId())); + return ns; + } + + public Namespace getNamespace(String id) { + return requireNamespace(id); + } + + public List listNamespaces(String region) { + List result = new ArrayList<>(); + for (Namespace n : scan(namespaceStore)) { + if (region.equals(n.getRegion())) { + result.add(n); + } + } + return result; + } + + public Operation deleteNamespace(String id, String region) { + Namespace ns = requireNamespace(id); + boolean hasServices = scan(serviceStore).stream() + .anyMatch(s -> ns.getId().equals(s.getNamespaceId())); + if (hasServices) { + throw new AwsException("ResourceInUse", + "The namespace contains existing services and cannot be deleted.", 400); + } + namespaceStore.delete(id); + return submitOperation("DELETE_NAMESPACE", "NAMESPACE", id, region); + } + + // ──────────────────────────── Services ──────────────────────────── + + public Service createService(String name, String namespaceId, String creatorRequestId, + String description, String dnsConfig, String healthCheckConfig, + String healthCheckCustomConfig, String type, + Map tags, String region) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidInput", "Service name is required.", 400); + } + String resolvedNamespaceId = namespaceId; + if (dnsConfig != null && resolvedNamespaceId == null) { + // DnsConfig may carry the namespace id when the top-level field is absent. + resolvedNamespaceId = dnsConfigNamespaceId(dnsConfig); + } + if (resolvedNamespaceId != null) { + requireNamespace(resolvedNamespaceId); + } + final String nsId = resolvedNamespaceId; + boolean exists = scan(serviceStore).stream() + .anyMatch(s -> region.equals(s.getRegion()) && name.equals(s.getName()) + && java.util.Objects.equals(nsId, s.getNamespaceId())); + if (exists) { + throw new AwsException("ServiceAlreadyExists", + "A service named \"" + name + "\" already exists.", 400); + } + Service service = new Service(); + service.setId("srv-" + randomId(20)); + service.setName(name); + service.setNamespaceId(nsId); + service.setDescription(description); + service.setDnsConfig(dnsConfig); + service.setHealthCheckConfig(healthCheckConfig); + service.setHealthCheckCustomConfig(healthCheckCustomConfig); + service.setType(resolveServiceType(type, dnsConfig)); + service.setCreatorRequestId(creatorRequestId != null ? creatorRequestId : UUID.randomUUID().toString()); + service.setCreateDate(Instant.now()); + service.setRegion(region); + service.setInstanceCount(0); + service.setRevision(0L); + if (tags != null) { + service.setTags(tags); + } + service.setArn(regionResolver.buildArn("servicediscovery", region, "service/" + service.getId())); + serviceStore.put(service.getId(), service); + if (nsId != null) { + namespaceStore.get(nsId).ifPresent(n -> { + n.setServiceCount(n.getServiceCount() + 1); + namespaceStore.put(n.getId(), n); + }); + } + return service; + } + + public Service getService(String id) { + return requireService(id); + } + + public List listServices(String region, String namespaceIdFilter) { + List result = new ArrayList<>(); + for (Service s : scan(serviceStore)) { + if (!region.equals(s.getRegion())) { + continue; + } + if (namespaceIdFilter != null && !namespaceIdFilter.equals(s.getNamespaceId())) { + continue; + } + result.add(s); + } + return result; + } + + public void deleteService(String id) { + Service service = requireService(id); + boolean hasInstances = !scanInstances(service.getId()).isEmpty(); + if (hasInstances) { + throw new AwsException("ResourceInUse", + "The service contains registered instances and cannot be deleted.", 400); + } + serviceStore.delete(id); + if (service.getNamespaceId() != null) { + namespaceStore.get(service.getNamespaceId()).ifPresent(n -> { + n.setServiceCount(Math.max(0, n.getServiceCount() - 1)); + namespaceStore.put(n.getId(), n); + }); + } + } + + // ──────────────────────────── Instances ──────────────────────────── + + public Operation registerInstance(String serviceId, String instanceId, String creatorRequestId, + Map attributes, String region) { + Service service = requireService(serviceId); + if (instanceId == null || instanceId.isBlank()) { + throw new AwsException("InvalidInput", "InstanceId is required.", 400); + } + if (attributes == null || attributes.isEmpty()) { + throw new AwsException("InvalidInput", "Attributes are required.", 400); + } + Instance instance = new Instance(); + instance.setInstanceId(instanceId); + instance.setServiceId(serviceId); + instance.setCreatorRequestId(creatorRequestId != null ? creatorRequestId : UUID.randomUUID().toString()); + instance.setAttributes(attributes); + boolean isNew = instanceStore.get(instanceKey(serviceId, instanceId)).isEmpty(); + instanceStore.put(instanceKey(serviceId, instanceId), instance); + if (isNew) { + service.setInstanceCount(service.getInstanceCount() + 1); + } + service.setRevision(service.getRevision() + 1); + serviceStore.put(service.getId(), service); + return submitOperation("REGISTER_INSTANCE", "INSTANCE", instanceId, region); + } + + public Operation deregisterInstance(String serviceId, String instanceId, String region) { + Service service = requireService(serviceId); + if (instanceStore.get(instanceKey(serviceId, instanceId)).isEmpty()) { + throw new AwsException("InstanceNotFound", "Instance not found: " + instanceId, 404); + } + instanceStore.delete(instanceKey(serviceId, instanceId)); + service.setInstanceCount(Math.max(0, service.getInstanceCount() - 1)); + service.setRevision(service.getRevision() + 1); + serviceStore.put(service.getId(), service); + return submitOperation("DEREGISTER_INSTANCE", "INSTANCE", instanceId, region); + } + + public Instance getInstance(String serviceId, String instanceId) { + requireService(serviceId); + return instanceStore.get(instanceKey(serviceId, instanceId)) + .orElseThrow(() -> new AwsException("InstanceNotFound", "Instance not found: " + instanceId, 404)); + } + + public List listInstances(String serviceId) { + requireService(serviceId); + return scanInstances(serviceId); + } + + public Map getInstancesHealthStatus(String serviceId, List instanceIds) { + requireService(serviceId); + Map status = new LinkedHashMap<>(); + for (Instance i : scanInstances(serviceId)) { + if (instanceIds == null || instanceIds.isEmpty() || instanceIds.contains(i.getInstanceId())) { + status.put(i.getInstanceId(), i.getHealthStatus()); + } + } + if (status.isEmpty() && instanceIds != null && !instanceIds.isEmpty()) { + throw new AwsException("InstanceNotFound", "No matching instances found.", 404); + } + return status; + } + + // ──────────────────────────── Discovery ──────────────────────────── + + public record DiscoverResult(List instances, long revision) {} + + public DiscoverResult discoverInstances(String namespaceName, String serviceName, + String healthFilter, Map queryParameters, + Integer maxResults, String region) { + Service service = resolveService(namespaceName, serviceName, region); + List all = scanInstances(service.getId()); + List filtered = applyHealthFilter(all, healthFilter); + if (queryParameters != null && !queryParameters.isEmpty()) { + filtered = filtered.stream() + .filter(i -> queryParameters.entrySet().stream() + .allMatch(e -> e.getValue().equals(i.getAttributes().get(e.getKey())))) + .toList(); + } + if (maxResults != null && maxResults > 0 && filtered.size() > maxResults) { + filtered = filtered.subList(0, maxResults); + } + return new DiscoverResult(filtered, service.getRevision()); + } + + public long discoverInstancesRevision(String namespaceName, String serviceName, String region) { + return resolveService(namespaceName, serviceName, region).getRevision(); + } + + private List applyHealthFilter(List instances, String healthFilter) { + String filter = healthFilter == null ? "ALL" : healthFilter; + return switch (filter) { + case "HEALTHY" -> instances.stream().filter(i -> "HEALTHY".equals(i.getHealthStatus())).toList(); + case "UNHEALTHY" -> instances.stream().filter(i -> "UNHEALTHY".equals(i.getHealthStatus())).toList(); + case "HEALTHY_OR_ELSE_ALL" -> { + List healthy = instances.stream() + .filter(i -> "HEALTHY".equals(i.getHealthStatus())).toList(); + yield healthy.isEmpty() ? instances : healthy; + } + default -> instances; + }; + } + + private Service resolveService(String namespaceName, String serviceName, String region) { + Namespace ns = scan(namespaceStore).stream() + .filter(n -> region.equals(n.getRegion()) && namespaceName.equals(n.getName())) + .findFirst() + .orElseThrow(() -> new AwsException("NamespaceNotFound", + "Namespace not found: " + namespaceName, 404)); + return scan(serviceStore).stream() + .filter(s -> serviceName.equals(s.getName()) && ns.getId().equals(s.getNamespaceId())) + .findFirst() + .orElseThrow(() -> new AwsException("ServiceNotFound", + "Service not found: " + serviceName, 404)); + } + + // ──────────────────────────── Operations ──────────────────────────── + + public Operation getOperation(String id) { + return operationStore.get(id) + .orElseThrow(() -> new AwsException("OperationNotFound", "Operation not found: " + id, 404)); + } + + public List listOperations(String region, Map> filters) { + List result = new ArrayList<>(); + for (Operation op : scan(operationStore)) { + if (!region.equals(op.getRegion())) { + continue; + } + if (matchesOperationFilters(op, filters)) { + result.add(op); + } + } + return result; + } + + private boolean matchesOperationFilters(Operation op, Map> filters) { + if (filters == null || filters.isEmpty()) { + return true; + } + for (Map.Entry> f : filters.entrySet()) { + List values = f.getValue(); + boolean ok = switch (f.getKey()) { + case "STATUS" -> values.contains(op.getStatus()); + case "TYPE" -> values.contains(op.getType()); + case "NAMESPACE_ID" -> values.contains(op.getTargets().get("NAMESPACE")); + case "SERVICE_ID" -> values.contains(op.getTargets().get("SERVICE")); + default -> true; + }; + if (!ok) { + return false; + } + } + return true; + } + + private Operation submitOperation(String type, String targetType, String targetId, String region) { + Operation op = new Operation(); + op.setId(randomId(32) + "-" + randomId(8)); + op.setType(type); + op.setCreateDate(Instant.now()); + op.setUpdateDate(Instant.now()); + op.setRegion(region); + op.getTargets().put(targetType, targetId); + if (scheduler == null) { + op.setStatus("SUCCESS"); + operationStore.put(op.getId(), op); + } else { + op.setStatus("PENDING"); + operationStore.put(op.getId(), op); + String accountId = regionResolver.getAccountId(); + scheduler.schedule(() -> completeOperation(accountId, op.getId()), + completionDelaySeconds, TimeUnit.SECONDS); + } + return op; + } + + private void completeOperation(String accountId, String operationId) { + try { + if (operationStore instanceof AccountAwareStorageBackend aware) { + aware.getForAccount(accountId, operationId).ifPresent(op -> { + op.setStatus("SUCCESS"); + op.setUpdateDate(Instant.now()); + aware.putForAccount(accountId, operationId, op); + }); + } + } catch (Exception e) { + LOG.warnv("Failed to complete Cloud Map operation {0}: {1}", operationId, e.getMessage()); + } + } + + // ──────────────────────────── Tags ──────────────────────────── + + public Map listTagsForResource(String resourceArn) { + return taggable(resourceArn).getTags(); + } + + public void tagResource(String resourceArn, Map tags) { + Object resource = taggableRaw(resourceArn); + if (resource instanceof Namespace ns) { + ns.getTags().putAll(tags); + namespaceStore.put(ns.getId(), ns); + } else if (resource instanceof Service s) { + s.getTags().putAll(tags); + serviceStore.put(s.getId(), s); + } + } + + public void untagResource(String resourceArn, List tagKeys) { + Object resource = taggableRaw(resourceArn); + if (resource instanceof Namespace ns) { + tagKeys.forEach(ns.getTags()::remove); + namespaceStore.put(ns.getId(), ns); + } else if (resource instanceof Service s) { + tagKeys.forEach(s.getTags()::remove); + serviceStore.put(s.getId(), s); + } + } + + private interface Taggable { Map getTags(); } + + private Taggable taggable(String resourceArn) { + Object raw = taggableRaw(resourceArn); + if (raw instanceof Namespace ns) { + return ns::getTags; + } + return ((Service) raw)::getTags; + } + + private Object taggableRaw(String resourceArn) { + if (resourceArn == null) { + throw new AwsException("InvalidInput", "ResourceARN is required.", 400); + } + int slash = resourceArn.lastIndexOf('/'); + int colon = resourceArn.lastIndexOf(':'); + String id = resourceArn.substring(Math.max(slash, colon) + 1); + Optional ns = namespaceStore.get(id); + if (ns.isPresent()) { + return ns.get(); + } + return serviceStore.get(id).orElseThrow(() -> + new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 404)); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private Namespace requireNamespace(String id) { + if (id == null) { + throw new AwsException("InvalidInput", "Namespace id is required.", 400); + } + return namespaceStore.get(id) + .orElseThrow(() -> new AwsException("NamespaceNotFound", "Namespace not found: " + id, 404)); + } + + private Service requireService(String id) { + if (id == null) { + throw new AwsException("InvalidInput", "Service id is required.", 400); + } + return serviceStore.get(id) + .orElseThrow(() -> new AwsException("ServiceNotFound", "Service not found: " + id, 404)); + } + + private List scanInstances(String serviceId) { + List result = new ArrayList<>(); + for (Instance i : scan(instanceStore)) { + if (serviceId.equals(i.getServiceId())) { + result.add(i); + } + } + return result; + } + + private List scan(StorageBackend store) { + return store.scan(k -> true); + } + + private String instanceKey(String serviceId, String instanceId) { + return serviceId + "/" + instanceId; + } + + private String resolveServiceType(String type, String dnsConfig) { + if (type != null && !type.isBlank()) { + return "HTTP".equals(type) ? "HTTP" : type; + } + return dnsConfig != null ? "DNS_HTTP" : "HTTP"; + } + + private String dnsConfigNamespaceId(String dnsConfig) { + // Best-effort extraction of a NamespaceId embedded in the DnsConfig JSON. + int idx = dnsConfig.indexOf("\"NamespaceId\""); + if (idx < 0) { + return null; + } + int start = dnsConfig.indexOf('"', dnsConfig.indexOf(':', idx) + 1); + int end = dnsConfig.indexOf('"', start + 1); + return (start > 0 && end > start) ? dnsConfig.substring(start + 1, end) : null; + } + + private String randomId(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = 0; i < length; i++) { + sb.append(ALNUM.charAt(RANDOM.nextInt(ALNUM.length()))); + } + return sb.toString(); + } + + private String generateHostedZoneId() { + StringBuilder sb = new StringBuilder("Z"); + String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + for (int i = 0; i < 13; i++) { + sb.append(chars.charAt(RANDOM.nextInt(chars.length()))); + } + return sb.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Instance.java new file mode 100644 index 0000000000..d7aa97f265 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Instance.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.cloudmap.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.HashMap; +import java.util.Map; + +/** + * A registered Cloud Map instance. {@code attributes} hold reserved keys + * (AWS_INSTANCE_IPV4, AWS_INSTANCE_PORT, …) plus arbitrary custom keys. + * {@code healthStatus} is HEALTHY by default and only changes via + * UpdateInstanceCustomHealthStatus (Phase 2) for custom-health services. + */ +@RegisterForReflection +public class Instance { + + private String instanceId; + private String serviceId; + private String creatorRequestId; + private String healthStatus = "HEALTHY"; + private Map attributes = new HashMap<>(); + + public Instance() {} + + public String getInstanceId() { return instanceId; } + public void setInstanceId(String instanceId) { this.instanceId = instanceId; } + + public String getServiceId() { return serviceId; } + public void setServiceId(String serviceId) { this.serviceId = serviceId; } + + public String getCreatorRequestId() { return creatorRequestId; } + public void setCreatorRequestId(String creatorRequestId) { this.creatorRequestId = creatorRequestId; } + + public String getHealthStatus() { return healthStatus; } + public void setHealthStatus(String healthStatus) { this.healthStatus = healthStatus; } + + public Map getAttributes() { return attributes; } + public void setAttributes(Map attributes) { this.attributes = attributes; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Namespace.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Namespace.java new file mode 100644 index 0000000000..a5c50e3f60 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Namespace.java @@ -0,0 +1,67 @@ +package io.github.hectorvent.floci.services.cloudmap.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +/** + * AWS Cloud Map namespace. {@code type} is one of DNS_PUBLIC, DNS_PRIVATE, HTTP. + * DNS namespaces carry a synthesized {@code hostedZoneId}; private DNS namespaces + * also record the {@code vpc} they were created against. + */ +@RegisterForReflection +public class Namespace { + + private String id; + private String arn; + private String name; + private String type; + private String description; + private int serviceCount; + private Instant createDate; + private String creatorRequestId; + private String region; + private String vpc; + private String hostedZoneId; + private Map tags = new HashMap<>(); + + public Namespace() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getType() { return type; } + public void setType(String type) { this.type = type; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public int getServiceCount() { return serviceCount; } + public void setServiceCount(int serviceCount) { this.serviceCount = serviceCount; } + + public Instant getCreateDate() { return createDate; } + public void setCreateDate(Instant createDate) { this.createDate = createDate; } + + public String getCreatorRequestId() { return creatorRequestId; } + public void setCreatorRequestId(String creatorRequestId) { this.creatorRequestId = creatorRequestId; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public String getVpc() { return vpc; } + public void setVpc(String vpc) { this.vpc = vpc; } + + public String getHostedZoneId() { return hostedZoneId; } + public void setHostedZoneId(String hostedZoneId) { this.hostedZoneId = hostedZoneId; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Operation.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Operation.java new file mode 100644 index 0000000000..908c07b24c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Operation.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.cloudmap.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +/** + * Async operation record. {@code type} is an OperationType (CREATE_NAMESPACE, …), + * {@code status} an OperationStatus (SUBMITTED|PENDING|SUCCESS|FAIL). {@code targets} + * maps an OperationTargetType (NAMESPACE|SERVICE|INSTANCE) to the affected resource id. + */ +@RegisterForReflection +public class Operation { + + private String id; + private String type; + private String status; + private String errorMessage; + private String errorCode; + private Instant createDate; + private Instant updateDate; + private String region; + private Map targets = new HashMap<>(); + + public Operation() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getType() { return type; } + public void setType(String type) { this.type = type; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getErrorMessage() { return errorMessage; } + public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } + + public String getErrorCode() { return errorCode; } + public void setErrorCode(String errorCode) { this.errorCode = errorCode; } + + public Instant getCreateDate() { return createDate; } + public void setCreateDate(Instant createDate) { this.createDate = createDate; } + + public Instant getUpdateDate() { return updateDate; } + public void setUpdateDate(Instant updateDate) { this.updateDate = updateDate; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public Map getTargets() { return targets; } + public void setTargets(Map targets) { this.targets = targets; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Service.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Service.java new file mode 100644 index 0000000000..4d9b4239fc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/model/Service.java @@ -0,0 +1,83 @@ +package io.github.hectorvent.floci.services.cloudmap.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +/** + * AWS Cloud Map service. {@code dnsConfig}, {@code healthCheckConfig} and + * {@code healthCheckCustomConfig} are stored as raw JSON strings and re-emitted + * verbatim as JSON objects so SDK clients round-trip the exact structure. + * {@code revision} is the monotonic InstancesRevision bumped on every + * register/deregister of an instance in this service. + */ +@RegisterForReflection +public class Service { + + private String id; + private String arn; + private String name; + private String namespaceId; + private String description; + private int instanceCount; + private String type; + private String dnsConfig; + private String healthCheckConfig; + private String healthCheckCustomConfig; + private Instant createDate; + private String creatorRequestId; + private String region; + private long revision; + private Map tags = new HashMap<>(); + + public Service() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getNamespaceId() { return namespaceId; } + public void setNamespaceId(String namespaceId) { this.namespaceId = namespaceId; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public int getInstanceCount() { return instanceCount; } + public void setInstanceCount(int instanceCount) { this.instanceCount = instanceCount; } + + public String getType() { return type; } + public void setType(String type) { this.type = type; } + + public String getDnsConfig() { return dnsConfig; } + public void setDnsConfig(String dnsConfig) { this.dnsConfig = dnsConfig; } + + public String getHealthCheckConfig() { return healthCheckConfig; } + public void setHealthCheckConfig(String healthCheckConfig) { this.healthCheckConfig = healthCheckConfig; } + + public String getHealthCheckCustomConfig() { return healthCheckCustomConfig; } + public void setHealthCheckCustomConfig(String healthCheckCustomConfig) { + this.healthCheckCustomConfig = healthCheckCustomConfig; + } + + public Instant getCreateDate() { return createDate; } + public void setCreateDate(Instant createDate) { this.createDate = createDate; } + + public String getCreatorRequestId() { return creatorRequestId; } + public void setCreatorRequestId(String creatorRequestId) { this.creatorRequestId = creatorRequestId; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public long getRevision() { return revision; } + public void setRevision(long revision) { this.revision = revision; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d1f8506256..e9359daebb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -189,6 +189,8 @@ floci: default-image: "tinkerpop/gremlin-server:3.7.3" eventbridge: enabled: true + cloudmap: + enabled: true scheduler: enabled: true cloudwatchlogs: diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java new file mode 100644 index 0000000000..07c35f451d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java @@ -0,0 +1,177 @@ +package io.github.hectorvent.floci.services.cloudmap; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; + +/** + * End-to-end Phase 1 flow for Cloud Map over the AWS JSON 1.1 wire protocol: + * create namespace → poll operation → create service → register instance → + * discover → deregister → delete. Mirrors the RestAssured convention used by the + * other JSON 1.1 service tests (EventBridge). + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CloudMapIntegrationTest { + + private static final String CT = "application/x-amz-json-1.1"; + private static final String PREFIX = "Route53AutoNaming_v20170314."; + + private static String namespaceId; + private static String serviceId; + private static final String INSTANCE_ID = "i-cloudmap-1"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response call(String action, String body) { + return given().contentType(CT).header("X-Amz-Target", PREFIX + action) + .body(body).when().post("/"); + } + + @Test + @Order(1) + void createHttpNamespace() { + String operationId = call("CreateHttpNamespace", + "{\"Name\":\"floci-cm-ns\",\"Description\":\"test\"}") + .then().statusCode(200) + .body("OperationId", notNullValue()) + .extract().jsonPath().getString("OperationId"); + + // Async op should be retrievable and SUCCESS (default 0s completion delay). + call("GetOperation", "{\"OperationId\":\"" + operationId + "\"}") + .then().statusCode(200) + .body("Operation.Status", equalTo("SUCCESS")) + .body("Operation.Type", equalTo("CREATE_NAMESPACE")); + } + + @Test + @Order(2) + void listNamespacesFindsIt() { + namespaceId = call("ListNamespaces", "{}") + .then().statusCode(200) + .body("Namespaces.find { it.Name == 'floci-cm-ns' }.Id", startsWith("ns-")) + .extract().jsonPath().getString("Namespaces.find { it.Name == 'floci-cm-ns' }.Id"); + } + + @Test + @Order(3) + void createService() { + serviceId = call("CreateService", + "{\"Name\":\"floci-cm-svc\",\"NamespaceId\":\"" + namespaceId + "\"}") + .then().statusCode(200) + .body("Service.Id", startsWith("srv-")) + .body("Service.Name", equalTo("floci-cm-svc")) + .body("Service.NamespaceId", equalTo(namespaceId)) + .extract().jsonPath().getString("Service.Id"); + } + + @Test + @Order(4) + void registerInstance() { + String operationId = call("RegisterInstance", + "{\"ServiceId\":\"" + serviceId + "\",\"InstanceId\":\"" + INSTANCE_ID + + "\",\"Attributes\":{\"AWS_INSTANCE_IPV4\":\"10.0.0.1\",\"AWS_INSTANCE_PORT\":\"8080\"}}") + .then().statusCode(200) + .body("OperationId", notNullValue()) + .extract().jsonPath().getString("OperationId"); + + call("GetOperation", "{\"OperationId\":\"" + operationId + "\"}") + .then().statusCode(200) + .body("Operation.Status", equalTo("SUCCESS")) + .body("Operation.Type", equalTo("REGISTER_INSTANCE")); + } + + @Test + @Order(5) + void listInstances() { + call("ListInstances", "{\"ServiceId\":\"" + serviceId + "\"}") + .then().statusCode(200) + .body("Instances", hasSize(1)) + .body("Instances[0].Id", equalTo(INSTANCE_ID)) + .body("Instances[0].Attributes.AWS_INSTANCE_IPV4", equalTo("10.0.0.1")); + } + + @Test + @Order(6) + void discoverInstancesHealthy() { + call("DiscoverInstances", + "{\"NamespaceName\":\"floci-cm-ns\",\"ServiceName\":\"floci-cm-svc\",\"HealthStatus\":\"HEALTHY\"}") + .then().statusCode(200) + .body("Instances", hasSize(1)) + .body("Instances[0].InstanceId", equalTo(INSTANCE_ID)) + .body("Instances[0].HealthStatus", equalTo("HEALTHY")) + .body("InstancesRevision", notNullValue()); + } + + @Test + @Order(7) + void discoverInstancesRevisionMatches() { + long discovered = call("DiscoverInstances", + "{\"NamespaceName\":\"floci-cm-ns\",\"ServiceName\":\"floci-cm-svc\",\"HealthStatus\":\"HEALTHY_OR_ELSE_ALL\"}") + .then().statusCode(200).extract().jsonPath().getLong("InstancesRevision"); + + call("DiscoverInstancesRevision", + "{\"NamespaceName\":\"floci-cm-ns\",\"ServiceName\":\"floci-cm-svc\"}") + .then().statusCode(200) + .body("InstancesRevision", equalTo((int) discovered)); + } + + @Test + @Order(8) + void listOperationsFilteredByNamespace() { + call("ListOperations", + "{\"Filters\":[{\"Name\":\"NAMESPACE_ID\",\"Condition\":\"EQ\",\"Values\":[\"" + namespaceId + "\"]}]}") + .then().statusCode(200) + .body("Operations.find { it.Status == 'SUCCESS' }", notNullValue()); + } + + @Test + @Order(9) + void deleteServiceWhileInstancesRegisteredFails() { + call("DeleteService", "{\"Id\":\"" + serviceId + "\"}") + .then().statusCode(400) + .body("__type", equalTo("ResourceInUse")); + } + + @Test + @Order(10) + void deleteNamespaceWithServiceFails() { + call("DeleteNamespace", "{\"Id\":\"" + namespaceId + "\"}") + .then().statusCode(400) + .body("__type", equalTo("ResourceInUse")); + } + + @Test + @Order(11) + void teardown() { + call("DeregisterInstance", + "{\"ServiceId\":\"" + serviceId + "\",\"InstanceId\":\"" + INSTANCE_ID + "\"}") + .then().statusCode(200).body("OperationId", notNullValue()); + + call("DeleteService", "{\"Id\":\"" + serviceId + "\"}").then().statusCode(200); + call("DeleteNamespace", "{\"Id\":\"" + namespaceId + "\"}") + .then().statusCode(200).body("OperationId", notNullValue()); + } + + @Test + @Order(12) + void getMissingNamespaceReturnsNotFound() { + call("GetNamespace", "{\"Id\":\"ns-doesnotexist00000\"}") + .then().statusCode(404) + .body("__type", equalTo("NamespaceNotFound")); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index fae5340a24..8b990f38cc 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -107,6 +107,8 @@ floci: default-image: "tinkerpop/gremlin-server:3.7.3" eventbridge: enabled: true + cloudmap: + enabled: true scheduler: enabled: true cloudwatchlogs: