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 50c65a7ea8..62f9ec2cbf 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -131,6 +131,7 @@ public interface EmulatorConfig { AppConfigDataStorageConfig appconfigdata(); ElastiCacheStorageConfig elasticache(); RdsStorageConfig rds(); + NeptuneStorageConfig neptune(); BackupStorageConfig backup(); } @@ -230,6 +231,10 @@ public interface EmulatorConfig { Optional mode(); } + interface NeptuneStorageConfig { + Optional mode(); + } + interface BackupStorageConfig { Optional mode(); @@ -297,6 +302,7 @@ public interface EmulatorConfig { CodeDeployServiceConfig codedeploy(); AutoScalingServiceConfig autoscaling(); BackupServiceConfig backup(); + NeptuneServiceConfig neptune(); Route53ServiceConfig route53(); TransferServiceConfig transfer(); TextractServiceConfig textract(); @@ -459,6 +465,24 @@ public interface EmulatorConfig { Optional dockerNetwork(); } + interface NeptuneServiceConfig { + @WithDefault("true") + boolean enabled(); + + /** Base port of the proxy port range. First cluster gets this port. */ + @WithDefault("8182") + int proxyBasePort(); + + /** Inclusive upper bound of the proxy port range. */ + @WithDefault("8282") + int proxyMaxPort(); + + @WithDefault("tinkerpop/gremlin-server:3.7.3") + String defaultImage(); + + Optional dockerNetwork(); + } + interface EventBridgeServiceConfig { @WithDefault("true") boolean enabled(); 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.java index 187ea46f8e..8be82ce7fd 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 @@ -1,5 +1,7 @@ package io.github.hectorvent.floci.core.common; +import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler; +import io.github.hectorvent.floci.services.neptune.NeptuneService; import io.github.hectorvent.floci.services.autoscaling.AutoScalingQueryHandler; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; import io.github.hectorvent.floci.services.ec2.Ec2QueryHandler; @@ -162,6 +164,8 @@ public class AwsQueryController { private final CloudFormationQueryHandler cloudFormationQueryHandler; private final ElastiCacheQueryHandler elastiCacheQueryHandler; private final RdsQueryHandler rdsQueryHandler; + private final NeptuneQueryHandler neptuneQueryHandler; + private final NeptuneService neptuneService; private final SqsQueryHandler sqsQueryHandler; private final SnsQueryHandler snsQueryHandler; private final SesQueryHandler sesQueryHandler; @@ -179,6 +183,8 @@ public class AwsQueryController { public AwsQueryController(CloudFormationQueryHandler cloudFormationQueryHandler, ElastiCacheQueryHandler elastiCacheQueryHandler, RdsQueryHandler rdsQueryHandler, + NeptuneQueryHandler neptuneQueryHandler, + NeptuneService neptuneService, SqsQueryHandler sqsQueryHandler, SnsQueryHandler snsQueryHandler, SesQueryHandler sesQueryHandler, IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler, @@ -192,6 +198,8 @@ public class AwsQueryController { this.cloudFormationQueryHandler = cloudFormationQueryHandler; this.elastiCacheQueryHandler = elastiCacheQueryHandler; this.rdsQueryHandler = rdsQueryHandler; + this.neptuneQueryHandler = neptuneQueryHandler; + this.neptuneService = neptuneService; this.sqsQueryHandler = sqsQueryHandler; this.snsQueryHandler = snsQueryHandler; this.sesQueryHandler = sesQueryHandler; @@ -230,7 +238,21 @@ public class AwsQueryController { case "iam" -> iamQueryHandler.handle(action, formParams); case "sts" -> stsQueryHandler.handle(action, formParams); case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams); - case "rds" -> rdsQueryHandler.handle(action, formParams); + case "rds" -> { + // Neptune signs requests with "rds" credential scope (same wire protocol). + // Route to Neptune when Engine=neptune (create ops) or when the cluster/instance + // already exists in Neptune storage (describe/modify/delete ops). + String engine = formParams.getFirst("Engine"); + String clusterId = formParams.getFirst("DBClusterIdentifier"); + String instanceId = formParams.getFirst("DBInstanceIdentifier"); + if ("neptune".equalsIgnoreCase(engine) + || neptuneService.hasCluster(clusterId) + || neptuneService.hasInstance(instanceId)) { + yield neptuneQueryHandler.handle(action, formParams); + } + yield rdsQueryHandler.handle(action, formParams); + } + case "neptune" -> neptuneQueryHandler.handle(action, formParams); case "email" -> sesQueryHandler.handle(action, formParams, region); case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region); case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, 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 5be92a02d7..c246a23794 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 @@ -87,6 +87,11 @@ public class ResolvedServiceCatalog { 5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY), Set.of(), Set.of("rds"), Set.of(), Set.of()), + descriptor("neptune", "neptune", config.services().neptune().enabled(), true, + "neptune", storageMode(config.storage().services().neptune().mode(), config.storage().mode()), + 5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("neptune"), Set.of(), Set.of()), descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true, "eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java new file mode 100644 index 0000000000..4eed595fa5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java @@ -0,0 +1,260 @@ +package io.github.hectorvent.floci.services.neptune; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +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.neptune.model.NeptuneCluster; +import io.github.hectorvent.floci.services.neptune.model.NeptuneInstance; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.Collection; + +@ApplicationScoped +public class NeptuneQueryHandler { + + private static final Logger LOG = Logger.getLogger(NeptuneQueryHandler.class); + + private final NeptuneService service; + private final EmulatorConfig config; + + @Inject + public NeptuneQueryHandler(NeptuneService service, EmulatorConfig config) { + this.service = service; + this.config = config; + } + + public Response handle(String action, MultivaluedMap params) { + LOG.infov("Neptune action: {0}", action); + try { + return switch (action) { + case "CreateDBCluster" -> handleCreateDbCluster(params); + case "DescribeDBClusters" -> handleDescribeDbClusters(params); + case "DeleteDBCluster" -> handleDeleteDbCluster(params); + case "ModifyDBCluster" -> handleModifyDbCluster(params); + case "CreateDBInstance" -> handleCreateDbInstance(params); + case "DescribeDBInstances"-> handleDescribeDbInstances(params); + case "DeleteDBInstance" -> handleDeleteDbInstance(params); + case "ModifyDBInstance" -> handleModifyDbInstance(params); + default -> AwsQueryResponse.error("UnsupportedOperation", + "Operation " + action + " is not supported by Neptune.", AwsNamespaces.RDS, 400); + }; + } catch (AwsException e) { + return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus()); + } catch (Exception e) { + LOG.errorv(e, "Unexpected error in Neptune {0}", action); + return Response.serverError().entity("Unexpected error: " + e.getMessage()).build(); + } + } + + // ── Clusters ────────────────────────────────────────────────────────────── + + private Response handleCreateDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + String engineVersion = params.getFirst("EngineVersion"); + boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication")); + + NeptuneCluster cluster = service.createDbCluster(id, engineVersion, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, + clusterXml(cluster))).build(); + } + + private Response handleDescribeDbClusters(MultivaluedMap params) { + String filterId = params.getFirst("DBClusterIdentifier"); + if (filterId == null || filterId.isBlank()) { + filterId = extractFilterValue(params, "db-cluster-id"); + } + + // When a specific cluster ID is requested, AWS returns 404 if not found + if (filterId != null && !filterId.isBlank()) { + service.getDbCluster(filterId); // throws DBClusterNotFoundFault if absent + } + + Collection result = service.listDbClusters(filterId); + + XmlBuilder xml = new XmlBuilder().start("DBClusters"); + for (NeptuneCluster c : result) { + xml.start("DBCluster").raw(clusterInnerXml(c)).end("DBCluster"); + } + xml.end("DBClusters").start("Marker").end("Marker"); + return Response.ok(AwsQueryResponse.envelope("DescribeDBClusters", AwsNamespaces.RDS, xml.build())).build(); + } + + private Response handleDeleteDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + NeptuneCluster cluster = service.getDbCluster(id); + service.deleteDbCluster(id); + return Response.ok(AwsQueryResponse.envelope("DeleteDBCluster", AwsNamespaces.RDS, + clusterXml(cluster))).build(); + } + + private Response handleModifyDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + String engineVersion = params.getFirst("EngineVersion"); + String iamStr = params.getFirst("EnableIAMDatabaseAuthentication"); + Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null; + + NeptuneCluster cluster = service.modifyDbCluster(id, engineVersion, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, + clusterXml(cluster))).build(); + } + + // ── Instances ───────────────────────────────────────────────────────────── + + private Response handleCreateDbInstance(MultivaluedMap params) { + String id = params.getFirst("DBInstanceIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); + } + String dbClusterIdentifier = params.getFirst("DBClusterIdentifier"); + if (dbClusterIdentifier == null || dbClusterIdentifier.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required for Neptune instances.", AwsNamespaces.RDS, 400); + } + String dbInstanceClass = params.getFirst("DBInstanceClass"); + String engineVersion = params.getFirst("EngineVersion"); + boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication")); + + NeptuneInstance instance = service.createDbInstance(id, dbClusterIdentifier, + dbInstanceClass, engineVersion, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("CreateDBInstance", AwsNamespaces.RDS, + instanceXml(instance))).build(); + } + + private Response handleDescribeDbInstances(MultivaluedMap params) { + String filterId = params.getFirst("DBInstanceIdentifier"); + if (filterId == null || filterId.isBlank()) { + filterId = extractFilterValue(params, "db-instance-id"); + } + + if (filterId != null && !filterId.isBlank()) { + service.getDbInstance(filterId); // throws DBInstanceNotFound if absent + } + + Collection result = service.listDbInstances(filterId); + + XmlBuilder xml = new XmlBuilder().start("DBInstances"); + for (NeptuneInstance i : result) { + xml.start("DBInstance").raw(instanceInnerXml(i)).end("DBInstance"); + } + xml.end("DBInstances").start("Marker").end("Marker"); + return Response.ok(AwsQueryResponse.envelope("DescribeDBInstances", AwsNamespaces.RDS, xml.build())).build(); + } + + private Response handleDeleteDbInstance(MultivaluedMap params) { + String id = params.getFirst("DBInstanceIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); + } + NeptuneInstance instance = service.getDbInstance(id); + service.deleteDbInstance(id); + return Response.ok(AwsQueryResponse.envelope("DeleteDBInstance", AwsNamespaces.RDS, + instanceXml(instance))).build(); + } + + private Response handleModifyDbInstance(MultivaluedMap params) { + String id = params.getFirst("DBInstanceIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); + } + String dbInstanceClass = params.getFirst("DBInstanceClass"); + String iamStr = params.getFirst("EnableIAMDatabaseAuthentication"); + Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null; + + NeptuneInstance instance = service.modifyDbInstance(id, dbInstanceClass, iamEnabled); + return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, + instanceXml(instance))).build(); + } + + // ── XML builders ────────────────────────────────────────────────────────── + + private String clusterXml(NeptuneCluster c) { + return new XmlBuilder().start("DBCluster").raw(clusterInnerXml(c)).end("DBCluster").build(); + } + + private String clusterInnerXml(NeptuneCluster c) { + XmlBuilder xml = new XmlBuilder() + .elem("DBClusterIdentifier", c.getDbClusterIdentifier()) + .elem("Status", c.getStatus()) + .elem("Engine", "neptune") + .elem("EngineVersion", c.getEngineVersion()) + .elem("Endpoint", c.getEndpoint()) + .elem("ReaderEndpoint", c.getReaderEndpoint()) + .elem("Port", c.getPort()) + .elem("IAMDatabaseAuthenticationEnabled", c.isIamDatabaseAuthenticationEnabled()) + .elem("MultiAZ", false) + .elem("StorageEncrypted", true) + .elem("AvailabilityZone", config.defaultAvailabilityZone()) + .elem("DbClusterResourceId", c.getDbClusterResourceId()) + .elem("DBClusterArn", c.getDbClusterArn()) + .start("DBClusterMembers"); + if (c.getDbClusterMembers() != null) { + for (String memberId : c.getDbClusterMembers()) { + xml.start("member") + .elem("DBInstanceIdentifier", memberId) + .elem("IsClusterWriter", true) + .end("member"); + } + } + xml.end("DBClusterMembers"); + return xml.build(); + } + + private String instanceXml(NeptuneInstance i) { + return new XmlBuilder().start("DBInstance").raw(instanceInnerXml(i)).end("DBInstance").build(); + } + + private String instanceInnerXml(NeptuneInstance i) { + return new XmlBuilder() + .elem("DBInstanceIdentifier", i.getDbInstanceIdentifier()) + .elem("DBClusterIdentifier", i.getDbClusterIdentifier()) + .elem("DBInstanceClass", i.getDbInstanceClass()) + .elem("DBInstanceStatus", i.getStatus()) + .elem("Engine", "neptune") + .elem("EngineVersion", i.getEngineVersion()) + .start("Endpoint") + .elem("Address", i.getEndpoint()) + .elem("Port", i.getPort()) + .end("Endpoint") + .elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled()) + .elem("MultiAZ", false) + .elem("StorageEncrypted", true) + .elem("AvailabilityZone", config.defaultAvailabilityZone()) + .elem("DbiResourceId", i.getDbiResourceId()) + .elem("DBInstanceArn", i.getDbInstanceArn()) + .build(); + } + + private static String extractFilterValue(MultivaluedMap params, String filterName) { + for (int i = 1; ; i++) { + String name = params.getFirst("Filters.Filter." + i + ".Name"); + if (name == null) { + break; + } + if (filterName.equals(name)) { + return params.getFirst("Filters.Filter." + i + ".Values.Value.1"); + } + } + return null; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java new file mode 100644 index 0000000000..7fb2565b3f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java @@ -0,0 +1,263 @@ +package io.github.hectorvent.floci.services.neptune; + +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.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerHandle; +import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager; +import io.github.hectorvent.floci.services.neptune.model.NeptuneCluster; +import io.github.hectorvent.floci.services.neptune.model.NeptuneInstance; +import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager; +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.Collection; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +@ApplicationScoped +public class NeptuneService { + + private static final Logger LOG = Logger.getLogger(NeptuneService.class); + private static final String ENGINE_VERSION_DEFAULT = "1.3.2.1"; + + private final StorageBackend clusters; + private final StorageBackend instances; + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final NeptuneContainerManager containerManager; + private final NeptuneProxyManager proxyManager; + private final Set usedPorts = ConcurrentHashMap.newKeySet(); + + @Inject + public NeptuneService(EmulatorConfig config, + RegionResolver regionResolver, + NeptuneContainerManager containerManager, + NeptuneProxyManager proxyManager, + StorageFactory storageFactory) { + this.config = config; + this.regionResolver = regionResolver; + this.containerManager = containerManager; + this.proxyManager = proxyManager; + this.clusters = storageFactory.create("neptune", "neptune-clusters.json", + new TypeReference>() {}); + this.instances = storageFactory.create("neptune", "neptune-instances.json", + new TypeReference>() {}); + } + + // ── Clusters ────────────────────────────────────────────────────────────── + + public NeptuneCluster createDbCluster(String id, String engineVersion, boolean iamEnabled) { + if (clusters.get(id).isPresent()) { + throw new AwsException("DBClusterAlreadyExistsFault", + "Neptune cluster " + id + " already exists.", 400); + } + + int proxyPort = allocateProxyPort(); + String image = config.services().neptune().defaultImage(); + + LOG.infov("Creating Neptune cluster {0} on proxy port {1}, image={2}", id, proxyPort, image); + + NeptuneContainerHandle handle = containerManager.start(id, image); + + String region = regionResolver.getDefaultRegion(); + String endpointHost = resolveEndpointHost(); + + NeptuneCluster cluster = new NeptuneCluster(); + cluster.setDbClusterIdentifier(id); + cluster.setStatus("available"); + cluster.setEngineVersion(engineVersion != null ? engineVersion : ENGINE_VERSION_DEFAULT); + cluster.setEndpoint(endpointHost); + cluster.setReaderEndpoint(endpointHost); + cluster.setPort(proxyPort); + cluster.setIamDatabaseAuthenticationEnabled(iamEnabled); + cluster.setDbClusterArn(regionResolver.buildArn("neptune", region, "cluster:" + id)); + cluster.setDbClusterResourceId("cluster-" + UUID.randomUUID().toString() + .replace("-", "").substring(0, 24).toUpperCase()); + cluster.setCreatedAt(Instant.now()); + cluster.setDbClusterMembers(new ArrayList<>()); + cluster.setContainerId(handle.getContainerId()); + cluster.setContainerHost(handle.getHost()); + cluster.setContainerPort(handle.getPort()); + cluster.setProxyPort(proxyPort); + + proxyManager.startProxy(id, proxyPort, handle.getHost(), handle.getPort()); + + clusters.put(id, cluster); + LOG.infov("Neptune cluster {0} created, Gremlin endpoint={1}:{2}", id, endpointHost, proxyPort); + return cluster; + } + + public NeptuneCluster getDbCluster(String id) { + return clusters.get(id).orElseThrow(() -> + new AwsException("DBClusterNotFoundFault", + "Neptune cluster " + id + " not found.", 404)); + } + + public boolean hasCluster(String id) { + if (id == null || id.isBlank()) { + return false; + } + return clusters.get(id).isPresent(); + } + + public boolean hasInstance(String id) { + if (id == null || id.isBlank()) { + return false; + } + return instances.get(id).isPresent(); + } + + public Collection listDbClusters(String filterId) { + if (filterId != null && !filterId.isBlank()) { + return clusters.scan(k -> k.equalsIgnoreCase(filterId)); + } + return clusters.scan(k -> true); + } + + public NeptuneCluster modifyDbCluster(String id, String engineVersion, Boolean iamEnabled) { + NeptuneCluster cluster = getDbCluster(id); + if (engineVersion != null && !engineVersion.isBlank()) { + cluster.setEngineVersion(engineVersion); + } + if (iamEnabled != null) { + cluster.setIamDatabaseAuthenticationEnabled(iamEnabled); + } + clusters.put(id, cluster); + LOG.infov("Neptune cluster {0} modified", id); + return cluster; + } + + public void deleteDbCluster(String id) { + NeptuneCluster cluster = clusters.get(id).orElseThrow(() -> + new AwsException("DBClusterNotFoundFault", + "Neptune cluster " + id + " not found.", 404)); + + if (cluster.getDbClusterMembers() != null && !cluster.getDbClusterMembers().isEmpty()) { + throw new AwsException("InvalidDBClusterStateFault", + "Cannot delete Neptune cluster " + id + " — it still has DB instances.", 400); + } + + cluster.setStatus("deleting"); + clusters.put(id, cluster); + + proxyManager.stopProxy(id); + + if (cluster.getContainerId() != null) { + containerManager.stop(new NeptuneContainerHandle( + cluster.getContainerId(), id, + cluster.getContainerHost(), cluster.getContainerPort())); + } + + releaseProxyPort(cluster.getProxyPort()); + clusters.delete(id); + LOG.infov("Neptune cluster {0} deleted", id); + } + + // ── Instances ───────────────────────────────────────────────────────────── + + public NeptuneInstance createDbInstance(String id, String dbClusterIdentifier, + String dbInstanceClass, String engineVersion, + boolean iamEnabled) { + if (instances.get(id).isPresent()) { + throw new AwsException("DBInstanceAlreadyExists", + "Neptune instance " + id + " already exists.", 400); + } + + NeptuneCluster cluster = getDbCluster(dbClusterIdentifier); + String region = regionResolver.getDefaultRegion(); + + NeptuneInstance instance = new NeptuneInstance(); + instance.setDbInstanceIdentifier(id); + instance.setDbClusterIdentifier(dbClusterIdentifier); + instance.setDbInstanceClass(dbInstanceClass != null ? dbInstanceClass : "db.r5.large"); + instance.setEngineVersion(engineVersion != null ? engineVersion : cluster.getEngineVersion()); + instance.setStatus("available"); + instance.setEndpoint(cluster.getEndpoint()); + instance.setPort(cluster.getPort()); + instance.setIamDatabaseAuthenticationEnabled(iamEnabled); + instance.setDbInstanceArn(regionResolver.buildArn("neptune", region, "db:" + id)); + instance.setDbiResourceId("db-" + UUID.randomUUID().toString() + .replace("-", "").substring(0, 24).toUpperCase()); + instance.setCreatedAt(Instant.now()); + + cluster.getDbClusterMembers().add(id); + clusters.put(dbClusterIdentifier, cluster); + + instances.put(id, instance); + LOG.infov("Neptune instance {0} created in cluster {1}", id, dbClusterIdentifier); + return instance; + } + + public NeptuneInstance getDbInstance(String id) { + return instances.get(id).orElseThrow(() -> + new AwsException("DBInstanceNotFound", + "Neptune instance " + id + " not found.", 404)); + } + + public Collection listDbInstances(String filterId) { + if (filterId != null && !filterId.isBlank()) { + return instances.scan(k -> k.equalsIgnoreCase(filterId)); + } + return instances.scan(k -> true); + } + + public NeptuneInstance modifyDbInstance(String id, String dbInstanceClass, Boolean iamEnabled) { + NeptuneInstance instance = getDbInstance(id); + if (dbInstanceClass != null && !dbInstanceClass.isBlank()) { + instance.setDbInstanceClass(dbInstanceClass); + } + if (iamEnabled != null) { + instance.setIamDatabaseAuthenticationEnabled(iamEnabled); + } + instances.put(id, instance); + LOG.infov("Neptune instance {0} modified", id); + return instance; + } + + public void deleteDbInstance(String id) { + NeptuneInstance instance = instances.get(id).orElseThrow(() -> + new AwsException("DBInstanceNotFound", + "Neptune instance " + id + " not found.", 404)); + + String clusterId = instance.getDbClusterIdentifier(); + NeptuneCluster cluster = clusters.get(clusterId).orElse(null); + if (cluster != null) { + cluster.getDbClusterMembers().remove(id); + clusters.put(clusterId, cluster); + } + + instances.delete(id); + LOG.infov("Neptune instance {0} deleted", id); + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + private String resolveEndpointHost() { + return config.hostname().orElse("localhost"); + } + + private int allocateProxyPort() { + int base = config.services().neptune().proxyBasePort(); + int max = config.services().neptune().proxyMaxPort(); + for (int port = base; port <= max; port++) { + if (usedPorts.add(port)) { + return port; + } + } + throw new AwsException("InsufficientNeptuneCapacity", + "No available proxy ports in range " + base + "-" + max, 503); + } + + private void releaseProxyPort(int port) { + usedPorts.remove(port); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerHandle.java new file mode 100644 index 0000000000..138d23fe9e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerHandle.java @@ -0,0 +1,29 @@ +package io.github.hectorvent.floci.services.neptune.container; + +import java.io.Closeable; + +/** + * Wraps a running backend Docker container for a Neptune DB cluster. + */ +public class NeptuneContainerHandle { + + private final String containerId; + private final String clusterId; + private final String host; + private final int port; + private Closeable logStream; + + public NeptuneContainerHandle(String containerId, String clusterId, String host, int port) { + this.containerId = containerId; + this.clusterId = clusterId; + this.host = host; + this.port = port; + } + + public String getContainerId() { return containerId; } + public String getClusterId() { return clusterId; } + public String getHost() { return host; } + public int getPort() { return port; } + public Closeable getLogStream() { return logStream; } + public void setLogStream(Closeable logStream) { this.logStream = logStream; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.java new file mode 100644 index 0000000000..7bf8a21df5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.java @@ -0,0 +1,168 @@ +package io.github.hectorvent.floci.services.neptune.container; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.Closeable; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Manages backend Docker container lifecycle for Neptune DB clusters. + * Spins up a TinkerPop Gremlin Server container per cluster. + */ +@ApplicationScoped +public class NeptuneContainerManager { + + private static final Logger LOG = Logger.getLogger(NeptuneContainerManager.class); + private static final int GREMLIN_PORT = 8182; + private static final int BACKEND_READY_DEADLINE_MS = 60_000; + private static final int BACKEND_READY_RETRY_MS = 200; + private static final int BACKEND_PROBE_CONNECT_MS = 2_000; + + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final ContainerLogStreamer logStreamer; + private final ContainerDetector containerDetector; + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final Map activeContainers = new ConcurrentHashMap<>(); + + @Inject + public NeptuneContainerManager(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerLogStreamer logStreamer, + ContainerDetector containerDetector, + EmulatorConfig config, + RegionResolver regionResolver) { + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.logStreamer = logStreamer; + this.containerDetector = containerDetector; + this.config = config; + this.regionResolver = regionResolver; + } + + public NeptuneContainerHandle start(String clusterId, String image) { + LOG.infov("Starting Neptune Gremlin Server container for cluster: {0}", clusterId); + + String containerName = "floci-neptune-" + clusterId; + lifecycleManager.removeIfExists(containerName); + + ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image) + .withName(containerName) + .withDockerNetwork(config.services().neptune().dockerNetwork()) + .withLogRotation(); + + if (!containerDetector.isRunningInContainer()) { + specBuilder.withDynamicPort(GREMLIN_PORT); + } else { + specBuilder.withExposedPort(GREMLIN_PORT); + } + + ContainerSpec spec = specBuilder.build(); + ContainerInfo info = lifecycleManager.createAndStart(spec); + EndpointInfo endpoint = info.getEndpoint(GREMLIN_PORT); + + LOG.infov("Neptune Gremlin Server for cluster {0}: {1}", clusterId, endpoint); + + NeptuneContainerHandle handle = new NeptuneContainerHandle( + info.containerId(), clusterId, endpoint.host(), endpoint.port()); + activeContainers.put(clusterId, handle); + + String shortId = info.containerId().length() >= 8 + ? info.containerId().substring(0, 8) + : info.containerId(); + String logGroup = "/aws/neptune/cluster/" + clusterId + "/gremlin-log"; + String logStream = logStreamer.generateLogStreamName(shortId); + String region = regionResolver.getDefaultRegion(); + + Closeable logHandle = logStreamer.attach( + info.containerId(), logGroup, logStream, region, "neptune:" + clusterId); + handle.setLogStream(logHandle); + + waitForBackendReady(clusterId, endpoint.host(), endpoint.port()); + + return handle; + } + + public void stop(NeptuneContainerHandle handle) { + if (handle == null) { + return; + } + activeContainers.remove(handle.getClusterId()); + lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream()); + } + + public void stopAll() { + List handles = new ArrayList<>(activeContainers.values()); + if (!handles.isEmpty()) { + LOG.infov("Stopping {0} Neptune container(s) on shutdown", handles.size()); + } + for (NeptuneContainerHandle handle : handles) { + stop(handle); + } + } + + /** + * Probes the Gremlin Server HTTP endpoint. Gremlin Server responds to a plain HTTP GET + * on /gremlin with HTTP 400 (not a WebSocket upgrade), confirming the server is listening. + */ + private static void waitForBackendReady(String clusterId, String host, int port) { + byte[] probe = "GET /gremlin HTTP/1.1\r\nHost: floci\r\n\r\n" + .getBytes(StandardCharsets.UTF_8); + long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS; + int attempt = 0; + while (System.currentTimeMillis() < deadline) { + attempt++; + try (Socket s = new Socket()) { + s.connect(new InetSocketAddress(host, port), BACKEND_PROBE_CONNECT_MS); + s.setSoTimeout(BACKEND_PROBE_CONNECT_MS); + OutputStream out = s.getOutputStream(); + out.write(probe); + out.flush(); + byte[] buf = new byte[32]; + int n = s.getInputStream().read(buf); + if (n > 0) { + if (attempt > 1) { + LOG.infov("Gremlin backend ready for cluster {0} after {1} probe attempt(s)", + clusterId, attempt); + } + return; + } + } catch (IOException e) { + if (LOG.isDebugEnabled()) { + LOG.debugv("Gremlin probe for cluster {0} attempt {1}: {2}", + clusterId, attempt, e.getMessage()); + } + } + try { + Thread.sleep(BACKEND_READY_RETRY_MS); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException( + "Interrupted while waiting for Gremlin backend " + clusterId, ie); + } + } + throw new RuntimeException( + "Gremlin backend for cluster " + clusterId + " did not become ready on " + + host + ":" + port + " within " + BACKEND_READY_DEADLINE_MS + "ms"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java new file mode 100644 index 0000000000..3ac251ef65 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java @@ -0,0 +1,80 @@ +package io.github.hectorvent.floci.services.neptune.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +@RegisterForReflection +public class NeptuneCluster { + + private String dbClusterIdentifier; + private String status; + private String engineVersion; + private String endpoint; + private int port; + private String readerEndpoint; + private boolean iamDatabaseAuthenticationEnabled; + private String dbClusterArn; + private String dbClusterResourceId; + private List dbClusterMembers = new ArrayList<>(); + private Instant createdAt; + + // Docker / proxy runtime fields — persisted so cleanup works across restarts + private String containerId; + private String containerHost; + private int containerPort; + private int proxyPort; + + public NeptuneCluster() {} + + public String getDbClusterIdentifier() { return dbClusterIdentifier; } + public void setDbClusterIdentifier(String dbClusterIdentifier) { this.dbClusterIdentifier = dbClusterIdentifier; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getEngineVersion() { return engineVersion; } + public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } + + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + public int getPort() { return port; } + public void setPort(int port) { this.port = port; } + + public String getReaderEndpoint() { return readerEndpoint; } + public void setReaderEndpoint(String readerEndpoint) { this.readerEndpoint = readerEndpoint; } + + public boolean isIamDatabaseAuthenticationEnabled() { return iamDatabaseAuthenticationEnabled; } + public void setIamDatabaseAuthenticationEnabled(boolean iamDatabaseAuthenticationEnabled) { + this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled; + } + + public String getDbClusterArn() { return dbClusterArn; } + public void setDbClusterArn(String dbClusterArn) { this.dbClusterArn = dbClusterArn; } + + public String getDbClusterResourceId() { return dbClusterResourceId; } + public void setDbClusterResourceId(String dbClusterResourceId) { this.dbClusterResourceId = dbClusterResourceId; } + + public List getDbClusterMembers() { return dbClusterMembers; } + public void setDbClusterMembers(List dbClusterMembers) { + this.dbClusterMembers = dbClusterMembers != null ? new ArrayList<>(dbClusterMembers) : new ArrayList<>(); + } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public String getContainerId() { return containerId; } + public void setContainerId(String containerId) { this.containerId = containerId; } + + public String getContainerHost() { return containerHost; } + public void setContainerHost(String containerHost) { this.containerHost = containerHost; } + + public int getContainerPort() { return containerPort; } + public void setContainerPort(int containerPort) { this.containerPort = containerPort; } + + public int getProxyPort() { return proxyPort; } + public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java new file mode 100644 index 0000000000..3fe1c9e0f3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java @@ -0,0 +1,58 @@ +package io.github.hectorvent.floci.services.neptune.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +@RegisterForReflection +public class NeptuneInstance { + + private String dbInstanceIdentifier; + private String dbClusterIdentifier; + private String dbInstanceClass; + private String engineVersion; + private String status; + private String endpoint; + private int port; + private boolean iamDatabaseAuthenticationEnabled; + private String dbInstanceArn; + private String dbiResourceId; + private Instant createdAt; + + public NeptuneInstance() {} + + public String getDbInstanceIdentifier() { return dbInstanceIdentifier; } + public void setDbInstanceIdentifier(String dbInstanceIdentifier) { this.dbInstanceIdentifier = dbInstanceIdentifier; } + + public String getDbClusterIdentifier() { return dbClusterIdentifier; } + public void setDbClusterIdentifier(String dbClusterIdentifier) { this.dbClusterIdentifier = dbClusterIdentifier; } + + public String getDbInstanceClass() { return dbInstanceClass; } + public void setDbInstanceClass(String dbInstanceClass) { this.dbInstanceClass = dbInstanceClass; } + + public String getEngineVersion() { return engineVersion; } + public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + public int getPort() { return port; } + public void setPort(int port) { this.port = port; } + + public boolean isIamDatabaseAuthenticationEnabled() { return iamDatabaseAuthenticationEnabled; } + public void setIamDatabaseAuthenticationEnabled(boolean iamDatabaseAuthenticationEnabled) { + this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled; + } + + public String getDbInstanceArn() { return dbInstanceArn; } + public void setDbInstanceArn(String dbInstanceArn) { this.dbInstanceArn = dbInstanceArn; } + + public String getDbiResourceId() { return dbiResourceId; } + public void setDbiResourceId(String dbiResourceId) { this.dbiResourceId = dbiResourceId; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java b/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java new file mode 100644 index 0000000000..ac4fa7f31d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java @@ -0,0 +1,120 @@ +package io.github.hectorvent.floci.services.neptune.proxy; + +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; + +/** + * Transparent TCP proxy for a single Neptune DB cluster's Gremlin endpoint. + * + *

Neptune uses WebSocket over port 8182. The client (botocore) embeds SigV4 credentials + * in the HTTP Upgrade headers. The backend TinkerPop Gremlin Server accepts plain WebSocket + * without authentication, so we relay all bytes transparently without inspecting the payload. + * + *

Uses Java virtual threads for non-blocking I/O. + */ +public class NeptuneGremlinProxy { + + private static final Logger LOG = Logger.getLogger(NeptuneGremlinProxy.class); + + private final String clusterId; + private final String backendHost; + private final int backendPort; + + private volatile boolean running; + private ServerSocket serverSocket; + + public NeptuneGremlinProxy(String clusterId, String backendHost, int backendPort) { + this.clusterId = clusterId; + this.backendHost = backendHost; + this.backendPort = backendPort; + } + + public void start(int proxyPort) throws IOException { + serverSocket = new ServerSocket(proxyPort); + running = true; + Thread.ofVirtual().name("neptune-proxy-accept-" + clusterId).start(this::acceptLoop); + LOG.infov("Neptune Gremlin proxy started for cluster {0} on port {1} → {2}:{3}", + clusterId, proxyPort, backendHost, backendPort); + } + + public void stop() { + running = false; + try { + if (serverSocket != null) { + serverSocket.close(); + } + } catch (IOException e) { + LOG.warnv("Error closing proxy server socket for cluster {0}: {1}", clusterId, e.getMessage()); + } + } + + private void acceptLoop() { + while (running) { + try { + Socket client = serverSocket.accept(); + Thread.ofVirtual().name("neptune-proxy-conn-" + clusterId).start(() -> relay(client)); + } catch (IOException e) { + if (running) { + LOG.warnv("Accept error for cluster {0}: {1}", clusterId, e.getMessage()); + } + } + } + } + + private void relay(Socket client) { + try { + client.setTcpNoDelay(true); + Socket backend = new Socket(backendHost, backendPort); + backend.setTcpNoDelay(true); + bridge(client, backend); + } catch (IOException e) { + LOG.debugv("Failed to connect to Gremlin backend for cluster {0}: {1}", + clusterId, e.getMessage()); + closeQuietly(client); + } + } + + /** + * Bidirectional byte relay. Relay threads are platform daemon threads; virtual threads + * for I/O-bound work can stall WebSocket frame delivery under high concurrency. + */ + private void bridge(Socket client, Socket backend) { + Thread t1 = Thread.ofPlatform().daemon(true).name("neptune-relay-c2b-" + clusterId) + .start(() -> pipe(client, backend)); + Thread t2 = Thread.ofPlatform().daemon(true).name("neptune-relay-b2c-" + clusterId) + .start(() -> pipe(backend, client)); + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + closeQuietly(client); + closeQuietly(backend); + } + } + + private static void pipe(Socket from, Socket to) { + byte[] buf = new byte[8192]; + try { + InputStream in = from.getInputStream(); + OutputStream out = to.getOutputStream(); + int n; + while ((n = in.read(buf)) != -1) { + out.write(buf, 0, n); + out.flush(); + } + } catch (IOException ignored) { + // Normal when either side closes the connection + } + } + + private static void closeQuietly(Socket s) { + try { s.close(); } catch (IOException ignored) {} + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneProxyManager.java new file mode 100644 index 0000000000..ee4dbf33bf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneProxyManager.java @@ -0,0 +1,43 @@ +package io.github.hectorvent.floci.services.neptune.proxy; + +import jakarta.enterprise.context.ApplicationScoped; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Registry of all active Neptune Gremlin proxies. One proxy per DB cluster. + */ +@ApplicationScoped +public class NeptuneProxyManager { + + private static final Logger LOG = Logger.getLogger(NeptuneProxyManager.class); + + private final ConcurrentHashMap proxies = new ConcurrentHashMap<>(); + + public void startProxy(String clusterId, int proxyPort, String backendHost, int backendPort) { + NeptuneGremlinProxy proxy = new NeptuneGremlinProxy(clusterId, backendHost, backendPort); + try { + proxy.start(proxyPort); + proxies.put(clusterId, proxy); + } catch (IOException e) { + throw new RuntimeException("Failed to start Gremlin proxy for cluster " + clusterId + + " on port " + proxyPort, e); + } + } + + public void stopProxy(String clusterId) { + NeptuneGremlinProxy proxy = proxies.remove(clusterId); + if (proxy != null) { + proxy.stop(); + LOG.infov("Stopped Gremlin proxy for cluster {0}", clusterId); + } + } + + public void stopAll() { + proxies.values().forEach(NeptuneGremlinProxy::stop); + proxies.clear(); + LOG.info("Stopped all Neptune Gremlin proxies"); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 140cd9602e..1b75649869 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -162,6 +162,11 @@ floci: default-postgres-image: "postgres:16-alpine" default-mysql-image: "mysql:8.0" default-mariadb-image: "mariadb:11" + neptune: + enabled: true + proxy-base-port: 8182 + proxy-max-port: 8282 + default-image: "tinkerpop/gremlin-server:3.7.3" eventbridge: enabled: true scheduler: diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneIntegrationTest.java new file mode 100644 index 0000000000..b9098c756a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneIntegrationTest.java @@ -0,0 +1,266 @@ +package io.github.hectorvent.floci.services.neptune; + +import io.quarkus.test.junit.QuarkusTest; +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.containsString; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class NeptuneIntegrationTest { + + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String CLUSTER_ID = "my-neptune-cluster"; + private static final String INSTANCE_ID = "my-neptune-instance"; + + // Fake SigV4 header — service name "neptune" is what AwsQueryController extracts + // to route to NeptuneQueryHandler instead of RdsQueryHandler. + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260516/us-east-1/neptune/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + + @Test + @Order(1) + void createCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("Engine", "neptune") + .formParam("EngineVersion", "1.3.2.1") + .formParam("EnableIAMDatabaseAuthentication", "true") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)) + .body(containsString("available")) + .body(containsString("neptune")) + .body(containsString("8182")) + .body(containsString("true")); + } + + @Test + @Order(2) + void createClusterDuplicateFails() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("Engine", "neptune") + .when().post("/") + .then() + .statusCode(400) + .body(containsString("DBClusterAlreadyExistsFault")); + } + + @Test + @Order(3) + void describeClusters() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)); + } + + @Test + @Order(4) + void describeClusterById() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)); + } + + @Test + @Order(5) + void describeClusterNotFound() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", "nonexistent-cluster") + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(6) + void modifyCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "ModifyDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("EngineVersion", "1.3.3.0") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)) + .body(containsString("1.3.3.0")); + } + + @Test + @Order(7) + void createInstance() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBInstance") + .formParam("DBInstanceIdentifier", INSTANCE_ID) + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "neptune") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)) + .body(containsString(CLUSTER_ID)) + .body(containsString("available")) + .body(containsString("db.r5.large")) + .body(containsString("8182")); + } + + @Test + @Order(8) + void clusterHasInstanceMember() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)); + } + + @Test + @Order(9) + void describeInstances() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBInstances") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)); + } + + @Test + @Order(10) + void createInstanceRequiresCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBInstance") + .formParam("DBInstanceIdentifier", "orphan-instance") + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "neptune") + .when().post("/") + .then() + .statusCode(400) + .body(containsString("DBClusterIdentifier is required")); + } + + @Test + @Order(11) + void deleteClusterWithInstanceFails() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(400) + .body(containsString("InvalidDBClusterStateFault")); + } + + @Test + @Order(12) + void deleteInstance() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBInstance") + .formParam("DBInstanceIdentifier", INSTANCE_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(INSTANCE_ID)); + } + + @Test + @Order(13) + void clusterHasNoMembersAfterInstanceDelete() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(not(containsString(INSTANCE_ID))); + } + + @Test + @Order(14) + void deleteCluster() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString(CLUSTER_ID)); + } + + @Test + @Order(15) + void describeAfterDeleteReturnsEmpty() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(16) + void unsupportedAction() { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "RestoreDBClusterFromSnapshot") + .when().post("/") + .then() + .statusCode(400) + .body(containsString("UnsupportedOperation")); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index a3a0b7dbd9..b4d36da54c 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -95,6 +95,11 @@ floci: default-postgres-image: "postgres:16-alpine" default-mysql-image: "mysql:8.0" default-mariadb-image: "mariadb:11" + neptune: + enabled: true + proxy-base-port: 8182 + proxy-max-port: 8282 + default-image: "tinkerpop/gremlin-server:3.7.3" eventbridge: enabled: true scheduler: