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.
This commit is contained in:
Stuart Lang authored and GitHub committed 2026-06-20 11:24:00 -05:00
1 parent 5aee7b6312
commit 760d48b91a
10 files changed
+343 -32

No files matched your search

@@ -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<String> dockerNetwork();
}
@@ -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;
}
@@ -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<String> 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:
* <ul>
* <li>Gremlin Server replies to a plain HTTP {@code GET /gremlin} (HTTP 400, not a
* WebSocket upgrade), confirming it is listening.</li>
* <li>Neo4j replies to the Bolt handshake with a 4-byte agreed version.</li>
* </ul>
*/
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;
};
}
}
@@ -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.
*
* <p>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:
* <ul>
* <li>{@link #GREMLIN} — Apache TinkerPop Gremlin Server. Gremlin traversals over a
* WebSocket on port 8182 (Neptune's native default).</li>
* <li>{@link #NEO4J} — Neo4j. openCypher queries over the Bolt protocol on port 7687,
* matching Neptune's openCypher / Bolt endpoint.</li>
* </ul>
*
* <p>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<NeptuneDbType> 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();
};
}
}