From 760d48b91aabde5984bfebfb6aa2ed0b0f0193a9 Mon Sep 17 00:00:00 2001 From: Stuart Lang Date: Sat, 20 Jun 2026 17:24:00 +0100 Subject: [PATCH] feat(neptune): support neo4j backend for openCypher via NEPTUNE_DB_TYPE (#1449) * feat(neptune): support neo4j backend for openCypher via NEPTUNE_DB_TYPE Neptune emulation always started a TinkerPop Gremlin Server, which only speaks Gremlin. Add a global db-type selector (FLOCI_SERVICES_NEPTUNE_DB_TYPE, mirroring LocalStack's NEPTUNE_DB_TYPE) so clusters can be backed by Neo4j and served over the Bolt protocol for openCypher. - Add NeptuneDbType enum (gremlin -> 8182, neo4j -> 7687) with alias parsing - Add db-type and default-neo4j-image config (default neo4j:5-community) - Resolve image/port per engine in NeptuneService and NeptuneContainerManager - Run Neo4j with NEO4J_AUTH=none and probe readiness via the Bolt handshake - Add openCypher/Bolt integration test and NeptuneDbType unit test - Document the new option in README and docs/services/neptune.md * test(neptune): assert DeleteDBCluster cleanup and clarify docs Assert the openCypher integration test's DeleteDBCluster cleanup returns 200 so a failed delete surfaces instead of silently leaking a backend container and proxy port into later tests. Also drop the misleading backend ports from the db-type table (users connect via the proxy port range, not the container-native port) and correct the SigV4 auth-header comment to reference the management request routing. * fix(neptune): treat all-zero Bolt handshake reply as not-ready The Neo4j readiness probe accepted any non-empty response, but Neo4j answers the Bolt handshake with 0x00000000 when it rejects every proposed version (Bolt disabled, wrong port, or an unsupported server version). That made the probe report ready for a backend whose sessions would then fail. Require a non-zero agreed version for the neo4j db-type so such a backend times out with a clear error instead. * fix(neptune): fall back to default db-type on unknown config value A server-side typo in FLOCI_SERVICES_NEPTUNE_DB_TYPE shouldn't fail the client's CreateDBCluster. Make NeptuneDbType.fromConfig return an Optional and have NeptuneService fall back to GREMLIN with a WARN for an unrecognised value, instead of throwing InvalidParameterValue. The cluster still comes up on the default engine. --- README.md | 4 +- docs/services/neptune.md | 42 +++++++- pom.xml | 7 ++ .../floci/config/EmulatorConfig.java | 13 +++ .../services/neptune/NeptuneService.java | 20 +++- .../container/NeptuneContainerManager.java | 97 ++++++++++++++----- .../services/neptune/model/NeptuneDbType.java | 52 ++++++++++ src/main/resources/application.yml | 2 + .../NeptuneOpenCypherIntegrationTest.java | 95 ++++++++++++++++++ .../neptune/model/NeptuneDbTypeTest.java | 43 ++++++++ 10 files changed, 343 insertions(+), 32 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbType.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneOpenCypherIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbTypeTest.java diff --git a/README.md b/README.md index 318c80330a..14e957ce7c 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | ElastiCache | Real Docker | Redis / Valkey protocol, IAM auth, SigV4 validation | | RDS | Real Docker | PostgreSQL, MySQL, MariaDB, IAM auth, JDBC-compatible engines | | RDS Data API | REST JSON over real RDS containers | Raw SQL execution and transactions for local MySQL / MariaDB RDS resources | -| Neptune | Real Docker | Graph DB via TinkerPop Gremlin Server; RDS-shaped control plane; Gremlin WebSocket on port 8182 with SigV4 proxy | +| Neptune | Real Docker | Graph DB via TinkerPop Gremlin Server (default) or Neo4j for openCypher/Bolt (`NEPTUNE_DB_TYPE`); RDS-shaped control plane; SigV4 proxy on port 8182 | | DocumentDB | Real Docker, mock mode available | MongoDB-compatible cluster via real MongoDB containers; RDS-shaped control plane; MongoDB wire protocol on port 27017 | | MSK | Real Docker | Kafka-compatible broker via Redpanda | | Athena | In-process with DuckDB sidecar | Real SQL execution over S3 and Glue-backed views | @@ -315,6 +315,7 @@ Floci uses real Docker containers when in-process emulation would reduce fidelit | RDS MySQL / Aurora | `mysql:8.0` | MySQL engine, IAM auth, JDBC-compatible access | | RDS MariaDB | `mariadb:11` | MariaDB engine, IAM auth, JDBC-compatible access | | Neptune | `tinkerpop/gremlin-server:3.7.3` | TinkerPop Gremlin Server; Gremlin WebSocket on port 8182; SigV4 auth proxy | +| Neptune (openCypher) | `neo4j:5-community` | Neo4j backend when `FLOCI_SERVICES_NEPTUNE_DB_TYPE=neo4j`; openCypher over Bolt | | DocumentDB | `mongo:7.0` | MongoDB engine; MongoDB wire protocol on port 27017 | | MSK | `redpandadata/redpanda:latest` | Kafka-compatible broker via Redpanda | | EC2 | AMI-mapped Linux images | Linux containers, SSH key injection, UserData, IMDS, IAM credentials | @@ -345,6 +346,7 @@ docker run -d --name floci \ | `FLOCI_SERVICES_MSK_DEFAULT_IMAGE` | `redpandadata/redpanda:latest` | | `FLOCI_SERVICES_OPENSEARCH_DEFAULT_IMAGE` | `opensearchproject/opensearch:2` | | `FLOCI_SERVICES_NEPTUNE_DEFAULT_IMAGE` | `tinkerpop/gremlin-server:3.7.3` | +| `FLOCI_SERVICES_NEPTUNE_DEFAULT_NEO4J_IMAGE` | `neo4j:5-community` | | `FLOCI_SERVICES_DOCDB_DEFAULT_IMAGE` | `mongo:7.0` | | `FLOCI_SERVICES_EKS_DEFAULT_IMAGE` | `rancher/k3s:latest` | | `FLOCI_SERVICES_ECR_REGISTRY_IMAGE` | `registry:2` | diff --git a/docs/services/neptune.md b/docs/services/neptune.md index f61cc863e5..342487d05c 100644 --- a/docs/services/neptune.md +++ b/docs/services/neptune.md @@ -1,10 +1,21 @@ # Neptune -**Protocol:** Query (XML) for management API + Gremlin / HTTP for data plane +**Protocol:** Query (XML) for management API + Gremlin / HTTP / Bolt for data plane **Management Endpoint:** `POST http://localhost:4566/` -**Data Endpoint:** `localhost:` (TCP / WebSocket) +**Data Endpoint:** `localhost:` (TCP / WebSocket / Bolt) -Floci manages real [Apache TinkerPop Gremlin Server](https://tinkerpop.apache.org/) Docker containers and proxies connections to them, providing an API-compatible Neptune emulation for local development and testing. +Floci manages real graph-database Docker containers and proxies connections to them, providing an API-compatible Neptune emulation for local development and testing. + +## Backend engine (`db-type`) + +Neptune supports multiple query languages. Floci backs each one with a different container and proxies the matching wire protocol, selected globally via `FLOCI_SERVICES_NEPTUNE_DB_TYPE` (mirroring LocalStack's `NEPTUNE_DB_TYPE`): + +| `db-type` | Backend image | Query language | Wire protocol | +|-----------|---------------|----------------|---------------| +| `gremlin` _(default)_ | [Apache TinkerPop Gremlin Server](https://tinkerpop.apache.org/) | Gremlin | WebSocket | +| `neo4j` | [Neo4j](https://neo4j.com/) | openCypher | Bolt | + +The proxy is a transparent byte relay, so the host-facing proxy port range is unchanged regardless of engine — only the protocol you connect with differs. Connect to a cluster's proxy port (from the `8182`–`8282` range, returned by `DescribeDBClusters`), not the backend's native port. The Neo4j backend runs with `NEO4J_AUTH=none`, matching Neptune's model of authenticating at the AWS edge (IAM) rather than at the graph protocol; connect your Bolt/openCypher driver with no auth. ## Supported Actions @@ -25,8 +36,10 @@ Floci manages real [Apache TinkerPop Gremlin Server](https://tinkerpop.apache.or |----------|---------|-------------| | `FLOCI_SERVICES_NEPTUNE_ENABLED` | `true` | Enable or disable Neptune | | `FLOCI_SERVICES_NEPTUNE_PROXY_BASE_PORT` | `8182` | First host port in the Gremlin proxy range | -| `FLOCI_SERVICES_NEPTUNE_PROXY_MAX_PORT` | `8282` | Last host port in the Gremlin proxy range | -| `FLOCI_SERVICES_NEPTUNE_DEFAULT_IMAGE` | `tinkerpop/gremlin-server:3.7.3` | Gremlin Server Docker image | +| `FLOCI_SERVICES_NEPTUNE_PROXY_MAX_PORT` | `8282` | Last host port in the proxy range | +| `FLOCI_SERVICES_NEPTUNE_DB_TYPE` | `gremlin` | Backend engine: `gremlin` (Gremlin/WebSocket) or `neo4j` (openCypher/Bolt) | +| `FLOCI_SERVICES_NEPTUNE_DEFAULT_IMAGE` | `tinkerpop/gremlin-server:3.7.3` | Image used when `db-type=gremlin` | +| `FLOCI_SERVICES_NEPTUNE_DEFAULT_NEO4J_IMAGE` | `neo4j:5-community` | Image used when `db-type=neo4j` | | `FLOCI_SERVICES_NEPTUNE_DOCKER_NETWORK` | _(host default)_ | Docker network for container connectivity | ### Docker Compose @@ -105,6 +118,25 @@ print(result) gremlin.close() ``` +### Graph data plane — openCypher (Python + neo4j driver) + +Start Floci with `FLOCI_SERVICES_NEPTUNE_DB_TYPE=neo4j`, then connect with any Bolt +driver and run openCypher: + +```python +from neo4j import GraphDatabase + +# Use the port returned by DescribeDBClusters; no auth (NEO4J_AUTH=none) +driver = GraphDatabase.driver("bolt://localhost:8182", auth=None) + +with driver.session() as session: + session.run("CREATE (:Person {name: 'Alice'})") + count = session.run("MATCH (p:Person) RETURN count(p) AS c").single()["c"] + print(count) + +driver.close() +``` + ### Management API (Python / boto3) ```python diff --git a/pom.xml b/pom.xml index 40da3a84a7..39efbb9b2b 100644 --- a/pom.xml +++ b/pom.xml @@ -239,6 +239,13 @@ 2.3.232 test + + + org.neo4j.driver + neo4j-java-driver + 5.28.5 + test + 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 468952a024..f356b9fae5 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -585,9 +585,22 @@ public interface EmulatorConfig { @WithDefault("8282") int proxyMaxPort(); + /** + * Backend graph engine and query language: {@code gremlin} (Apache TinkerPop, Gremlin + * over WebSocket) or {@code neo4j} (Neo4j, openCypher over Bolt). Mirrors LocalStack's + * {@code NEPTUNE_DB_TYPE}. + */ + @WithDefault("gremlin") + String dbType(); + + /** Image used when {@code db-type=gremlin}. */ @WithDefault("tinkerpop/gremlin-server:3.7.3") String defaultImage(); + /** Image used when {@code db-type=neo4j} (openCypher / Bolt). */ + @WithDefault("neo4j:5-community") + String defaultNeo4jImage(); + Optional dockerNetwork(); } 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 index 6b980ce8f7..fd64687bd6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java @@ -9,6 +9,7 @@ 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.NeptuneDbType; import io.github.hectorvent.floci.services.neptune.model.NeptuneInstance; import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager; import jakarta.enterprise.context.ApplicationScoped; @@ -62,11 +63,21 @@ public class NeptuneService { } int proxyPort = allocateProxyPort(); - String image = config.services().neptune().defaultImage(); + String configuredDbType = config.services().neptune().dbType(); + NeptuneDbType dbType = NeptuneDbType.fromConfig(configuredDbType).orElseGet(() -> { + LOG.warnv("Unsupported Neptune db-type ''{0}'', falling back to {1}. Supported: gremlin, neo4j.", + configuredDbType, NeptuneDbType.GREMLIN); + return NeptuneDbType.GREMLIN; + }); + String image = switch (dbType) { + case GREMLIN -> config.services().neptune().defaultImage(); + case NEO4J -> config.services().neptune().defaultNeo4jImage(); + }; - LOG.infov("Creating Neptune cluster {0} on proxy port {1}, image={2}", id, String.valueOf(proxyPort), image); + LOG.infov("Creating Neptune cluster {0} on proxy port {1}, dbType={2}, image={3}", + id, String.valueOf(proxyPort), dbType, image); - NeptuneContainerHandle handle = containerManager.start(id, image); + NeptuneContainerHandle handle = containerManager.start(id, image, dbType); String region = regionResolver.getDefaultRegion(); String endpointHost = resolveEndpointHost(); @@ -92,7 +103,8 @@ public class NeptuneService { proxyManager.startProxy(id, proxyPort, handle.getHost(), handle.getPort()); clusters.put(id, cluster); - LOG.infov("Neptune cluster {0} created, Gremlin endpoint={1}:{2}", id, endpointHost, String.valueOf(proxyPort)); + LOG.infov("Neptune cluster {0} created ({1}), endpoint={2}:{3}", + id, dbType, endpointHost, String.valueOf(proxyPort)); return cluster; } 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 index 7bf8a21df5..1d794f158a 100644 --- 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 @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.C 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 io.github.hectorvent.floci.services.neptune.model.NeptuneDbType; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -26,13 +27,13 @@ import java.util.concurrent.ConcurrentHashMap; /** * Manages backend Docker container lifecycle for Neptune DB clusters. - * Spins up a TinkerPop Gremlin Server container per cluster. + * Spins up one graph database container per cluster — a TinkerPop Gremlin Server + * ({@code db-type=gremlin}) or Neo4j ({@code db-type=neo4j}, openCypher over Bolt). */ @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; @@ -60,28 +61,30 @@ public class NeptuneContainerManager { this.regionResolver = regionResolver; } - public NeptuneContainerHandle start(String clusterId, String image) { - LOG.infov("Starting Neptune Gremlin Server container for cluster: {0}", clusterId); + public NeptuneContainerHandle start(String clusterId, String image, NeptuneDbType dbType) { + LOG.infov("Starting Neptune backend container ({0}) for cluster: {1}", dbType, clusterId); + int backendPort = dbType.backendPort(); String containerName = "floci-neptune-" + clusterId; lifecycleManager.removeIfExists(containerName); ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image) .withName(containerName) + .withEnv(backendEnv(dbType)) .withDockerNetwork(config.services().neptune().dockerNetwork()) .withLogRotation(); if (!containerDetector.isRunningInContainer()) { - specBuilder.withDynamicPort(GREMLIN_PORT); + specBuilder.withDynamicPort(backendPort); } else { - specBuilder.withExposedPort(GREMLIN_PORT); + specBuilder.withExposedPort(backendPort); } ContainerSpec spec = specBuilder.build(); ContainerInfo info = lifecycleManager.createAndStart(spec); - EndpointInfo endpoint = info.getEndpoint(GREMLIN_PORT); + EndpointInfo endpoint = info.getEndpoint(backendPort); - LOG.infov("Neptune Gremlin Server for cluster {0}: {1}", clusterId, endpoint); + LOG.infov("Neptune {0} backend for cluster {1}: {2}", dbType, clusterId, endpoint); NeptuneContainerHandle handle = new NeptuneContainerHandle( info.containerId(), clusterId, endpoint.host(), endpoint.port()); @@ -90,7 +93,7 @@ public class NeptuneContainerManager { String shortId = info.containerId().length() >= 8 ? info.containerId().substring(0, 8) : info.containerId(); - String logGroup = "/aws/neptune/cluster/" + clusterId + "/gremlin-log"; + String logGroup = "/aws/neptune/cluster/" + clusterId + "/" + dbType.name().toLowerCase() + "-log"; String logStream = logStreamer.generateLogStreamName(shortId); String region = regionResolver.getDefaultRegion(); @@ -98,11 +101,24 @@ public class NeptuneContainerManager { info.containerId(), logGroup, logStream, region, "neptune:" + clusterId); handle.setLogStream(logHandle); - waitForBackendReady(clusterId, endpoint.host(), endpoint.port()); + waitForBackendReady(clusterId, dbType, endpoint.host(), endpoint.port()); return handle; } + /** + * Environment for the backend container. Neo4j's Bolt endpoint requires auth to be + * explicitly disabled so the transparent proxy can relay openCypher sessions without + * brokering credentials — matching Neptune, which authenticates at the AWS edge (IAM), + * not at the graph protocol. + */ + private static List backendEnv(NeptuneDbType dbType) { + return switch (dbType) { + case GREMLIN -> List.of(); + case NEO4J -> List.of("NEO4J_AUTH=none"); + }; + } + public void stop(NeptuneContainerHandle handle) { if (handle == null) { return; @@ -122,12 +138,32 @@ public class NeptuneContainerManager { } /** - * 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. + * Bolt handshake magic preamble {@code 0x6060B017} followed by four 4-byte version + * proposals (highest first). Neo4j replies with the 4-byte agreed version once its Bolt + * connector is accepting connections, which is the readiness signal we probe for. */ - 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); + private static final byte[] BOLT_HANDSHAKE = { + 0x60, 0x60, (byte) 0xB0, 0x17, // magic preamble + 0x00, 0x00, 0x00, 0x05, // propose Bolt 5.0 + 0x00, 0x00, 0x00, 0x04, // propose Bolt 4.0 + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00 + }; + + /** + * Waits until the backend's native data-plane protocol is answering. The probe payload and + * expected response differ per engine: + *
    + *
  • Gremlin Server replies to a plain HTTP {@code GET /gremlin} (HTTP 400, not a + * WebSocket upgrade), confirming it is listening.
  • + *
  • Neo4j replies to the Bolt handshake with a 4-byte agreed version.
  • + *
+ */ + private static void waitForBackendReady(String clusterId, NeptuneDbType dbType, String host, int port) { + byte[] probe = switch (dbType) { + case GREMLIN -> "GET /gremlin HTTP/1.1\r\nHost: floci\r\n\r\n".getBytes(StandardCharsets.UTF_8); + case NEO4J -> BOLT_HANDSHAKE; + }; long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS; int attempt = 0; while (System.currentTimeMillis() < deadline) { @@ -140,17 +176,17 @@ public class NeptuneContainerManager { out.flush(); byte[] buf = new byte[32]; int n = s.getInputStream().read(buf); - if (n > 0) { + if (probeIndicatesReady(dbType, buf, n)) { if (attempt > 1) { - LOG.infov("Gremlin backend ready for cluster {0} after {1} probe attempt(s)", - clusterId, attempt); + LOG.infov("Neptune {0} backend ready for cluster {1} after {2} probe attempt(s)", + dbType, clusterId, attempt); } return; } } catch (IOException e) { if (LOG.isDebugEnabled()) { - LOG.debugv("Gremlin probe for cluster {0} attempt {1}: {2}", - clusterId, attempt, e.getMessage()); + LOG.debugv("Neptune {0} probe for cluster {1} attempt {2}: {3}", + dbType, clusterId, attempt, e.getMessage()); } } try { @@ -158,11 +194,28 @@ public class NeptuneContainerManager { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException( - "Interrupted while waiting for Gremlin backend " + clusterId, ie); + "Interrupted while waiting for Neptune " + dbType + " backend " + clusterId, ie); } } throw new RuntimeException( - "Gremlin backend for cluster " + clusterId + " did not become ready on " + "Neptune " + dbType + " backend for cluster " + clusterId + " did not become ready on " + host + ":" + port + " within " + BACKEND_READY_DEADLINE_MS + "ms"); } + + /** + * Decides whether a probe response signals readiness. For Gremlin any reply confirms the + * server is listening. For Neo4j the Bolt handshake reply is the 4-byte agreed version; + * an all-zero version ({@code 0x00000000}) means the connector answered but rejected every + * proposed Bolt version, so the backend is reachable but unusable — treat it as not-ready + * and keep retrying rather than handing back a cluster whose sessions will fail. + */ + private static boolean probeIndicatesReady(NeptuneDbType dbType, byte[] response, int n) { + if (n <= 0) { + return false; + } + return switch (dbType) { + case GREMLIN -> true; + case NEO4J -> n >= 4 && (response[0] | response[1] | response[2] | response[3]) != 0; + }; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbType.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbType.java new file mode 100644 index 0000000000..56bab887cd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbType.java @@ -0,0 +1,52 @@ +package io.github.hectorvent.floci.services.neptune.model; + +import java.util.Optional; + +/** + * Backend graph database engine used to emulate a Neptune cluster. + * + *

Amazon Neptune exposes several query languages over its data-plane endpoint. Floci backs + * each one with a different container image and proxies the matching wire protocol: + *

    + *
  • {@link #GREMLIN} — Apache TinkerPop Gremlin Server. Gremlin traversals over a + * WebSocket on port 8182 (Neptune's native default).
  • + *
  • {@link #NEO4J} — Neo4j. openCypher queries over the Bolt protocol on port 7687, + * matching Neptune's openCypher / Bolt endpoint.
  • + *
+ * + *

The engine is selected globally via {@code FLOCI_SERVICES_NEPTUNE_DB_TYPE}, mirroring + * LocalStack's {@code NEPTUNE_DB_TYPE} toggle. + */ +public enum NeptuneDbType { + + GREMLIN(8182), + NEO4J(7687); + + private final int backendPort; + + NeptuneDbType(int backendPort) { + this.backendPort = backendPort; + } + + /** Container port the backend listens on for its native data-plane protocol. */ + public int backendPort() { + return backendPort; + } + + /** + * Resolves a configured db-type string (case-insensitive) to an engine. + * Empty / null falls back to {@link #GREMLIN} to preserve historical behaviour. + * An unrecognised value returns {@link Optional#empty()} so the caller can fall back + * to the default rather than failing the client's request over a server-side typo. + */ + public static Optional fromConfig(String value) { + if (value == null || value.isBlank()) { + return Optional.of(GREMLIN); + } + return switch (value.trim().toLowerCase()) { + case "gremlin", "tinkerpop" -> Optional.of(GREMLIN); + case "neo4j", "opencypher", "cypher", "bolt" -> Optional.of(NEO4J); + default -> Optional.empty(); + }; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 14c60f2773..89c578c6c2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -207,7 +207,9 @@ floci: enabled: true proxy-base-port: 8182 proxy-max-port: 8282 + db-type: "gremlin" default-image: "tinkerpop/gremlin-server:3.7.3" + default-neo4j-image: "neo4j:5-community" eventbridge: enabled: true cloudmap: diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneOpenCypherIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneOpenCypherIntegrationTest.java new file mode 100644 index 0000000000..ce16de8c98 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneOpenCypherIntegrationTest.java @@ -0,0 +1,95 @@ +package io.github.hectorvent.floci.services.neptune; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.neo4j.driver.AuthTokens; +import org.neo4j.driver.Driver; +import org.neo4j.driver.GraphDatabase; +import org.neo4j.driver.Session; + +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Demonstrates that a Neptune cluster configured with {@code db-type=neo4j} speaks the + * openCypher query language over the Bolt protocol. + * + *

The default Gremlin backend ({@code tinkerpop/gremlin-server}) does NOT understand + * openCypher/Bolt, so before {@code db-type} support existed this test could not pass — + * the proxied port served a Gremlin WebSocket endpoint, not a Bolt endpoint. + */ +@QuarkusTest +@TestProfile(NeptuneOpenCypherIntegrationTest.Neo4jDbTypeProfile.class) +class NeptuneOpenCypherIntegrationTest { + + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String CLUSTER_ID = "opencypher-cluster"; + + // Fake SigV4 header whose credential scope service is "neptune" routes the management + // request (CreateDBCluster/DeleteDBCluster) to the Neptune service. + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260516/us-east-1/neptune/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + + private static final Pattern PORT = Pattern.compile("(\\d+)"); + + @Test + void openCypherQueryWorksOverBolt() { + String createResponse = given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("Engine", "neptune") + .when().post("/") + .then() + .statusCode(200) + .extract().asString(); + + int boltPort = parsePort(createResponse); + + try (Driver driver = GraphDatabase.driver( + "bolt://localhost:" + boltPort, AuthTokens.none())) { + driver.verifyConnectivity(); + try (Session session = driver.session()) { + long one = session.run("RETURN 1 AS n").single().get("n").asLong(); + assertEquals(1L, one, "openCypher RETURN should evaluate on the neo4j backend"); + + session.run("CREATE (:Person {name: 'Alice'})").consume(); + long count = session.run("MATCH (p:Person) RETURN count(p) AS c") + .single().get("c").asLong(); + assertEquals(1L, count, "openCypher CREATE + MATCH should round-trip"); + } + } finally { + given() + .header("Authorization", AUTH) + .contentType(FORM) + .formParam("Action", "DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200); + } + } + + private static int parsePort(String xml) { + Matcher m = PORT.matcher(xml); + if (!m.find()) { + throw new AssertionError("No in CreateDBCluster response: " + xml); + } + return Integer.parseInt(m.group(1)); + } + + public static final class Neo4jDbTypeProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.neptune.db-type", "neo4j"); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbTypeTest.java new file mode 100644 index 0000000000..27120e1a66 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/model/NeptuneDbTypeTest.java @@ -0,0 +1,43 @@ +package io.github.hectorvent.floci.services.neptune.model; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NeptuneDbTypeTest { + + @Test + void defaultsToGremlinWhenUnset() { + assertEquals(Optional.of(NeptuneDbType.GREMLIN), NeptuneDbType.fromConfig(null)); + assertEquals(Optional.of(NeptuneDbType.GREMLIN), NeptuneDbType.fromConfig("")); + assertEquals(Optional.of(NeptuneDbType.GREMLIN), NeptuneDbType.fromConfig(" ")); + } + + @Test + void parsesGremlinAliases() { + assertEquals(Optional.of(NeptuneDbType.GREMLIN), NeptuneDbType.fromConfig("gremlin")); + assertEquals(Optional.of(NeptuneDbType.GREMLIN), NeptuneDbType.fromConfig("TinkerPop")); + assertEquals(Optional.of(NeptuneDbType.GREMLIN), NeptuneDbType.fromConfig(" GREMLIN ")); + } + + @Test + void parsesNeo4jAliases() { + assertEquals(Optional.of(NeptuneDbType.NEO4J), NeptuneDbType.fromConfig("neo4j")); + assertEquals(Optional.of(NeptuneDbType.NEO4J), NeptuneDbType.fromConfig("openCypher")); + assertEquals(Optional.of(NeptuneDbType.NEO4J), NeptuneDbType.fromConfig("cypher")); + assertEquals(Optional.of(NeptuneDbType.NEO4J), NeptuneDbType.fromConfig("bolt")); + } + + @Test + void backendPortsMatchProtocols() { + assertEquals(8182, NeptuneDbType.GREMLIN.backendPort()); + assertEquals(7687, NeptuneDbType.NEO4J.backendPort()); + } + + @Test + void rejectsUnknownDbType() { + assertEquals(Optional.empty(), NeptuneDbType.fromConfig("sparql")); + } +}