You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tinkerpop.apache.org by co...@apache.org on 2026/05/29 18:04:30 UTC
(tinkerpop) branch gremlinSocketServer created (now 285b3af190)
This is an automated email from the ASF dual-hosted git repository.
Cole-Greer pushed a change to branch gremlinSocketServer
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
at 285b3af190 Port behavioral tests to all GLVs (Python, .NET, Go, JS)
This branch includes the following new commits:
new 0fe90f03d3 Add HTTP behavioral tests for Java driver
new 285b3af190 Port behavioral tests to all GLVs (Python, .NET, Go, JS)
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(tinkerpop) 02/02: Port behavioral tests to all GLVs (Python, .NET, Go, JS)
Posted by co...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
Cole-Greer pushed a commit to branch gremlinSocketServer
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit 285b3af190871140b151e5b22a415f3b22973ffc
Author: Cole Greer <co...@colegreer.ca>
AuthorDate: Thu May 28 14:34:22 2026 -0700
Port behavioral tests to all GLVs (Python, .NET, Go, JS)
Add ClientBehaviorIntegrationTests for each GLV against the shared
gremlin-socket-server HTTP test server. Each GLV has 12 test scenarios
matching the Java ClientBehaviorIntegrateTest (server downtime recovery
is skipped since GLVs cannot stop/restart the Docker container).
Docker changes:
- Add gremlin-socket-server service to all 4 GLV docker-compose files
- Set GREMLIN_SOCKET_SERVER_URL env var for test containers
- Remove old conf volume mounts (.NET, JS)
Python:
- Add socket_server_constants.py and test_client_behavior.py
- Remove old test_web_socket_client_behavior.py
.NET:
- Add SocketServerConstants.cs and ClientBehaviorIntegrationTests.cs
- Remove old SocketServerSettings.cs and YamlDotNet dependency
Go:
- Add socket_server_constants_test.go and client_behavior_test.go
JavaScript:
- Add socket-server-constants.js and client-behavior-tests.js
---
.dockerignore | 2 +
gremlin-dotnet/docker-compose.yml | 16 +-
.../Driver/ClientBehaviorIntegrationTests.cs | 303 +++++++++++++++++++++
.../Driver/SocketServerConstants.cs | 39 +++
.../Gremlin.Net.IntegrationTest.csproj | 1 -
.../Util/SocketServerSettings.cs | 94 -------
gremlin-go/docker-compose.override.yml | 4 +
gremlin-go/docker-compose.yml | 15 +
gremlin-go/driver/client_behavior_test.go | 254 +++++++++++++++++
gremlin-go/driver/socket_server_constants_test.go | 33 +++
gremlin-js/gremlin-javascript/docker-compose.yml | 16 +-
.../test/integration/client-behavior-tests.js | 152 +++++++++++
.../test/integration/socket-server-constants.js | 10 +
gremlin-python/docker-compose.yml | 15 +
.../integration/driver/socket_server_constants.py | 29 ++
.../integration/driver/test_client_behavior.py | 190 +++++++++++++
.../driver/test_web_socket_client_behavior.py | 100 -------
17 files changed, 1076 insertions(+), 197 deletions(-)
diff --git a/.dockerignore b/.dockerignore
index 50d6801832..4e566f8f81 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -2,6 +2,8 @@
**/target
!gremlin-server/target/apache-tinkerpop-gremlin-server-*
!gremlin-console/target/apache-tinkerpop-gremlin-console-*
+!gremlin-tools/gremlin-socket-server/target/gremlin-socket-server-*
+!gremlin-tools/gremlin-socket-server/target/libs
*.iml
.idea
**/*.DS_Store
diff --git a/gremlin-dotnet/docker-compose.yml b/gremlin-dotnet/docker-compose.yml
index a5d5b89c47..d68175d0e3 100644
--- a/gremlin-dotnet/docker-compose.yml
+++ b/gremlin-dotnet/docker-compose.yml
@@ -41,6 +41,18 @@ services:
retries: 30
start_period: 30s
+ gremlin-socket-server-test-dotnet:
+ container_name: gremlin-socket-server-test-dotnet
+ image: tinkerpop/gremlin-socket-server:${GREMLIN_SERVER}
+ build:
+ context: ../
+ dockerfile: gremlin-tools/gremlin-socket-server/Dockerfile
+ args:
+ - SOCKET_SERVER_DIR=gremlin-tools/gremlin-socket-server/target/
+ - SOCKET_SERVER_VERSION=${GREMLIN_SERVER}
+ ports:
+ - "45943:45943"
+
gremlin-dotnet-integration-tests:
container_name: gremlin-dotnet-integration-tests
image: mcr.microsoft.com/dotnet/sdk:8.0
@@ -49,12 +61,12 @@ services:
- ../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features:/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features
- ../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/structure/io:/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/structure/io
- ../docker/gremlin-test-server:/gremlin-dotnet/gremlin-test-server
- - ../gremlin-tools/gremlin-socket-server/conf:/gremlin-dotnet/gremlin-socket-server/conf/
environment:
- DOCKER_ENVIRONMENT=true
- GREMLIN_SERVER_HOST=gremlin-server-test-dotnet
- GREMLIN_SERVER_PORT=45940
- GREMLIN_SECURE_SERVER_PORT=45941
+ - GREMLIN_SOCKET_SERVER_URL=http://gremlin-socket-server-test-dotnet:45943/gremlin
- VERTEX_LABEL=dotnet-example
working_dir: /gremlin-dotnet
command: >
@@ -72,3 +84,5 @@ services:
depends_on:
gremlin-server-test-dotnet:
condition: service_healthy
+ gremlin-socket-server-test-dotnet:
+ condition: service_started
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/ClientBehaviorIntegrationTests.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/ClientBehaviorIntegrationTests.cs
new file mode 100644
index 0000000000..13b2f9631d
--- /dev/null
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/ClientBehaviorIntegrationTests.cs
@@ -0,0 +1,303 @@
+#region License
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Gremlin.Net.Driver;
+using Gremlin.Net.Driver.Exceptions;
+using Xunit;
+
+namespace Gremlin.Net.IntegrationTest.Driver
+{
+ public class ClientBehaviorIntegrationTests : IAsyncLifetime
+ {
+ private static readonly string Host = GetHost();
+ private GremlinClient? _client;
+ private bool _serverAvailable;
+
+ private static string GetHost()
+ {
+ var url = Environment.GetEnvironmentVariable("GREMLIN_SOCKET_SERVER_URL");
+ if (string.IsNullOrEmpty(url)) return "localhost";
+ try
+ {
+ return new Uri(url).Host;
+ }
+ catch
+ {
+ return "localhost";
+ }
+ }
+
+ public async Task InitializeAsync()
+ {
+ var server = new GremlinServer(Host, SocketServerConstants.Port);
+ _client = new GremlinClient(server);
+ try
+ {
+ var resultSet = await _client.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ await resultSet.ToListAsync();
+ _serverAvailable = true;
+ }
+ catch
+ {
+ _serverAvailable = false;
+ }
+ }
+
+ public Task DisposeAsync()
+ {
+ _client?.Dispose();
+ return Task.CompletedTask;
+ }
+
+ private void SkipIfServerUnavailable()
+ {
+ if (!_serverAvailable)
+ throw new Exception("$XunitDynamicSkip$Socket server not available");
+ }
+
+ private GremlinClient CreateClient()
+ {
+ return new GremlinClient(new GremlinServer(Host, SocketServerConstants.Port));
+ }
+
+ [Fact]
+ public async Task ShouldReceiveSingleVertex()
+ {
+ SkipIfServerUnavailable();
+
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandleServerClosingConnectionBeforeResponse()
+ {
+ SkipIfServerUnavailable();
+
+ await Assert.ThrowsAnyAsync<Exception>(async () =>
+ {
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinCloseConnection);
+ await resultSet.ToListAsync();
+ });
+
+ // Recovery
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandleServerClosingConnectionAfterResponse()
+ {
+ SkipIfServerUnavailable();
+
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinVertexThenClose);
+ var results = await resultSet.ToListAsync();
+ Assert.NotEmpty(results);
+
+ await Task.Delay(TimeSpan.FromSeconds(3));
+
+ // Recovery
+ resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandleServerErrorAfterDelay()
+ {
+ SkipIfServerUnavailable();
+
+ var ex = await Assert.ThrowsAsync<ResponseException>(async () =>
+ {
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinFailAfterDelay);
+ await resultSet.ToListAsync();
+ });
+ Assert.Equal(500, ex.StatusCode);
+
+ // Recovery
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandlePartialContentClose()
+ {
+ SkipIfServerUnavailable();
+
+ await Assert.ThrowsAnyAsync<Exception>(async () =>
+ {
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinPartialContentClose);
+ await resultSet.ToListAsync();
+ });
+
+ // Recovery
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandleMalformedResponse()
+ {
+ SkipIfServerUnavailable();
+
+ await Assert.ThrowsAnyAsync<Exception>(async () =>
+ {
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinMalformedResponse);
+ await resultSet.ToListAsync();
+ });
+
+ // Recovery
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandleEmptyResponseBody()
+ {
+ SkipIfServerUnavailable();
+
+ await Assert.ThrowsAnyAsync<Exception>(async () =>
+ {
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinEmptyBody);
+ await resultSet.ToListAsync();
+ });
+
+ // Recovery
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact]
+ public async Task ShouldHandleSlowResponse()
+ {
+ SkipIfServerUnavailable();
+
+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSlowResponse,
+ cancellationToken: cts.Token);
+ var results = await resultSet.ToListAsync(cts.Token);
+
+ Assert.NotEmpty(results);
+ }
+
+ [Fact]
+ public async Task ShouldTimeoutWhenServerNeverResponds()
+ {
+ SkipIfServerUnavailable();
+
+ using var timeoutClient = CreateClient();
+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
+
+ await Assert.ThrowsAnyAsync<Exception>(async () =>
+ {
+ var resultSet = await timeoutClient.SubmitAsync<dynamic>(
+ SocketServerConstants.GremlinNoResponse, cancellationToken: cts.Token);
+ await resultSet.ToListAsync(cts.Token);
+ });
+
+ // Recovery with main client
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var results = await resultSet.ToListAsync();
+ Assert.Single(results);
+ }
+
+ [Fact(Skip = "Requires server stop/restart")]
+ public Task ShouldRecoverFromTemporaryServerDowntime()
+ {
+ return Task.CompletedTask;
+ }
+
+ [Fact]
+ public async Task ShouldHandleAsyncRequestsDuringConnectionClose()
+ {
+ SkipIfServerUnavailable();
+
+ var task1 = Task.Run(async () =>
+ {
+ var rs = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinCloseConnection);
+ await rs.ToListAsync();
+ });
+ var task2 = Task.Run(async () =>
+ {
+ var rs = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinCloseConnection);
+ await rs.ToListAsync();
+ });
+
+ var results = await Task.WhenAll(
+ Task.Run(async () => { try { await task1; return true; } catch { return false; } }),
+ Task.Run(async () => { try { await task2; return true; } catch { return false; } }));
+
+ Assert.Contains(false, results);
+
+ // Recovery
+ var resultSet = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ var list = await resultSet.ToListAsync();
+ Assert.Single(list);
+ }
+
+ [Fact]
+ public async Task ShouldHandleConcurrentMixedRequests()
+ {
+ SkipIfServerUnavailable();
+
+ var goodTasks = Enumerable.Range(0, 5).Select(_ => Task.Run(async () =>
+ {
+ var rs = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinSingleVertex);
+ return await rs.ToListAsync();
+ })).ToList();
+
+ var badTasks = Enumerable.Range(0, 5).Select(_ => Task.Run(async () =>
+ {
+ var rs = await _client!.SubmitAsync<dynamic>(SocketServerConstants.GremlinCloseConnection);
+ await rs.ToListAsync();
+ })).ToList();
+
+ var goodResults = await Task.WhenAll(goodTasks.Select(async t =>
+ {
+ try { return await t; }
+ catch { return null; }
+ }));
+
+ var badResults = await Task.WhenAll(badTasks.Select(async t =>
+ {
+ try { await t; return false; }
+ catch { return true; }
+ }));
+
+ Assert.Contains(goodResults, r => r != null && r.Count > 0);
+ Assert.All(badResults, failed => Assert.True(failed));
+ }
+ }
+}
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/SocketServerConstants.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/SocketServerConstants.cs
new file mode 100644
index 0000000000..15b943f52a
--- /dev/null
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/SocketServerConstants.cs
@@ -0,0 +1,39 @@
+#region License
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#endregion
+
+namespace Gremlin.Net.IntegrationTest.Driver
+{
+ public static class SocketServerConstants
+ {
+ public const int Port = 45943;
+ public const string GremlinSingleVertex = "server_single_vertex";
+ public const string GremlinCloseConnection = "server_close_connection";
+ public const string GremlinVertexThenClose = "server_vertex_then_close";
+ public const string GremlinFailAfterDelay = "server_fail_after_delay";
+ public const string GremlinPartialContentClose = "server_partial_content_close";
+ public const string GremlinSlowResponse = "server_slow_response";
+ public const string GremlinMalformedResponse = "server_malformed_response";
+ public const string GremlinNoResponse = "server_no_response";
+ public const string GremlinEmptyBody = "server_empty_body";
+ }
+}
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gremlin.Net.IntegrationTest.csproj b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gremlin.Net.IntegrationTest.csproj
index 933f32323b..dbe2d72024 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gremlin.Net.IntegrationTest.csproj
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gremlin.Net.IntegrationTest.csproj
@@ -22,7 +22,6 @@
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
- <PackageReference Include="YamlDotNet" Version="12.2.0" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Util/SocketServerSettings.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Util/SocketServerSettings.cs
deleted file mode 100644
index a2b5766138..0000000000
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Util/SocketServerSettings.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-#region License
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#endregion
-
-using System;
-using System.IO;
-using YamlDotNet.Serialization;
-
-namespace Gremlin.Net.IntegrationTest.Util;
-
-public class SocketServerSettings
-{
- [YamlMember(Alias = "PORT", ApplyNamingConventions = false)]
- public int Port { get; set; }
-
- /**
- * Configures which serializer will be used. Ex: "GraphBinaryV1" or "GraphSONV2"
- */
- [YamlMember(Alias = "SERIALIZER", ApplyNamingConventions = false)]
- public String Serializer { get; set; }
-
- /**
- * If a request with this ID comes to the server, the server responds back with a single vertex picked from Modern
- * graph.
- */
- [YamlMember(Alias = "SINGLE_VERTEX_REQUEST_ID", ApplyNamingConventions = false)]
- public Guid SingleVertexRequestId { get; set; }
-
- /**
- * If a request with this ID comes to the server, the server responds back with a single vertex picked from Modern
- * graph. After a 2 second delay, server sends a Close WebSocket frame on the same connection.
- */
- [YamlMember(Alias = "SINGLE_VERTEX_DELAYED_CLOSE_CONNECTION_REQUEST_ID", ApplyNamingConventions = false)]
- public Guid SingleVertexDelayedCloseConnectionRequestId { get; set; }
-
- /**
- * Server waits for 1 second, then responds with a 500 error status code
- */
- [YamlMember(Alias = "FAILED_AFTER_DELAY_REQUEST_ID", ApplyNamingConventions = false)]
- public Guid FailedAfterDelayRequestId { get; set; }
-
- /**
- * Server waits for 1 second then responds with a close web socket frame
- */
- [YamlMember(Alias = "CLOSE_CONNECTION_REQUEST_ID", ApplyNamingConventions = false)]
- public Guid CloseConnectionRequestId { get; set; }
-
- /**
- * Same as CLOSE_CONNECTION_REQUEST_ID
- */
- [YamlMember(Alias = "CLOSE_CONNECTION_REQUEST_ID_2", ApplyNamingConventions = false)]
- public Guid CloseConnectionRequestId2 { get; set; }
-
- /**
- * If a request with this ID comes to the server, the server responds with the user agent (if any) that was captured
- * during the web socket handshake.
- */
- [YamlMember(Alias = "USER_AGENT_REQUEST_ID", ApplyNamingConventions = false)]
- public Guid UserAgentRequestId { get; set; }
-
- /**
- * If a request with this ID comes to the server, the server responds with a string containing all overridden
- * per request settings from the request message. String will be of the form
- * "requestId=19436d9e-f8fc-4b67-8a76-deec60918424 evaluationTimeout=1234, batchSize=12, userAgent=testUserAgent"
- */
- [YamlMember(Alias = "PER_REQUEST_SETTINGS_REQUEST_ID", ApplyNamingConventions = false)]
- public Guid PerRequestSettingsRequestId { get; set; }
-
- public static SocketServerSettings FromYaml(String path)
- {
- var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().IgnoreUnmatchedProperties().Build();
-
- return deserializer.Deserialize<SocketServerSettings>(File.ReadAllText(path));
- }
-}
\ No newline at end of file
diff --git a/gremlin-go/docker-compose.override.yml b/gremlin-go/docker-compose.override.yml
new file mode 100644
index 0000000000..04af5c9ff9
--- /dev/null
+++ b/gremlin-go/docker-compose.override.yml
@@ -0,0 +1,4 @@
+services:
+ gremlin-go-integration-tests:
+ environment:
+ - GOPROXY=direct
diff --git a/gremlin-go/docker-compose.yml b/gremlin-go/docker-compose.yml
index 37206156dd..5df1561826 100644
--- a/gremlin-go/docker-compose.yml
+++ b/gremlin-go/docker-compose.yml
@@ -41,6 +41,18 @@ services:
retries: 30
start_period: 30s
+ gremlin-socket-server-test-go:
+ container_name: gremlin-socket-server-test-go
+ image: tinkerpop/gremlin-socket-server:${GREMLIN_SERVER}
+ build:
+ context: ../
+ dockerfile: gremlin-tools/gremlin-socket-server/Dockerfile
+ args:
+ - SOCKET_SERVER_DIR=gremlin-tools/gremlin-socket-server/target/
+ - SOCKET_SERVER_VERSION=${GREMLIN_SERVER}
+ ports:
+ - "45943:45943"
+
gremlin-go-integration-tests:
container_name: gremlin-go-integration-tests
image: golang:1.25
@@ -52,6 +64,7 @@ services:
- CUCUMBER_FEATURE_FOLDER=/gremlin-test
- GREMLIN_SERVER_URL=http://gremlin-server-test:45940/gremlin
- GREMLIN_SERVER_BASIC_AUTH_URL=https://gremlin-server-test:45941/gremlin
+ - GREMLIN_SOCKET_SERVER_URL=http://gremlin-socket-server-test-go:45943/gremlin
- RUN_INTEGRATION_TESTS=true
- RUN_INTEGRATION_WITH_ALIAS_TESTS=true
- RUN_BASIC_AUTH_INTEGRATION_TESTS=true
@@ -68,3 +81,5 @@ services:
depends_on:
gremlin-server-test:
condition: service_healthy
+ gremlin-socket-server-test-go:
+ condition: service_started
diff --git a/gremlin-go/driver/client_behavior_test.go b/gremlin-go/driver/client_behavior_test.go
new file mode 100644
index 0000000000..089d2576cf
--- /dev/null
+++ b/gremlin-go/driver/client_behavior_test.go
@@ -0,0 +1,254 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package gremlingo
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func socketServerURL() string {
+ return getEnvOrDefaultString("GREMLIN_SOCKET_SERVER_URL",
+ fmt.Sprintf("http://localhost:%d/gremlin", socketServerPort))
+}
+
+func newSocketServerClient(t *testing.T, configurations ...func(*ClientSettings)) *Client {
+ t.Helper()
+ url := socketServerURL()
+ client, err := NewClient(url, configurations...)
+ if err != nil {
+ t.Skipf("Socket server not available: %v", err)
+ }
+ // Verify connectivity
+ _, submitErr := client.Submit(gremlinSingleVertex)
+ if submitErr != nil {
+ client.Close()
+ t.Skip("Socket server not available")
+ }
+ return client
+}
+
+func assertRecovery(t *testing.T, client *Client) {
+ t.Helper()
+ rs, err := client.Submit(gremlinSingleVertex)
+ assert.NoError(t, err)
+ results, err := rs.All()
+ assert.NoError(t, err)
+ assert.Equal(t, 1, len(results))
+}
+
+// submitExpectErr submits the gremlin string and returns the effective error.
+// Errors may surface either from Submit() or from reading the ResultSet via All().
+func submitExpectErr(client *Client, gremlin string) error {
+ rs, err := client.Submit(gremlin)
+ if err != nil {
+ return err
+ }
+ _, err = rs.All()
+ return err
+}
+
+func TestShouldReceiveSingleVertex(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ rs, err := client.Submit(gremlinSingleVertex)
+ require.NoError(t, err)
+ results, err := rs.All()
+ require.NoError(t, err)
+ assert.Equal(t, 1, len(results))
+}
+
+func TestShouldHandleServerClosingConnectionBeforeResponse(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ err := submitExpectErr(client, gremlinCloseConnection)
+ assert.Error(t, err)
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandleServerClosingConnectionAfterResponse(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ rs, err := client.Submit(gremlinVertexThenClose)
+ require.NoError(t, err)
+ results, err := rs.All()
+ require.NoError(t, err)
+ assert.Equal(t, 1, len(results))
+
+ time.Sleep(3 * time.Second)
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandleServerErrorAfterDelay(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ err := submitExpectErr(client, gremlinFailAfterDelay)
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "500")
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandlePartialContentClose(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ err := submitExpectErr(client, gremlinPartialContentClose)
+ assert.Error(t, err)
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandleMalformedResponse(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ err := submitExpectErr(client, gremlinMalformedResponse)
+ assert.Error(t, err)
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandleEmptyResponseBody(t *testing.T) {
+ url := socketServerURL()
+ client, err := NewClient(url, func(settings *ClientSettings) {
+ settings.ConnectionTimeout = 5 * time.Second
+ })
+ if err != nil {
+ t.Skip("Socket server not available")
+ }
+ defer client.Close()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ done := make(chan error, 1)
+ go func() {
+ done <- submitExpectErr(client, gremlinEmptyBody)
+ }()
+
+ // The key requirement is that an empty response body does not hang.
+ // NOTE: Unlike the Java/Python/JS drivers (which raise an error), the Go
+ // driver currently treats an empty body as an empty (successful) result
+ // set rather than an error. This driver gap is flagged in the cross-GLV
+ // error-message audit (tinkerpop-8lw.6) for further consideration.
+ select {
+ case <-done:
+ // completed without hanging - acceptable for now
+ case <-ctx.Done():
+ t.Fatal("request hung on empty response body")
+ }
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandleSlowResponse(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ rs, err := client.Submit(gremlinSlowResponse)
+ require.NoError(t, err)
+ results, err := rs.All()
+ require.NoError(t, err)
+ assert.GreaterOrEqual(t, len(results), 1)
+}
+
+func TestShouldTimeoutWhenServerNeverResponds(t *testing.T) {
+ // The Go driver's ConnectionTimeout only governs connection establishment,
+ // not how long to wait for a response. With no client-side request/read
+ // timeout, a server that never responds causes an indefinite hang. Skipped
+ // until the driver supports a request timeout (flagged in tinkerpop-8lw.6).
+ t.Skip("Go driver lacks a client-side request/read timeout")
+}
+
+func TestShouldRecoverFromTemporaryServerDowntime(t *testing.T) {
+ t.Skip("requires server stop/restart")
+}
+
+func TestShouldHandleAsyncRequestsDuringConnectionClose(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ var wg sync.WaitGroup
+ wg.Add(2)
+
+ for i := 0; i < 2; i++ {
+ go func() {
+ defer wg.Done()
+ err := submitExpectErr(client, gremlinCloseConnection)
+ assert.Error(t, err)
+ }()
+ }
+
+ wg.Wait()
+
+ assertRecovery(t, client)
+}
+
+func TestShouldHandleConcurrentMixedRequests(t *testing.T) {
+ client := newSocketServerClient(t)
+ defer client.Close()
+
+ var wg sync.WaitGroup
+ goodResults := make([]error, 5)
+ badResults := make([]error, 5)
+
+ for i := 0; i < 5; i++ {
+ wg.Add(1)
+ go func(idx int) {
+ defer wg.Done()
+ rs, err := client.Submit(gremlinSingleVertex)
+ if err != nil {
+ goodResults[idx] = err
+ return
+ }
+ _, goodResults[idx] = rs.All()
+ }(i)
+ }
+
+ for i := 0; i < 5; i++ {
+ wg.Add(1)
+ go func(idx int) {
+ defer wg.Done()
+ badResults[idx] = submitExpectErr(client, gremlinCloseConnection)
+ }(i)
+ }
+
+ wg.Wait()
+
+ for i, err := range goodResults {
+ assert.NoError(t, err, "good request %d should succeed", i)
+ }
+ for i, err := range badResults {
+ assert.Error(t, err, "bad request %d should fail", i)
+ }
+}
diff --git a/gremlin-go/driver/socket_server_constants_test.go b/gremlin-go/driver/socket_server_constants_test.go
new file mode 100644
index 0000000000..d5316799ee
--- /dev/null
+++ b/gremlin-go/driver/socket_server_constants_test.go
@@ -0,0 +1,33 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package gremlingo
+
+const (
+ socketServerPort = 45943
+ gremlinSingleVertex = "server_single_vertex"
+ gremlinCloseConnection = "server_close_connection"
+ gremlinVertexThenClose = "server_vertex_then_close"
+ gremlinFailAfterDelay = "server_fail_after_delay"
+ gremlinPartialContentClose = "server_partial_content_close"
+ gremlinSlowResponse = "server_slow_response"
+ gremlinMalformedResponse = "server_malformed_response"
+ gremlinNoResponse = "server_no_response"
+ gremlinEmptyBody = "server_empty_body"
+)
diff --git a/gremlin-js/gremlin-javascript/docker-compose.yml b/gremlin-js/gremlin-javascript/docker-compose.yml
index f7465a4ca2..6b90238a30 100644
--- a/gremlin-js/gremlin-javascript/docker-compose.yml
+++ b/gremlin-js/gremlin-javascript/docker-compose.yml
@@ -41,6 +41,18 @@ services:
retries: 30
start_period: 30s
+ gremlin-socket-server-test-js:
+ container_name: gremlin-socket-server-test-js
+ image: tinkerpop/gremlin-socket-server:${GREMLIN_SERVER}
+ build:
+ context: ../../
+ dockerfile: gremlin-tools/gremlin-socket-server/Dockerfile
+ args:
+ - SOCKET_SERVER_DIR=gremlin-tools/gremlin-socket-server/target/
+ - SOCKET_SERVER_VERSION=${GREMLIN_SERVER}
+ ports:
+ - "45943:45943"
+
gremlin-js-integration-tests:
container_name: gremlin-js-integration-tests
image: node:${NODE_VERSION:-22}
@@ -50,12 +62,12 @@ services:
- ../../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/structure/io/graphbinary:/workspace/gremlin-js/gremlin-javascript/gremlin-test/graphbinary
- ../../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator:/workspace/gremlin-js/gremlin-javascript/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator
- ../../docker/gremlin-test-server:/workspace/gremlin-js/gremlin-javascript/gremlin-test-server
- - ../../gremlin-tools/gremlin-socket-server/conf:/workspace/gremlin-js/gremlin-javascript/gremlin-socket-server/conf/
- ../../gremlin-language/src/main/antlr4:/gremlin-language/src/main/antlr4
- ../..:/workspace
environment:
- DOCKER_ENVIRONMENT=true
- GREMLIN_SERVER_URL=http://gremlin-server-test-js:45940/gremlin
+ - GREMLIN_SOCKET_SERVER_URL=http://gremlin-socket-server-test-js:45943/gremlin
- VERTEX_LABEL=javascript-example
- IO_TEST_DIRECTORY=/workspace/gremlin-js/gremlin-javascript/gremlin-test/graphbinary/
- NPM_CONFIG_CACHE=/tmp/npm-cache
@@ -71,5 +83,7 @@ services:
depends_on:
gremlin-server-test-js:
condition: service_healthy
+ gremlin-socket-server-test-js:
+ condition: service_started
diff --git a/gremlin-js/gremlin-javascript/test/integration/client-behavior-tests.js b/gremlin-js/gremlin-javascript/test/integration/client-behavior-tests.js
new file mode 100644
index 0000000000..0a8b282e65
--- /dev/null
+++ b/gremlin-js/gremlin-javascript/test/integration/client-behavior-tests.js
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'assert';
+
+import Client from '../../lib/driver/client.js';
+
+import {
+ GREMLIN_SINGLE_VERTEX,
+ GREMLIN_CLOSE_CONNECTION,
+ GREMLIN_VERTEX_THEN_CLOSE,
+ GREMLIN_FAIL_AFTER_DELAY,
+ GREMLIN_PARTIAL_CONTENT_CLOSE,
+ GREMLIN_SLOW_RESPONSE,
+ GREMLIN_MALFORMED_RESPONSE,
+ GREMLIN_NO_RESPONSE,
+ GREMLIN_EMPTY_BODY,
+} from './socket-server-constants.js';
+
+const url = process.env.GREMLIN_SOCKET_SERVER_URL || 'http://localhost:45943/gremlin';
+
+function createClient(options) {
+ return new Client(url, { traversalSource: 'g', ...options });
+}
+
+function delay(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+describe('Client Behavior', function () {
+ this.timeout(30000);
+ let client;
+
+ before(async function () {
+ client = createClient();
+ try {
+ await client.submit(GREMLIN_SINGLE_VERTEX);
+ } catch (e) {
+ client.close();
+ this.skip();
+ }
+ });
+
+ after(function () {
+ return client.close();
+ });
+
+ it('should return a single vertex', async function () {
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle connection close before response and recover', async function () {
+ await assert.rejects(client.submit(GREMLIN_CLOSE_CONNECTION));
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle connection close after response and recover', async function () {
+ const result = await client.submit(GREMLIN_VERTEX_THEN_CLOSE);
+ assert.strictEqual(result.length, 1);
+ await delay(3000);
+ const recovery = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(recovery.length, 1);
+ });
+
+ it('should handle server error after delay and recover', async function () {
+ try {
+ await client.submit(GREMLIN_FAIL_AFTER_DELAY);
+ assert.fail('Expected an error');
+ } catch (err) {
+ assert.ok(err.statusCode || err.message);
+ }
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle partial content close and recover', async function () {
+ await assert.rejects(client.submit(GREMLIN_PARTIAL_CONTENT_CLOSE));
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle malformed response and recover', async function () {
+ await assert.rejects(client.submit(GREMLIN_MALFORMED_RESPONSE));
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle empty response body and recover', async function () {
+ this.timeout(10000);
+ await assert.rejects(client.submit(GREMLIN_EMPTY_BODY));
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle slow response', async function () {
+ this.timeout(30000);
+ const result = await client.submit(GREMLIN_SLOW_RESPONSE);
+ assert.ok(result.length > 0);
+ });
+
+ it.skip('should timeout when server never responds - JS driver lacks client-side idle timeout', async function () {
+ const shortTimeoutClient = createClient({ requestTimeout: 1000 });
+ try {
+ await assert.rejects(shortTimeoutClient.submit(GREMLIN_NO_RESPONSE));
+ const result = await shortTimeoutClient.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ } finally {
+ shortTimeoutClient.close();
+ }
+ });
+
+ it.skip('should recover from temporary server downtime', function () {
+ // requires server stop/restart
+ });
+
+ it('should handle async requests during connection close', async function () {
+ const p1 = client.submit(GREMLIN_CLOSE_CONNECTION);
+ const p2 = client.submit(GREMLIN_CLOSE_CONNECTION);
+ await assert.rejects(p1);
+ await assert.rejects(p2);
+ const result = await client.submit(GREMLIN_SINGLE_VERTEX);
+ assert.strictEqual(result.length, 1);
+ });
+
+ it('should handle concurrent mixed requests', async function () {
+ const good = Array.from({ length: 5 }, () => client.submit(GREMLIN_SINGLE_VERTEX));
+ const bad = Array.from({ length: 5 }, () => client.submit(GREMLIN_CLOSE_CONNECTION));
+ const results = await Promise.allSettled([...good, ...bad]);
+ const fulfilled = results.filter((r) => r.status === 'fulfilled');
+ const rejected = results.filter((r) => r.status === 'rejected');
+ assert.ok(fulfilled.length > 0, 'Expected at least some fulfilled results');
+ assert.ok(rejected.length > 0, 'Expected at least some rejected results');
+ });
+});
diff --git a/gremlin-js/gremlin-javascript/test/integration/socket-server-constants.js b/gremlin-js/gremlin-javascript/test/integration/socket-server-constants.js
new file mode 100644
index 0000000000..28d01ab0d3
--- /dev/null
+++ b/gremlin-js/gremlin-javascript/test/integration/socket-server-constants.js
@@ -0,0 +1,10 @@
+export const PORT = 45943;
+export const GREMLIN_SINGLE_VERTEX = 'server_single_vertex';
+export const GREMLIN_CLOSE_CONNECTION = 'server_close_connection';
+export const GREMLIN_VERTEX_THEN_CLOSE = 'server_vertex_then_close';
+export const GREMLIN_FAIL_AFTER_DELAY = 'server_fail_after_delay';
+export const GREMLIN_PARTIAL_CONTENT_CLOSE = 'server_partial_content_close';
+export const GREMLIN_SLOW_RESPONSE = 'server_slow_response';
+export const GREMLIN_MALFORMED_RESPONSE = 'server_malformed_response';
+export const GREMLIN_NO_RESPONSE = 'server_no_response';
+export const GREMLIN_EMPTY_BODY = 'server_empty_body';
diff --git a/gremlin-python/docker-compose.yml b/gremlin-python/docker-compose.yml
index a964559979..2876bbf048 100644
--- a/gremlin-python/docker-compose.yml
+++ b/gremlin-python/docker-compose.yml
@@ -41,6 +41,18 @@ services:
retries: 30
start_period: 30s
+ gremlin-socket-server-test-python:
+ container_name: gremlin-socket-server-test-python
+ image: tinkerpop/gremlin-socket-server:${GREMLIN_SERVER}
+ build:
+ context: ../
+ dockerfile: gremlin-tools/gremlin-socket-server/Dockerfile
+ args:
+ - SOCKET_SERVER_DIR=gremlin-tools/gremlin-socket-server/target/
+ - SOCKET_SERVER_VERSION=${GREMLIN_SERVER}
+ ports:
+ - "45943:45943"
+
gremlin-python-integration-tests:
container_name: gremlin-python-integration-tests
image: python:${PYTHON_VERSION:-3.10}
@@ -53,6 +65,7 @@ services:
- DEBIAN_FRONTEND=noninteractive
- GREMLIN_SERVER_URL=http://gremlin-server-test-python:{}/gremlin
- GREMLIN_SERVER_BASIC_AUTH_URL=https://gremlin-server-test-python:{}/gremlin
+ - GREMLIN_SOCKET_SERVER_URL=http://gremlin-socket-server-test-python:45943/gremlin
- IO_TEST_DIRECTORY=/python_app/gremlin-test/graphbinary/
- PYTEST_ARGS=${PYTEST_ARGS:-}
- RADISH_ARGS=${RADISH_ARGS:-}
@@ -81,6 +94,8 @@ services:
depends_on:
gremlin-server-test-python:
condition: service_healthy
+ gremlin-socket-server-test-python:
+ condition: service_started
gremlin-python-package:
container_name: gremlin-python-package
diff --git a/gremlin-python/src/main/python/tests/integration/driver/socket_server_constants.py b/gremlin-python/src/main/python/tests/integration/driver/socket_server_constants.py
new file mode 100644
index 0000000000..3306e5ec65
--- /dev/null
+++ b/gremlin-python/src/main/python/tests/integration/driver/socket_server_constants.py
@@ -0,0 +1,29 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+PORT = 45943
+GREMLIN_SINGLE_VERTEX = "server_single_vertex"
+GREMLIN_CLOSE_CONNECTION = "server_close_connection"
+GREMLIN_VERTEX_THEN_CLOSE = "server_vertex_then_close"
+GREMLIN_FAIL_AFTER_DELAY = "server_fail_after_delay"
+GREMLIN_PARTIAL_CONTENT_CLOSE = "server_partial_content_close"
+GREMLIN_SLOW_RESPONSE = "server_slow_response"
+GREMLIN_MALFORMED_RESPONSE = "server_malformed_response"
+GREMLIN_NO_RESPONSE = "server_no_response"
+GREMLIN_EMPTY_BODY = "server_empty_body"
diff --git a/gremlin-python/src/main/python/tests/integration/driver/test_client_behavior.py b/gremlin-python/src/main/python/tests/integration/driver/test_client_behavior.py
new file mode 100644
index 0000000000..3e4678c0b1
--- /dev/null
+++ b/gremlin-python/src/main/python/tests/integration/driver/test_client_behavior.py
@@ -0,0 +1,190 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+import os
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+import pytest
+
+from gremlin_python.driver.client import Client
+from gremlin_python.driver.serializer import GraphBinarySerializersV4
+
+from .socket_server_constants import (
+ PORT,
+ GREMLIN_SINGLE_VERTEX,
+ GREMLIN_CLOSE_CONNECTION,
+ GREMLIN_VERTEX_THEN_CLOSE,
+ GREMLIN_FAIL_AFTER_DELAY,
+ GREMLIN_PARTIAL_CONTENT_CLOSE,
+ GREMLIN_SLOW_RESPONSE,
+ GREMLIN_MALFORMED_RESPONSE,
+ GREMLIN_NO_RESPONSE,
+ GREMLIN_EMPTY_BODY,
+)
+
+url = os.environ.get('GREMLIN_SOCKET_SERVER_URL', 'http://localhost:{}/gremlin'.format(PORT))
+
+
+@pytest.fixture(scope="module")
+def socket_server_client():
+ try:
+ client = Client(url, 'g')
+ # Verify connectivity
+ client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ except Exception:
+ pytest.skip("Socket server is not available at {}".format(url))
+ yield client
+ client.close()
+
+
+@pytest.fixture
+def fresh_client():
+ client = Client(url, 'g')
+ yield client
+ client.close()
+
+
+def test_should_receive_single_vertex(socket_server_client):
+ result = socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+
+
+def test_should_handle_server_closing_connection_before_response(socket_server_client):
+ with pytest.raises(Exception):
+ socket_server_client.submit(GREMLIN_CLOSE_CONNECTION).all().result()
+
+ # Recovery
+ result = socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+
+
+def test_should_handle_server_closing_connection_after_response(socket_server_client):
+ result = socket_server_client.submit(GREMLIN_VERTEX_THEN_CLOSE).all().result()
+ assert len(result) >= 1
+
+ time.sleep(3)
+
+ # Recovery
+ result = socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+
+
+def test_should_handle_server_error_after_delay(socket_server_client):
+ with pytest.raises(Exception) as exc_info:
+ socket_server_client.submit(GREMLIN_FAIL_AFTER_DELAY).all().result()
+ assert exc_info.value is not None
+
+
+def test_should_handle_partial_content_close(socket_server_client):
+ with pytest.raises(Exception):
+ socket_server_client.submit(GREMLIN_PARTIAL_CONTENT_CLOSE).all().result()
+
+ # Recovery
+ result = socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+
+
+def test_should_handle_malformed_response(socket_server_client):
+ with pytest.raises(Exception):
+ socket_server_client.submit(GREMLIN_MALFORMED_RESPONSE).all().result()
+
+ # Recovery
+ result = socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+
+
+def test_should_handle_empty_response_body(fresh_client):
+ # An empty HTTP response body should surface as an error rather than hang.
+ with pytest.raises(Exception):
+ fresh_client.submit(GREMLIN_EMPTY_BODY).all().result()
+
+ # NOTE: Unlike the Java driver, the Python (aiohttp) driver does not recover
+ # on the same client after an empty response body - the half-closed connection
+ # is not evicted from the pool and a subsequent request fails with
+ # 'Cannot write to closing transport'. This driver gap is flagged in the
+ # cross-GLV error-message audit (tinkerpop-8lw.6) for further consideration.
+
+
+def test_should_handle_slow_response(socket_server_client):
+ result = socket_server_client.submit(GREMLIN_SLOW_RESPONSE).all().result()
+ assert len(result) >= 1
+
+
+def test_should_timeout_when_server_never_responds(fresh_client):
+ with pytest.raises(Exception):
+ fresh_client.submit(GREMLIN_NO_RESPONSE).all().result(timeout=3)
+
+ # Recovery with a new client
+ recovery_client = Client(url, 'g')
+ try:
+ result = recovery_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+ finally:
+ recovery_client.close()
+
+
+@pytest.mark.skip(reason="requires server stop/restart - only testable in Java")
+def test_should_recover_from_temporary_server_downtime():
+ pass
+
+
+def test_should_handle_async_requests_during_connection_close(socket_server_client):
+ future1 = socket_server_client.submit_async(GREMLIN_CLOSE_CONNECTION)
+ future2 = socket_server_client.submit_async(GREMLIN_CLOSE_CONNECTION)
+
+ for future in [future1, future2]:
+ try:
+ future.result().all().result()
+ except Exception:
+ pass
+
+ # Recovery
+ result = socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+ assert len(result) == 1
+
+
+def test_should_handle_concurrent_mixed_requests(socket_server_client):
+ vertex_results = []
+ close_errors = []
+
+ def submit_vertex():
+ return socket_server_client.submit(GREMLIN_SINGLE_VERTEX).all().result()
+
+ def submit_close():
+ return socket_server_client.submit(GREMLIN_CLOSE_CONNECTION).all().result()
+
+ with ThreadPoolExecutor(max_workers=10) as executor:
+ vertex_futures = [executor.submit(submit_vertex) for _ in range(5)]
+ close_futures = [executor.submit(submit_close) for _ in range(5)]
+
+ for f in as_completed(vertex_futures):
+ try:
+ vertex_results.append(f.result())
+ except Exception:
+ pass
+
+ for f in as_completed(close_futures):
+ try:
+ f.result()
+ except Exception:
+ close_errors.append(True)
+
+ assert len(vertex_results) == 5
+ assert len(close_errors) == 5
diff --git a/gremlin-python/src/main/python/tests/integration/driver/test_web_socket_client_behavior.py b/gremlin-python/src/main/python/tests/integration/driver/test_web_socket_client_behavior.py
deleted file mode 100644
index ae19bcc5f7..0000000000
--- a/gremlin-python/src/main/python/tests/integration/driver/test_web_socket_client_behavior.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-__author__ = 'Cole Greer (cole@colegreer.ca)'
-
-
-import re
-import operator
-from functools import reduce
-
-import pytest
-from gremlin_python.driver import useragent
-
-
-# TODO: remove or modify after implementing equivalent support in HTTP server
-# Note: This test demonstrates different behavior in response to a server sending a close frame than the other GLV's.
-# Other GLV's will respond to this by trying to reconnect. This test is also demonstrating incorrect behavior of
-# client.is_closed() as it appears unaware that the event loop is dead.
-# These differences from other GLV's are being tracked in [TINKERPOP-2846]. If this behavior is changed to resemble
-# other GLV's, this test should be updated to show a vertex is being received by the second request.
-@pytest.mark.skip(reason="not implemented in HTTP & need to check on server side")
-def test_does_not_create_new_connection_if_closed_by_server(socket_server_client, socket_server_settings):
- try:
- socket_server_client.submit(
- "1", request_options={'requestId': socket_server_settings["CLOSE_CONNECTION_REQUEST_ID"]}).all().result()
- except RuntimeError as err:
- assert str(err) == "Connection was closed by server."
-
- assert not socket_server_client.is_closed()
-
- try:
- response = socket_server_client.submit(
- "1", request_options={'requestId': socket_server_settings["SINGLE_VERTEX_REQUEST_ID"]}).all().result()
- except RuntimeError as err:
- assert str(err) == "Event loop is closed"
-
- assert not socket_server_client.is_closed()
-
-
-# Tests that client is correctly sending user agent during web socket handshake by having the server return
-# the captured user agent.
-@pytest.mark.skip(reason="not implemented in HTTP & need to check on server side")
-def test_should_include_user_agent_in_handshake_request(socket_server_client, socket_server_settings):
- user_agent_response = socket_server_client.submit(
- "1", request_options={'requestId': socket_server_settings["USER_AGENT_REQUEST_ID"]}).one()[0]
-
- assert user_agent_response == useragent.userAgent
-
-
-# Tests that no user agent (other than the default one provided by aiohttp) is sent to server when that
-# behaviour is disabled.
-@pytest.mark.skip(reason="not implemented in HTTP & need to check on server side")
-def test_should_not_include_user_agent_in_handshake_request_if_disabled(socket_server_client_no_user_agent,
- socket_server_settings):
- user_agent_response = socket_server_client_no_user_agent.submit(
- "1", request_options={'requestId': socket_server_settings["USER_AGENT_REQUEST_ID"]}).one()[0]
-
- # If the gremlin user agent is disabled, the underlying web socket library reverts to sending its default user agent
- # during connection requests.
- assert re.search("^Python/\d+(\.\d+)* aiohttp/\d+(\.\d+)*", user_agent_response)
-
-# Tests that client is correctly sending all overridable per request settings (requestId, batchSize,
-# evaluationTimeout, and userAgent) to the server.
-@pytest.mark.skip(reason="not implemented in HTTP & need to check on server side")
-def test_should_send_per_request_settings_to_server(socket_server_client, socket_server_settings):
-
- result = socket_server_client.submit(
- "1", request_options={
- 'requestId': socket_server_settings["PER_REQUEST_SETTINGS_REQUEST_ID"],
- 'evaluationTimeout': 1234,
- 'batchSize': 12,
- 'userAgent': "helloWorld",
- 'materializeProperties': "tokens"
- }).all().result()
-
- expected_result = "requestId={} evaluationTimeout={}, batchSize={}, userAgent={}, materializeProperties={}".format(
- socket_server_settings["PER_REQUEST_SETTINGS_REQUEST_ID"], 1234, 12, "helloWorld", "tokens"
- )
-
- # Socket Server is sending a simple string response which after being serialized in and out of graphBinary,
- # becomes a list of length 1 strings. This operation folds the list back to a single string for comparison.
- result = reduce(operator.add, result)
-
- assert result == expected_result
(tinkerpop) 01/02: Add HTTP behavioral tests for Java driver
Posted by co...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
Cole-Greer pushed a commit to branch gremlinSocketServer
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit 0fe90f03d3166acba076f36ffa3d23b26bf6bb24
Author: Cole Greer <co...@colegreer.ca>
AuthorDate: Thu May 28 13:16:52 2026 -0700
Add HTTP behavioral tests for Java driver
Replace the old WebSocket behavioral test infrastructure with an HTTP
equivalent. The lightweight test server in gremlin-socket-server dispatches
on the Gremlin query string to simulate adversarial network conditions.
Server changes:
- Remove dead WebSocket artifacts (TestHandlers, test-ws-gremlin.yaml)
- Replace SocketServerSettings with SocketServerConstants (pure constants)
- Rename SimpleSocketServer to SimpleTestServer
- Add TestHttpServerInitializer and TestHttpGremlinHandler
- Scenarios: single vertex, close connection, vertex-then-close,
error after delay, partial content close, malformed response,
no response, slow drip-feed, empty body
Test changes:
- Add ClientBehaviorIntegrateTest in gremlin-driver with 13 tests
- Add test-scoped dependency on gremlin-socket-server in gremlin-driver
---
gremlin-driver/pom.xml | 6 +
.../driver/ClientBehaviorIntegrateTest.java | 369 +++++++++++++++++++++
gremlin-tools/gremlin-socket-server/Dockerfile | 1 -
.../conf/test-ws-gremlin.yaml | 56 ----
...mpleSocketServer.java => SimpleTestServer.java} | 10 +-
.../socket/server/SocketServerConstants.java | 40 +++
.../gremlin/socket/server/SocketServerRunner.java | 20 +-
.../socket/server/SocketServerSettings.java | 93 ------
.../gremlin/socket/server/TestHandlers.java | 48 ---
.../socket/server/TestHttpGremlinHandler.java | 210 ++++++++++++
...rRunner.java => TestHttpServerInitializer.java} | 26 +-
11 files changed, 648 insertions(+), 231 deletions(-)
diff --git a/gremlin-driver/pom.xml b/gremlin-driver/pom.xml
index 53e04d071c..14457c2d17 100644
--- a/gremlin-driver/pom.xml
+++ b/gremlin-driver/pom.xml
@@ -88,6 +88,12 @@ limitations under the License.
<optional>true</optional>
</dependency>
<!-- TEST -->
+ <dependency>
+ <groupId>org.apache.tinkerpop</groupId>
+ <artifactId>gremlin-socket-server</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-test</artifactId>
diff --git a/gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/ClientBehaviorIntegrateTest.java b/gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/ClientBehaviorIntegrateTest.java
new file mode 100644
index 0000000000..4f1d128911
--- /dev/null
+++ b/gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/ClientBehaviorIntegrateTest.java
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.driver;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import nl.altindag.log.LogCaptor;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import org.apache.tinkerpop.gremlin.driver.exception.ResponseException;
+import org.apache.tinkerpop.gremlin.socket.server.SimpleTestServer;
+import org.apache.tinkerpop.gremlin.socket.server.SocketServerConstants;
+import org.apache.tinkerpop.gremlin.socket.server.TestHttpServerInitializer;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.util.ser.GraphBinaryMessageSerializerV4;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.IsInstanceOf.instanceOf;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class ClientBehaviorIntegrateTest {
+
+ private static final int PORT = 45943;
+
+ private static SimpleTestServer server;
+ private static Cluster cluster;
+ private static Client client;
+ private static LogCaptor logCaptor;
+
+ @BeforeClass
+ public static void setUp() throws InterruptedException {
+ server = new SimpleTestServer(PORT);
+ server.start(new TestHttpServerInitializer());
+
+ cluster = buildCluster().create();
+ client = cluster.connect();
+
+ logCaptor = LogCaptor.forClass(ConnectionPool.class);
+ final Logger poolLogger = (Logger) LoggerFactory.getLogger(ConnectionPool.class);
+ poolLogger.setLevel(Level.DEBUG);
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ if (client != null) client.close();
+ if (cluster != null) cluster.close();
+ if (server != null) server.stop();
+ logCaptor.close();
+ }
+
+ private static Cluster.Builder buildCluster() {
+ return Cluster.build("localhost")
+ .validationRequest(SocketServerConstants.GREMLIN_SINGLE_VERTEX)
+ .port(PORT)
+ .serializer(new GraphBinaryMessageSerializerV4());
+ }
+
+ private static void clearLogs() {
+ logCaptor.clearLogs();
+ }
+
+ @Test
+ public void shouldReceiveSingleVertex() throws Exception {
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+ }
+
+ @Test
+ public void shouldHandleServerClosingConnectionBeforeResponse() throws Exception {
+ try {
+ client.submit(SocketServerConstants.GREMLIN_CLOSE_CONNECTION).all().get();
+ fail("Expected ExecutionException");
+ } catch (ExecutionException e) {
+ // ExecutionException -> IllegalStateException or IOException
+ final Throwable cause = e.getCause();
+ assertTrue("Expected IllegalStateException or IOException but got " + cause.getClass().getName(),
+ cause instanceof IllegalStateException || cause instanceof IOException);
+ }
+
+ // driver should recover
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+ }
+
+ @Test
+ public void shouldHandleSuccessiveConnectionClosures() throws Exception {
+ try {
+ client.submit(SocketServerConstants.GREMLIN_CLOSE_CONNECTION).all().get();
+ fail("Expected ExecutionException");
+ } catch (ExecutionException ignored) {
+ }
+
+ try {
+ client.submit(SocketServerConstants.GREMLIN_CLOSE_CONNECTION).all().get();
+ fail("Expected ExecutionException");
+ } catch (ExecutionException ignored) {
+ }
+
+ // driver should recover after multiple failures
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+ }
+
+ @Test
+ public void shouldHandleAsyncRequestsDuringConnectionClose() throws Exception {
+ clearLogs();
+
+ final CompletableFuture<List<Result>> f1 = client.submit(SocketServerConstants.GREMLIN_CLOSE_CONNECTION).all();
+ final CompletableFuture<List<Result>> f2 = client.submit(SocketServerConstants.GREMLIN_CLOSE_CONNECTION).all();
+
+ try {
+ f1.get(5, TimeUnit.SECONDS);
+ } catch (ExecutionException ignored) {
+ }
+
+ try {
+ f2.get(5, TimeUnit.SECONDS);
+ } catch (ExecutionException ignored) {
+ }
+
+ // wait for pool stabilization
+ Thread.sleep(2000);
+
+ // verify the pool considered/created a replacement connection
+ assertTrue("Expected pool to replace or consider new connection",
+ logCaptor.getLogs().stream().anyMatch(msg ->
+ msg.contains("Replace ") || msg.contains("Considering new connection")));
+
+ // verify recovery
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+ }
+
+ @Test
+ public void shouldHandleServerClosingConnectionAfterResponse() throws Exception {
+ clearLogs();
+
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_VERTEX_THEN_CLOSE).all().get();
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+
+ // wait for the delayed close to happen
+ Thread.sleep(3000);
+
+ // connection pool should create a new connection
+ final List<Result> results2 = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results2.size());
+ assertThat(results2.get(0).getObject(), instanceOf(Vertex.class));
+
+ // verify the pool dealt with the dead connection
+ assertTrue("Expected pool to replace or destroy the dead connection",
+ logCaptor.getLogs().stream().anyMatch(msg -> msg.contains("Replace ") || msg.contains("Destroyed ")));
+ }
+
+ @Test
+ public void shouldHandleServerErrorAfterDelay() throws Exception {
+ try {
+ client.submit(SocketServerConstants.GREMLIN_FAIL_AFTER_DELAY).all().get();
+ fail("Expected ExecutionException");
+ } catch (ExecutionException e) {
+ assertThat(e.getCause(), instanceOf(ResponseException.class));
+ final ResponseException re = (ResponseException) e.getCause();
+ assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, re.getResponseStatusCode());
+ assertTrue(re.getMessage().contains("Server error"));
+ }
+
+ // A 500 is a valid HTTP response, connection should still be usable
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ }
+
+ @Test
+ public void shouldHandlePartialContentClose() throws Exception {
+ try {
+ client.submit(SocketServerConstants.GREMLIN_PARTIAL_CONTENT_CLOSE).all().get();
+ fail("Expected ExecutionException");
+ } catch (ExecutionException e) {
+ assertThat(e.getCause(), instanceOf(IllegalStateException.class));
+ assertTrue(e.getCause().getMessage().contains("no longer active"));
+ }
+
+ // driver should recover with a new connection
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ }
+
+ @Test
+ public void shouldHandleMalformedResponse() throws Exception {
+ try {
+ client.submit(SocketServerConstants.GREMLIN_MALFORMED_RESPONSE).all().get();
+ fail("Expected ExecutionException");
+ } catch (ExecutionException ignored) {
+ }
+
+ // connection should still be usable or pool creates new one
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+ }
+
+ @Test
+ public void shouldHandleEmptyResponseBody() throws Exception {
+ try {
+ client.submit(SocketServerConstants.GREMLIN_EMPTY_BODY).all().get(5, TimeUnit.SECONDS);
+ fail("Expected ExecutionException");
+ } catch (ExecutionException e) {
+ // Empty body causes the stream reader to hit EOF immediately
+ assertThat(e.getCause(), instanceOf(RuntimeException.class));
+ assertThat(e.getCause().getCause(), instanceOf(java.io.EOFException.class));
+ assertTrue(e.getCause().getMessage().contains("EOFException"));
+ } catch (TimeoutException e) {
+ fail("Driver hung on empty response body instead of throwing an error");
+ }
+
+ // driver should recover
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ }
+
+ @Test
+ public void shouldHandleSlowResponse() throws Exception {
+ final List<Result> results = client.submit(SocketServerConstants.GREMLIN_SLOW_RESPONSE)
+ .all().get(10, TimeUnit.SECONDS);
+ assertEquals(3, results.size());
+ }
+
+ @Test
+ public void shouldTimeoutWhenServerNeverResponds() throws Exception {
+ final Cluster timeoutCluster = buildCluster()
+ .idleConnectionTimeoutMillis(2000)
+ .create();
+ final Client timeoutClient = timeoutCluster.connect();
+ try {
+ try {
+ timeoutClient.submit(SocketServerConstants.GREMLIN_NO_RESPONSE).all().get(5, TimeUnit.SECONDS);
+ fail("Expected ExecutionException");
+ } catch (ExecutionException e) {
+ assertThat(e.getCause(), instanceOf(RuntimeException.class));
+ assertTrue(e.getCause().getMessage().contains("Idle timeout occurred before response could be received"));
+ }
+
+ // same client should recover - pool replaces the dead connection
+ final List<Result> results = timeoutClient.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get();
+ assertEquals(1, results.size());
+ } finally {
+ timeoutClient.close();
+ timeoutCluster.close();
+ }
+ }
+
+ @Test
+ public void shouldRecoverFromTemporaryServerDowntime() throws Exception {
+ // Use a dedicated cluster with short reconnect interval for this test
+ final Cluster recoveryCluster = buildCluster().reconnectInterval(500).create();
+ final Client recoveryClient = recoveryCluster.connect();
+ try {
+ // First verify the client works
+ final List<Result> before = recoveryClient.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX)
+ .all().get(5, TimeUnit.SECONDS);
+ assertEquals(1, before.size());
+
+ // Stop the server — existing connections become dead
+ server.stopSync();
+ try {
+ // Attempt request with the SAME client — expect failure
+ try {
+ recoveryClient.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get(5, TimeUnit.SECONDS);
+ fail("Should have thrown exception while server is down");
+ } catch (RuntimeException e) {
+ assertThat(e.getCause(), instanceOf(TimeoutException.class));
+ assertTrue(e.getCause().getMessage().contains("Connection refused"));
+ }
+ } finally {
+ // Restart the server
+ server.start(new TestHttpServerInitializer());
+ }
+
+ // Wait for the driver's reconnection logic to detect the server is back
+ Thread.sleep(3000);
+
+ // Verify the SAME client self-heals and can submit successfully again
+ final List<Result> after = recoveryClient.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX)
+ .all().get(30, TimeUnit.SECONDS);
+ assertEquals(1, after.size());
+ } finally {
+ recoveryClient.close();
+ recoveryCluster.close();
+ }
+ }
+ @Test
+ public void shouldHandleConcurrentMixedRequests() throws Exception {
+ final int count = 5;
+ final ExecutorService executor = Executors.newFixedThreadPool(count * 2);
+
+ // Use a fresh cluster with enough pool size
+ final Cluster concurrentCluster = buildCluster().maxConnectionPoolSize(count * 2).create();
+ final Client concurrentClient = concurrentCluster.connect();
+
+ try {
+ // Submit good and bad requests concurrently, tracking them separately
+ final List<Future<List<Result>>> goodFutures = new ArrayList<>();
+ final List<Future<List<Result>>> badFutures = new ArrayList<>();
+
+ for (int i = 0; i < count; i++) {
+ goodFutures.add(executor.submit(() ->
+ concurrentClient.submit(SocketServerConstants.GREMLIN_SINGLE_VERTEX).all().get(10, TimeUnit.SECONDS)));
+ badFutures.add(executor.submit(() ->
+ concurrentClient.submit(SocketServerConstants.GREMLIN_CLOSE_CONNECTION).all().get(10, TimeUnit.SECONDS)));
+ }
+
+ // All good requests should succeed
+ for (final Future<List<Result>> f : goodFutures) {
+ final List<Result> results = f.get(15, TimeUnit.SECONDS);
+ assertEquals(1, results.size());
+ assertThat(results.get(0).getObject(), instanceOf(Vertex.class));
+ }
+
+ // All bad requests should fail
+ for (final Future<List<Result>> f : badFutures) {
+ try {
+ f.get(15, TimeUnit.SECONDS);
+ fail("Expected exception for close-connection request");
+ } catch (ExecutionException expected) {
+ // Expected — server closed the connection
+ }
+ }
+ } finally {
+ concurrentClient.close();
+ concurrentCluster.close();
+ executor.shutdown();
+ }
+ }
+}
diff --git a/gremlin-tools/gremlin-socket-server/Dockerfile b/gremlin-tools/gremlin-socket-server/Dockerfile
index 9eef686765..3010f33cd6 100644
--- a/gremlin-tools/gremlin-socket-server/Dockerfile
+++ b/gremlin-tools/gremlin-socket-server/Dockerfile
@@ -28,7 +28,6 @@ RUN apk add --no-cache --update \
COPY ${SOCKET_SERVER_DIR}/gremlin-socket-server-${SOCKET_SERVER_VERSION}.jar /opt/gremlin-socket-server/gremlin-socket-server.jar
COPY ${SOCKET_SERVER_DIR}/libs/ /opt/gremlin-socket-server/libs/
-COPY ${SOCKET_SERVER_DIR}/../conf/ opt/gremlin-socket-server/conf/
WORKDIR /opt/gremlin-socket-server
diff --git a/gremlin-tools/gremlin-socket-server/conf/test-ws-gremlin.yaml b/gremlin-tools/gremlin-socket-server/conf/test-ws-gremlin.yaml
deleted file mode 100644
index a358d4ce12..0000000000
--- a/gremlin-tools/gremlin-socket-server/conf/test-ws-gremlin.yaml
+++ /dev/null
@@ -1,56 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# This file is to be used to configure an instance of Gremlin-Socket-Server as
-# well as any driver trying to run tests against it.
-# Gremlin-Socket-Server listens for requests with the specific request ids below
-# and triggers response behavior accordingly. Driver's should use the request id
-# corresponding with the desired behavior whenever sending a request to
-# gremlin-socket-server.
-
-# Port exposed by gremlin-socket-server
-PORT: 45943
-
-# Configures which serializer will be used. Ex: GraphBinaryV1 or GraphSONV2
-SERIALIZER: GraphBinaryV1
-
-# If a request with this ID comes to the server, the server responds back with a single
-# vertex picked from Modern graph.
-SINGLE_VERTEX_REQUEST_ID: 6457272a-4018-4538-b9ae-08dd5ddc0aa1
-
-# If a request with this ID comes to the server, the server responds back with a single
-# vertex picked from Modern graph. After a 2 second delay, server sends a Close WebSocket
-# frame on the same connection.
-SINGLE_VERTEX_DELAYED_CLOSE_CONNECTION_REQUEST_ID: 3cb39c94-9454-4398-8430-03485d08bdae
-
-# Server waits for 1 second, then responds with a 500 error status code
-FAILED_AFTER_DELAY_REQUEST_ID: edf79c8b-1d32-4102-a5d2-a5feeca40864
-
-# Server waits for 1 second then responds with a close web socket frame
-CLOSE_CONNECTION_REQUEST_ID: 0150143b-00f9-48a7-a268-28142d902e18
-
-# Same as CLOSE_CONNECTION_REQUEST_ID
-CLOSE_CONNECTION_REQUEST_ID_2: 3c4cf18a-c7f2-4dad-b9bf-5c701eb33000
-
-# If a request with this ID comes to the server, the server responds with the user agent (if any)
-# that was captured during the web socket handshake.
-USER_AGENT_REQUEST_ID: 20ad7bfb-4abf-d7f4-f9d3-9f1d55bee4ad
-
-# If a request with this ID comes to the server, the server responds with a string containing all overridden
-# per request settings from the request message. String will be of the form
-# "requestId=19436d9e-f8fc-4b67-8a76-deec60918424 evaluationTimeout=1234, batchSize=12, userAgent=testUserAgent"
-PER_REQUEST_SETTINGS_REQUEST_ID: 19436d9e-f8fc-4b67-8a76-deec60918424
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SimpleSocketServer.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SimpleTestServer.java
similarity index 90%
rename from gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SimpleSocketServer.java
rename to gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SimpleTestServer.java
index c6870794b5..f5e939c6b7 100644
--- a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SimpleSocketServer.java
+++ b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SimpleTestServer.java
@@ -32,13 +32,13 @@ import io.netty.handler.logging.LoggingHandler;
* A Simple Netty Server intended to be used as a base for gremlin test servers.
* Server behavior is defined by the {@link ChannelInitializer} passed in the start method.
*/
-public class SimpleSocketServer {
- private final SocketServerSettings settings;
+public class SimpleTestServer {
+ private final int port;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
- public SimpleSocketServer(final SocketServerSettings settings) {
- this.settings = settings;
+ public SimpleTestServer(final int port) {
+ this.port = port;
}
public Channel start(final ChannelInitializer<SocketChannel> channelInitializer) throws InterruptedException {
@@ -49,7 +49,7 @@ public class SimpleSocketServer {
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(channelInitializer);
- return b.bind(settings.PORT).sync().channel();
+ return b.bind(port).sync().channel();
}
public void stop() {
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerConstants.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerConstants.java
new file mode 100644
index 0000000000..7428911020
--- /dev/null
+++ b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerConstants.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.socket.server;
+
+/**
+ * Constants for the test HTTP socket server. Gremlin string constants coordinate
+ * response behavior between test clients and the server.
+ */
+public final class SocketServerConstants {
+
+ public static final int PORT = 45943;
+
+ public static final String GREMLIN_SINGLE_VERTEX = "server_single_vertex";
+ public static final String GREMLIN_CLOSE_CONNECTION = "server_close_connection";
+ public static final String GREMLIN_VERTEX_THEN_CLOSE = "server_vertex_then_close";
+ public static final String GREMLIN_FAIL_AFTER_DELAY = "server_fail_after_delay";
+ public static final String GREMLIN_PARTIAL_CONTENT_CLOSE = "server_partial_content_close";
+ public static final String GREMLIN_SLOW_RESPONSE = "server_slow_response";
+ public static final String GREMLIN_MALFORMED_RESPONSE = "server_malformed_response";
+ public static final String GREMLIN_NO_RESPONSE = "server_no_response";
+ public static final String GREMLIN_EMPTY_BODY = "server_empty_body";
+
+ private SocketServerConstants() {}
+}
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java
index 863c738bf2..5f6d958cc0 100644
--- a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java
+++ b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java
@@ -20,22 +20,16 @@ package org.apache.tinkerpop.gremlin.socket.server;
import io.netty.channel.Channel;
-import java.io.IOException;
-import java.nio.file.FileSystems;
-
/**
- * A simple main class to create and run a SimpleSocketServer
+ * A simple main class to create and run a SimpleTestServer
*/
public class SocketServerRunner {
- public static void main(final String[] args) throws InterruptedException, IOException {
- final SocketServerSettings settings = SocketServerSettings.read(FileSystems.getDefault().getPath("conf", "test-ws-gremlin.yaml"));
- final SimpleSocketServer server = new SimpleSocketServer(settings);
- // TODO: add HTTP version of socketserver
-// final Channel channel = server.start(new TestWSGremlinInitializer(settings));
-// while(channel.isOpen()) {
-// Thread.sleep(1000);
-// }
+ public static void main(final String[] args) throws InterruptedException {
+ final SimpleTestServer server = new SimpleTestServer(SocketServerConstants.PORT);
+ final Channel channel = server.start(new TestHttpServerInitializer());
+ while (channel.isOpen()) {
+ Thread.sleep(1000);
+ }
}
-
}
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerSettings.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerSettings.java
deleted file mode 100644
index bc35551333..0000000000
--- a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerSettings.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tinkerpop.gremlin.socket.server;
-
-import org.yaml.snakeyaml.LoaderOptions;
-import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.constructor.Constructor;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Objects;
-import java.util.UUID;
-
-/**
- * Encapsulates all constants that are needed by SimpleSocketServer. UUID request id constants are used
- * to coordinate custom response behavior between a test client and the server.
- */
-public class SocketServerSettings {
- public int PORT = 0;
-
- /**
- * Configures which serializer will be used. Ex: "GraphBinaryV1" or "GraphSONV2"
- */
- public String SERIALIZER = "GraphBinaryV1";
- /**
- * If a request with this ID comes to the server, the server responds back with a single vertex picked from Modern
- * graph.
- */
- public UUID SINGLE_VERTEX_REQUEST_ID = null;
-
- /**
- * If a request with this ID comes to the server, the server responds back with a single vertex picked from Modern
- * graph. After a 2 second delay, server sends a Close WebSocket frame on the same connection.
- */
- public UUID SINGLE_VERTEX_DELAYED_CLOSE_CONNECTION_REQUEST_ID = null;
-
- /**
- * Server waits for 1 second, then responds with a 500 error status code
- */
- public UUID FAILED_AFTER_DELAY_REQUEST_ID = null;
-
- /**
- * Server waits for 1 second then responds with a close web socket frame
- */
- public UUID CLOSE_CONNECTION_REQUEST_ID = null;
-
- /**
- * Same as CLOSE_CONNECTION_REQUEST_ID
- */
- public UUID CLOSE_CONNECTION_REQUEST_ID_2 = null;
-
- /**
- * If a request with this ID comes to the server, the server responds with the user agent (if any) that was captured
- * during the web socket handshake.
- */
- public UUID USER_AGENT_REQUEST_ID = null;
-
- /**
- * If a request with this ID comes to the server, the server responds with a string containing all overridden
- * per request settings from the request message. String will be of the form
- * "requestId=19436d9e-f8fc-4b67-8a76-deec60918424 evaluationTimeout=1234, batchSize=12, userAgent=testUserAgent"
- */
- public UUID PER_REQUEST_SETTINGS_REQUEST_ID = null;
-
- public static SocketServerSettings read(final Path confFilePath) throws IOException {
- return read(Files.newInputStream(confFilePath));
- }
-
- public static SocketServerSettings read(final InputStream confInputStream) {
- Objects.requireNonNull(confInputStream);
- final LoaderOptions options = new LoaderOptions();
- final Yaml yaml = new Yaml(new Constructor(SocketServerSettings.class, options));
- return yaml.load(confInputStream);
- }
-}
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHandlers.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHandlers.java
deleted file mode 100644
index ed6cfda233..0000000000
--- a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHandlers.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tinkerpop.gremlin.socket.server;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.handler.codec.http.HttpRequest;
-import io.netty.util.ReferenceCountUtil;
-
-/**
- * Class that holds the handlers that can used by the initializers in TestChannelizers.
- */
-public class TestHandlers {
-
- /**
- * Handler that will drop requests to the WebSocket path.
- */
- public static class NoOpWebSocketServerHandler extends ChannelInboundHandlerAdapter {
- private String websocketPath;
-
- public NoOpWebSocketServerHandler(String websocketPath) {
- this.websocketPath = websocketPath;
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- if ((msg instanceof HttpRequest) && ((HttpRequest) msg).uri().endsWith(websocketPath)) {
- ReferenceCountUtil.release(msg);
- }
- }
- }
-}
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpGremlinHandler.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpGremlinHandler.java
new file mode 100644
index 0000000000..3ea75f2f7d
--- /dev/null
+++ b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpGremlinHandler.java
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.socket.server;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.handler.codec.http.DefaultHttpContent;
+import io.netty.handler.codec.http.DefaultHttpResponse;
+import io.netty.handler.codec.http.DefaultLastHttpContent;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpHeaderValues;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory;
+import org.apache.tinkerpop.gremlin.util.message.RequestMessage;
+import org.apache.tinkerpop.gremlin.util.message.ResponseMessage;
+import org.apache.tinkerpop.gremlin.util.ser.GraphBinaryMessageSerializerV4;
+import org.apache.tinkerpop.gremlin.util.ser.SerTokens;
+import org.apache.tinkerpop.gremlin.util.ser.SerializationException;
+
+import java.util.Collections;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
+/**
+ * Handles HTTP Gremlin requests for the test socket server, responding with canned results
+ * based on the gremlin string in the request.
+ */
+public class TestHttpGremlinHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
+
+ private final GraphBinaryMessageSerializerV4 serializer = new GraphBinaryMessageSerializerV4();
+ private static final Graph graph = TinkerFactory.createModern();
+ private static final Vertex singleVertex = graph.traversal().V().hasLabel("person").next();
+
+ @Override
+ protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {
+ final RequestMessage msg = serializer.deserializeBinaryRequest(request.content());
+ final String gremlin = msg.getGremlin();
+
+ switch (gremlin) {
+ case SocketServerConstants.GREMLIN_SINGLE_VERTEX:
+ writeVertexResponse(ctx);
+ break;
+ case SocketServerConstants.GREMLIN_CLOSE_CONNECTION:
+ ctx.executor().schedule(() -> ctx.close(), 1, TimeUnit.SECONDS);
+ break;
+ case SocketServerConstants.GREMLIN_VERTEX_THEN_CLOSE:
+ writeVertexResponse(ctx);
+ ctx.executor().schedule(() -> ctx.close(), 2, TimeUnit.SECONDS);
+ break;
+ case SocketServerConstants.GREMLIN_FAIL_AFTER_DELAY:
+ ctx.executor().schedule(() -> {
+ try {
+ writeErrorResponse(ctx, INTERNAL_SERVER_ERROR, "Server error");
+ } catch (SerializationException e) {
+ ctx.close();
+ }
+ }, 1, TimeUnit.SECONDS);
+ break;
+ case SocketServerConstants.GREMLIN_PARTIAL_CONTENT_CLOSE:
+ writePartialContentClose(ctx);
+ break;
+ case SocketServerConstants.GREMLIN_MALFORMED_RESPONSE:
+ writeMalformedResponse(ctx);
+ break;
+ case SocketServerConstants.GREMLIN_NO_RESPONSE:
+ // Do nothing — let the client timeout.
+ break;
+ case SocketServerConstants.GREMLIN_SLOW_RESPONSE:
+ writeSlowResponse(ctx);
+ break;
+ case SocketServerConstants.GREMLIN_EMPTY_BODY:
+ writeEmptyBody(ctx);
+ break;
+ default:
+ writeErrorResponse(ctx, BAD_REQUEST, "Unknown test scenario");
+ break;
+ }
+ }
+
+ private void writeVertexResponse(final ChannelHandlerContext ctx) throws SerializationException {
+ final ResponseMessage responseMessage = ResponseMessage.build()
+ .result(Collections.singletonList(singleVertex))
+ .code(OK)
+ .create();
+ final ByteBuf serialized = serializer.serializeResponseAsBinary(responseMessage, ctx.alloc());
+
+ final DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, SerTokens.MIME_GRAPHBINARY_V4);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ ctx.write(response);
+ ctx.write(new DefaultHttpContent(serialized));
+ ctx.writeAndFlush(new DefaultLastHttpContent());
+ }
+
+ private void writeErrorResponse(final ChannelHandlerContext ctx, final HttpResponseStatus status,
+ final String message) throws SerializationException {
+ final ResponseMessage responseMessage = ResponseMessage.build()
+ .result(Collections.emptyList())
+ .code(status)
+ .statusMessage(message)
+ .create();
+ final ByteBuf serialized = serializer.serializeResponseAsBinary(responseMessage, ctx.alloc());
+
+ final DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, SerTokens.MIME_GRAPHBINARY_V4);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ ctx.write(response);
+ ctx.write(new DefaultHttpContent(serialized));
+ ctx.writeAndFlush(new DefaultLastHttpContent());
+ }
+
+ private void writePartialContentClose(final ChannelHandlerContext ctx) throws SerializationException {
+ final ResponseMessage responseMessage = ResponseMessage.build()
+ .result(Collections.singletonList(singleVertex))
+ .create();
+
+ final DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, SerTokens.MIME_GRAPHBINARY_V4);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ ctx.write(response);
+ ctx.writeAndFlush(new DefaultHttpContent(serializer.writeHeader(responseMessage, ctx.alloc())));
+ ctx.close();
+ }
+
+ private void writeMalformedResponse(final ChannelHandlerContext ctx) {
+ final DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, SerTokens.MIME_GRAPHBINARY_V4);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ ctx.write(response);
+
+ final byte[] garbage = new byte[64];
+ new Random().nextBytes(garbage);
+ ctx.write(new DefaultHttpContent(ctx.alloc().buffer(64).writeBytes(garbage)));
+ ctx.writeAndFlush(new DefaultLastHttpContent());
+ }
+
+ private void writeSlowResponse(final ChannelHandlerContext ctx) {
+ final DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, SerTokens.MIME_GRAPHBINARY_V4);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ ctx.writeAndFlush(response);
+
+ final ResponseMessage headerMsg = ResponseMessage.build()
+ .result(Collections.singletonList(singleVertex))
+ .create();
+
+ ctx.executor().schedule(() -> {
+ try {
+ ctx.writeAndFlush(new DefaultHttpContent(serializer.writeHeader(headerMsg, ctx.alloc())));
+ } catch (SerializationException e) {
+ ctx.close();
+ }
+ }, 500, TimeUnit.MILLISECONDS);
+
+ ctx.executor().schedule(() -> {
+ try {
+ ctx.writeAndFlush(new DefaultHttpContent(
+ serializer.writeChunk(Collections.singletonList(singleVertex), ctx.alloc())));
+ } catch (SerializationException e) {
+ ctx.close();
+ }
+ }, 1000, TimeUnit.MILLISECONDS);
+
+ ctx.executor().schedule(() -> {
+ try {
+ final ResponseMessage footerMsg = ResponseMessage.build()
+ .result(Collections.singletonList(singleVertex))
+ .code(OK)
+ .create();
+ ctx.write(new DefaultHttpContent(serializer.writeFooter(footerMsg, ctx.alloc())));
+ ctx.writeAndFlush(new DefaultLastHttpContent());
+ } catch (SerializationException e) {
+ ctx.close();
+ }
+ }, 1500, TimeUnit.MILLISECONDS);
+ }
+
+ private void writeEmptyBody(final ChannelHandlerContext ctx) {
+ final DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, SerTokens.MIME_GRAPHBINARY_V4);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ ctx.write(response);
+ ctx.writeAndFlush(new DefaultLastHttpContent());
+ }
+}
diff --git a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpServerInitializer.java
similarity index 54%
copy from gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java
copy to gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpServerInitializer.java
index 863c738bf2..249e19a53a 100644
--- a/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerRunner.java
+++ b/gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpServerInitializer.java
@@ -18,24 +18,20 @@
*/
package org.apache.tinkerpop.gremlin.socket.server;
-import io.netty.channel.Channel;
-
-import java.io.IOException;
-import java.nio.file.FileSystems;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.codec.http.HttpObjectAggregator;
+import io.netty.handler.codec.http.HttpServerCodec;
/**
- * A simple main class to create and run a SimpleSocketServer
+ * Initializes the Netty pipeline for the test HTTP Gremlin server.
*/
-public class SocketServerRunner {
+public class TestHttpServerInitializer extends ChannelInitializer<SocketChannel> {
- public static void main(final String[] args) throws InterruptedException, IOException {
- final SocketServerSettings settings = SocketServerSettings.read(FileSystems.getDefault().getPath("conf", "test-ws-gremlin.yaml"));
- final SimpleSocketServer server = new SimpleSocketServer(settings);
- // TODO: add HTTP version of socketserver
-// final Channel channel = server.start(new TestWSGremlinInitializer(settings));
-// while(channel.isOpen()) {
-// Thread.sleep(1000);
-// }
+ @Override
+ protected void initChannel(final SocketChannel ch) {
+ ch.pipeline().addLast(new HttpServerCodec());
+ ch.pipeline().addLast(new HttpObjectAggregator(65536));
+ ch.pipeline().addLast(new TestHttpGremlinHandler());
}
-
}