Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/main/java/io/appium/java_client/AppiumClientConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,10 @@ public Duration wsTimeout() {
}

/**
* Sets the web socket timeout.
* Sets the WebSocket handshake timeout. Zero or negative values cause
* a fallback to {@link #readTimeout()}.
*
* @param timeout the maximum time to wait for a web socket message
* @param timeout the maximum time to wait for a WebSocket handshake to complete
* @return A new instance of AppiumClientConfig
*/
public AppiumClientConfig wsTimeout(Duration timeout) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public interface ClientConfig {
Duration readTimeout();

/**
* The maximum time to wait for a WebSocket connection to be established.
* The maximum time to wait for a WebSocket handshake to complete.
* Zero or negative values cause a fallback to {@link #readTimeout()}.
*
* @return the WebSocket timeout
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,18 @@ public class JdkHttpClient implements HttpClient {
private final ExecutorService executorService;
private final Duration readTimeout;
private final Duration connectTimeout;
private final Duration wsTimeout;
private java.net.http.HttpClient client;

JdkHttpClient(ClientConfig config) {
Objects.requireNonNull(config, "Client config must be set");
this.messages = new JdkHttpMessages(config);
this.readTimeout = config.readTimeout();
this.connectTimeout = config.connectionTimeout();
Duration configuredWsTimeout = config.wsTimeout();
this.wsTimeout = configuredWsTimeout != null && configuredWsTimeout.compareTo(Duration.ZERO) > 0
? configuredWsTimeout
: this.readTimeout;
this.handler = config.filter().andFinally(this::execute0);

String poolName = "JdkHttpClient-" + POOL_COUNTER.getAndIncrement();
Expand Down Expand Up @@ -154,12 +159,11 @@ public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {
request.getHeaderNames().forEach(name -> builder.header(name, request.getHeader(name)));
CompletableFuture<Integer> closed = new CompletableFuture<>();
CompletableFuture<java.net.http.WebSocket> socketFuture = builder
.connectTimeout(connectTimeout)
.buildAsync(uri, new JdkListener(listener, closed));

java.net.http.WebSocket underlyingSocket;
try {
underlyingSocket = socketFuture.get(readTimeout.toMillis(), TimeUnit.MILLISECONDS);
underlyingSocket = socketFuture.get(wsTimeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (CancellationException e) {
throw new ConnectionFailedException("JdkWebSocket initial request canceled", e);
} catch (ExecutionException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.openqa.selenium.Credentials;

import javax.net.ssl.SSLContext;
Expand All @@ -48,6 +51,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
Expand Down Expand Up @@ -133,25 +137,34 @@ private static String readTextFrame(DataInputStream in) throws IOException {
}

private ClientConfig config() {
return config(Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5));
}

private ClientConfig config(Duration wsTimeout, Duration readTimeout, Duration connectionTimeout) {
return config(URI.create("http://127.0.0.1:" + serverSocket.getLocalPort()),
wsTimeout, readTimeout, connectionTimeout);
}

private ClientConfig config(URI uri, Duration wsTimeout, Duration readTimeout, Duration connectionTimeout) {
return new ClientConfig() {
@Override
public URI baseUri() {
return URI.create("http://127.0.0.1:" + serverSocket.getLocalPort());
return uri;
}

@Override
public Duration connectionTimeout() {
return Duration.ofSeconds(5);
return connectionTimeout;
}

@Override
public Duration readTimeout() {
return Duration.ofSeconds(5);
return readTimeout;
}

@Override
public Duration wsTimeout() {
return Duration.ofSeconds(5);
return wsTimeout;
}

@Override
Expand Down Expand Up @@ -221,4 +234,55 @@ void failsIfTheServerDoesNotAcceptTheConnection() throws IOException {
() -> client.openSocket(new HttpRequest(HttpMethod.GET, "http://127.0.0.1:" + port + "/ws"),
new WebSocket.Listener() { }));
}

static Stream<Arguments> handshakeTimeoutCases() {
return Stream.of(
Arguments.of("positive wsTimeout",
Duration.ofMillis(200), Duration.ofMinutes(5)),
Arguments.of("zero wsTimeout falls back to readTimeout",
Duration.ZERO, Duration.ofMillis(200)),
Arguments.of("negative wsTimeout falls back to readTimeout",
Duration.ofMillis(-100), Duration.ofMillis(200))
);
}

@ParameterizedTest(name = "{0}")
@MethodSource("handshakeTimeoutCases")
void timesOutWhenHandshakeDoesNotComplete(String description, Duration wsTimeout,
Duration readTimeout) throws Exception {
try (ServerSocket stallServer = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
Thread thread = new Thread(() -> {
try (Socket ignored = stallServer.accept()) {
Thread.sleep(10_000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (IOException ignored) {
// Closed when stallServer closes
}
});
thread.setDaemon(true);
thread.start();

try {
client = new JdkHttpClient(config(
URI.create("http://127.0.0.1:" + stallServer.getLocalPort()),
wsTimeout, readTimeout, Duration.ofSeconds(10)));

long startNanos = System.nanoTime();
ConnectionFailedException ex = assertThrows(ConnectionFailedException.class,
() -> client.openSocket(
new HttpRequest(HttpMethod.GET, "/ws"), new WebSocket.Listener() { }));
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);

assertTrue(ex.getMessage().contains("initial request timeout"),
"Expected timeout message, got: " + ex.getMessage());
assertTrue(elapsedMillis >= 150,
"Should wait at least 150ms, took " + elapsedMillis + "ms");
assertTrue(elapsedMillis < 3000,
"Should time out near the effective timeout, took " + elapsedMillis + "ms");
} finally {
thread.interrupt();
}
}
}
}