fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams (#5294)

* fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams

docker-java's UnixSocket reads through a blocking channel stream that
ignores SO_TIMEOUT, so on the default unix:// Docker host no call ever
timed out: a 2-second response timeout let a container wait run 153
seconds, and a hung daemon blocked its caller forever. It is also why
httpclient5's stale-connection check, a read with a 1 ms timeout, cannot be
enabled there.

FlociDockerHttpClient now connects to a unix:// host through
UnixDomainSocket, which keeps the channel non-blocking and waits on a
selector, so a read with a timeout fails with SocketTimeoutException. Making
the timeout real would cut off streams that are silent while healthy, so
requests that hold a stream open (container wait, exec and attach output,
followed logs, streamed stats, events, image pulls and builds) get no
response timeout on any host, which also keeps a TCP host's container wait
from dying at five minutes. Every other call keeps the 5-minute timeout.

* fix(core): keep the Unix socket's failures IOExceptions on close and interrupt

Closing the socket while another thread waited in a read or write could
end that wait with the selector's unchecked ClosedSelectorException,
since close() may shut the selector between select() and
selectedKeys(); callers expecting an IOException did not handle it. It
is now a SocketException. A thread reading a silent stream with no
timeout spun once interrupted, because select() returns at once while
the interrupt flag is set; it now closes the socket and throws
ClosedByInterruptException, as the blocking channel it replaced did.

The tests wait with a timed get that expects a TimeoutException rather
than a fixed sleep, so an early return fails at once, and cover a close
during a blocked read and an interrupted read.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 07:27:04 -04:00
1 parent c09c7ae62b
commit ddc47a465d
5 files changed
+596 -14

No files matched your search

+2
View File
@@ -82,6 +82,8 @@ floci:
Environment variable: `FLOCI_DOCKER_CONNECTION_REQUEST_TIMEOUT_SECONDS`
A Docker call that gets no response within 5 minutes fails, on Unix-socket and TCP hosts alike. Requests that follow a container for as long as it runs (container waits, exec and attach output, followed logs, streamed stats, daemon events, image pulls and builds) have no such limit, since they can stay silent while healthy.
## Private Registry Authentication
Any service that pulls a container image from a private registry (Lambda image functions, custom OpenSearch images, private Postgres images, etc.) needs Docker credentials. Two approaches are supported and can be combined.
@@ -10,7 +10,6 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import com.github.dockerjava.transport.NamedPipeSocket;
import com.github.dockerjava.transport.SSLConfig;
import com.github.dockerjava.transport.UnixSocket;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.config.ConnectionConfig;
@@ -59,19 +58,23 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Floci's own Docker HTTP transport over httpclient5: the same transport docker-java's
* Floci's own Docker HTTP transport over httpclient5: the transport docker-java's
* {@code ApacheDockerHttpClient} builds, owned here so Floci can set what that builder does not
* expose (idle-connection validation and eviction, the connection-lease timeout). It currently
* applies exactly docker-java's settings: unix, npipe and tcp hosts, TLS from the SSL config, a pool
* of {@code maxConnections} for one route, no socket read timeout on the pool ({@code SO_TIMEOUT} 0),
* the request's response timeout, no stale-connection validation, and hijacked exec/attach upgrades
* through {@link HijackingHttpRequestExecutor}.
* expose (idle-connection validation and eviction, the connection-lease timeout). It applies
* docker-java's settings (npipe and tcp hosts, TLS from the SSL config, a pool of
* {@code maxConnections} for one route, no socket read timeout on the pool, no stale-connection
* validation, hijacked exec/attach upgrades through {@link HijackingHttpRequestExecutor}) with two
* differences: a {@code unix://} host connects through {@link UnixDomainSocket}, which honours read
* timeouts where docker-java's socket ignored them, and requests that hold a stream open get no
* response timeout ({@link #isLongLivedStream}), while every other call keeps it.
*/
public final class FlociDockerHttpClient implements DockerHttpClient {
private final CloseableHttpClient httpClient;
private final HttpHost host;
private final String pathPrefix;
/** The same settings with no response timeout, for requests that hold a stream open (see isLongLivedStream). */
private final RequestConfig streamRequestConfig;
private FlociDockerHttpClient(URI dockerHost, SSLConfig sslConfig, int maxConnections,
Duration connectionTimeout, Duration responseTimeout,
@@ -110,15 +113,17 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
? Timeout.of(connectionTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
.build());
RequestConfig requestConfig = RequestConfig.custom()
.setResponseTimeout(responseTimeout != null
? Timeout.of(responseTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
.setConnectionRequestTimeout(connectionRequestTimeout != null
? Timeout.of(connectionRequestTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
.build();
streamRequestConfig = RequestConfig.copy(requestConfig).setResponseTimeout(Timeout.DISABLED).build();
httpClient = HttpClients.custom()
.setRequestExecutor(new HijackingHttpRequestExecutor(null))
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(RequestConfig.custom()
.setResponseTimeout(responseTimeout != null
? Timeout.of(responseTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
.setConnectionRequestTimeout(connectionRequestTimeout != null
? Timeout.of(connectionRequestTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
.build())
.setDefaultRequestConfig(requestConfig)
.disableConnectionState()
.build();
}
@@ -140,7 +145,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
return new DefaultHttpClientConnectionOperator(
socksProxy -> {
if ("unix".equalsIgnoreCase(scheme)) {
return UnixSocket.get(path);
return UnixDomainSocket.connect(path);
}
if ("npipe".equalsIgnoreCase(scheme)) {
return new NamedPipeSocket(path);
@@ -169,6 +174,10 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
httpRequest.setEntity(new InputStreamEntity(request.body(), null));
}
if (isLongLivedStream(request)) {
httpRequest.setConfig(streamRequestConfig);
}
if (request.hijackedInput() != null) {
context.setAttribute(HijackingHttpRequestExecutor.HIJACKED_INPUT_ATTRIBUTE, request.hijackedInput());
httpRequest.setHeader("Upgrade", "tcp");
@@ -188,6 +197,43 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
httpClient.close();
}
/**
* Requests whose response is a stream that stays open, and may stay silent, for as long as what it
* follows: a container wait, exec and attach output, followed logs, streamed stats, daemon events,
* and the progress of an image pull or build. The response timeout bounds how long a silent
* daemon is waited for, so applied to these it would cut off a quiet but healthy stream; they get
* none. Every other call keeps the response timeout.
*/
static boolean isLongLivedStream(Request request) {
if (request.hijackedInput() != null) {
return true;
}
String path = request.path();
int queryStart = path.indexOf('?');
String route = queryStart < 0 ? path : path.substring(0, queryStart);
String query = queryStart < 0 ? "" : path.substring(queryStart + 1);
return switch (request.method()) {
case "POST" -> route.endsWith("/wait") || route.endsWith("/attach") || route.endsWith("/build")
|| route.endsWith("/images/create")
|| (route.contains("/exec/") && route.endsWith("/start"));
case "GET" -> route.endsWith("/events")
|| (route.endsWith("/logs") && queryFlag(query, "follow", false))
|| (route.endsWith("/stats") && queryFlag(query, "stream", true));
default -> false;
};
}
/** A boolean query parameter as Docker reads it ({@code 1} or {@code true}), or its default when absent. */
private static boolean queryFlag(String query, String name, boolean defaultValue) {
for (String param : query.split("&")) {
if (param.startsWith(name + "=")) {
String value = param.substring(name.length() + 1);
return "1".equals(value) || "true".equalsIgnoreCase(value);
}
}
return defaultValue;
}
/** Builds a client; mirrors docker-java's {@code ApacheDockerHttpClient.Builder}. */
public static final class Builder {
@@ -0,0 +1,289 @@
package io.github.hectorvent.floci.core.common.docker;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;
/**
* A {@link Socket} over a Unix domain socket that honours {@link #setSoTimeout(int)}.
*
* <p>docker-java's {@code UnixSocket} reads through a blocking channel stream, which ignores the read
* timeout, so on a {@code unix://} Docker host no call ever timed out and httpclient5's stale-connection
* check (a read with a 1 ms timeout) would block forever. This socket keeps the channel non-blocking and
* waits on a {@link Selector}: a read with a timeout fails with {@link SocketTimeoutException} once the
* timeout passes without data, and a timeout of zero waits indefinitely, as {@code SO_TIMEOUT} does.
* Reads and writes have their own selector and lock, so a hijacked exec can write stdin on one thread
* while another reads its output.
*
* <p>Failures keep the blocking channel's shape, so callers that expect an {@link IOException} still get
* one: closing the socket while another thread waits in a read or write ends that wait with a
* {@link SocketException} rather than the selector's unchecked {@link ClosedSelectorException}, and an
* interrupted thread closes the socket and fails with {@link ClosedByInterruptException} instead of
* spinning, since a selector returns at once while the interrupt flag is set.
*/
final class UnixDomainSocket extends Socket {
private final SocketChannel channel;
private final SocketAddress address;
private final Selector readSelector;
private final Selector writeSelector;
private final Object readLock = new Object();
private final Object writeLock = new Object();
private final InputStream input = new ChannelInputStream();
private final OutputStream output = new ChannelOutputStream();
private volatile int soTimeoutMillis;
private volatile boolean closed;
private volatile boolean inputShutdown;
private volatile boolean outputShutdown;
private UnixDomainSocket(SocketChannel channel, SocketAddress address) throws IOException {
this.channel = channel;
this.address = address;
this.readSelector = Selector.open();
this.writeSelector = Selector.open();
channel.register(readSelector, SelectionKey.OP_READ);
channel.register(writeSelector, SelectionKey.OP_WRITE);
}
/** Connects to the Unix domain socket at {@code path}. */
static UnixDomainSocket connect(String path) throws IOException {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(path);
SocketChannel channel = SocketChannel.open(address);
try {
channel.configureBlocking(false);
return new UnixDomainSocket(channel, address);
} catch (IOException | RuntimeException e) {
channel.close();
throw e;
}
}
@Override
public void connect(SocketAddress endpoint) {
// Already connected by connect(String): httpclient5 calls this on the socket its factory returned.
}
@Override
public void connect(SocketAddress endpoint, int timeout) {
// Already connected by connect(String).
}
@Override
public InputStream getInputStream() throws IOException {
ensureOpen();
if (inputShutdown) {
throw new SocketException("Socket input is shutdown");
}
return input;
}
@Override
public OutputStream getOutputStream() throws IOException {
ensureOpen();
if (outputShutdown) {
throw new SocketException("Socket output is shutdown");
}
return output;
}
@Override
public void setSoTimeout(int timeout) throws SocketException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout can't be negative");
}
soTimeoutMillis = timeout;
}
@Override
public int getSoTimeout() {
return soTimeoutMillis;
}
@Override
public void shutdownInput() throws IOException {
ensureOpen();
channel.shutdownInput();
inputShutdown = true;
}
@Override
public void shutdownOutput() throws IOException {
ensureOpen();
channel.shutdownOutput();
outputShutdown = true;
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
readSelector.wakeup();
writeSelector.wakeup();
try {
channel.close();
} finally {
readSelector.close();
writeSelector.close();
}
}
@Override
public boolean isConnected() {
return channel.isConnected();
}
@Override
public boolean isBound() {
return true;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public boolean isInputShutdown() {
return inputShutdown;
}
@Override
public boolean isOutputShutdown() {
return outputShutdown;
}
@Override
public SocketAddress getLocalSocketAddress() {
return address;
}
@Override
public SocketAddress getRemoteSocketAddress() {
return address;
}
@Override
public InetAddress getInetAddress() {
return null;
}
@Override
public InetAddress getLocalAddress() {
return null;
}
private void ensureOpen() throws SocketException {
if (closed) {
throw new SocketException("Socket is closed");
}
}
private int read(ByteBuffer buffer) throws IOException {
synchronized (readLock) {
int timeout = soTimeoutMillis;
long deadline = timeout > 0 ? System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout) : 0L;
try {
while (true) {
ensureOpen();
int read = channel.read(buffer);
if (read != 0) {
return read;
}
if (timeout > 0) {
long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime());
if (remaining <= 0) {
throw new SocketTimeoutException("Read timed out");
}
readSelector.select(remaining);
} else {
readSelector.select();
}
failIfInterrupted();
readSelector.selectedKeys().clear();
}
} catch (ClosedSelectorException e) {
throw new SocketException("Socket is closed");
}
}
}
private void write(ByteBuffer buffer) throws IOException {
synchronized (writeLock) {
try {
while (buffer.hasRemaining()) {
ensureOpen();
if (channel.write(buffer) == 0) {
writeSelector.select();
failIfInterrupted();
writeSelector.selectedKeys().clear();
}
}
} catch (ClosedSelectorException e) {
throw new SocketException("Socket is closed");
}
}
}
private void failIfInterrupted() throws IOException {
if (Thread.currentThread().isInterrupted()) {
close();
throw new ClosedByInterruptException();
}
}
private final class ChannelInputStream extends InputStream {
@Override
public int read() throws IOException {
byte[] one = new byte[1];
int read = read(one, 0, 1);
return read == -1 ? -1 : one[0] & 0xff;
}
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
if (length == 0) {
return 0;
}
return UnixDomainSocket.this.read(ByteBuffer.wrap(bytes, offset, length));
}
@Override
public void close() throws IOException {
UnixDomainSocket.this.close();
}
}
private final class ChannelOutputStream extends OutputStream {
@Override
public void write(int value) throws IOException {
write(new byte[] {(byte) value}, 0, 1);
}
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
UnixDomainSocket.this.write(ByteBuffer.wrap(bytes, offset, length));
}
@Override
public void close() throws IOException {
UnixDomainSocket.this.close();
}
}
}
@@ -3,17 +3,31 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import org.apache.hc.core5.http.ConnectionRequestTimeoutException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -73,4 +87,76 @@ class FlociDockerHttpClientTest {
private static DockerHttpClient.Request get(String path) {
return DockerHttpClient.Request.builder().method(DockerHttpClient.Request.Method.GET).path(path).build();
}
// Catches: on a unix:// host, a call to a silent daemon blocking forever because the socket ignored
// the response timeout, and a long-lived stream (a container wait) cut off by that timeout once it
// applies.
@Test
@Timeout(60)
void overAUnixSocketOrdinaryCallsTimeOutWhileLongLivedStreamsStayOpen(@TempDir Path dir) throws Exception {
Path socketPath = dir.resolve("docker.sock");
List<SocketChannel> accepted = new CopyOnWriteArrayList<>();
try (ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
server.bind(UnixDomainSocketAddress.of(socketPath));
Thread acceptor = Thread.ofVirtual().start(() -> {
try {
while (true) {
accepted.add(server.accept());
}
} catch (IOException expected) {
// The server channel closed at the end of the test.
}
});
try (FlociDockerHttpClient client = new FlociDockerHttpClient.Builder()
.dockerHost(URI.create("unix://" + socketPath))
.responseTimeout(Duration.ofSeconds(1))
.build()) {
long start = System.nanoTime();
RuntimeException failure = assertThrows(RuntimeException.class,
() -> client.execute(get("/containers/abc/json")));
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
assertTrue(failure.getCause() instanceof SocketTimeoutException,
"an ordinary call should time out, got " + failure.getCause());
assertTrue(elapsedMillis < 10_000, "timed out after " + elapsedMillis + " ms");
CompletableFuture<Integer> wait = CompletableFuture.supplyAsync(() -> {
try (DockerHttpClient.Response response = client.execute(DockerHttpClient.Request.builder()
.method(DockerHttpClient.Request.Method.POST).path("/containers/abc/wait").build())) {
return response.getStatusCode();
}
});
assertThrows(TimeoutException.class, () -> wait.get(2_500, TimeUnit.MILLISECONDS),
"a container wait must outlive the response timeout");
SocketChannel waitConnection = accepted.get(accepted.size() - 1);
waitConnection.write(ByteBuffer.wrap(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
+ "Content-Length: 15\r\n\r\n{\"StatusCode\":0}").getBytes(StandardCharsets.UTF_8)));
assertEquals(200, wait.get(10, TimeUnit.SECONDS));
} finally {
for (SocketChannel channel : accepted) {
channel.close();
}
acceptor.interrupt();
}
}
}
@Test
void streamingEndpointsAreRecognisedAndOrdinaryCallsAreNot() {
for (String streaming : List.of("POST /v1.43/containers/abc/wait", "POST /exec/xyz/start",
"POST /containers/abc/attach?stream=1", "GET /events?since=1", "GET /containers/abc/logs?follow=true",
"GET /containers/abc/stats", "POST /images/create?fromImage=alpine", "POST /build")) {
assertTrue(FlociDockerHttpClient.isLongLivedStream(request(streaming)), streaming);
}
for (String ordinary : List.of("GET /containers/abc/json", "GET /containers/abc/logs?tail=100",
"GET /containers/abc/stats?stream=0", "POST /containers/abc/start", "POST /containers/create",
"DELETE /containers/abc", "GET /_ping")) {
assertFalse(FlociDockerHttpClient.isLongLivedStream(request(ordinary)), ordinary);
}
}
private static DockerHttpClient.Request request(String methodAndPath) {
String[] parts = methodAndPath.split(" ", 2);
return DockerHttpClient.Request.builder().method(parts[0]).path(parts[1]).build();
}
}
@@ -0,0 +1,159 @@
package io.github.hectorvent.floci.core.common.docker;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.SocketTimeoutException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UnixDomainSocketTest {
@TempDir
Path dir;
private ServerSocketChannel server;
private Path socketPath;
@BeforeEach
void startServer() throws IOException {
socketPath = dir.resolve("docker.sock");
server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
server.bind(UnixDomainSocketAddress.of(socketPath));
}
@AfterEach
void stopServer() throws IOException {
server.close();
}
// Catches: a read that ignores SO_TIMEOUT and blocks forever on a silent peer, as docker-java's
// UnixSocket does.
@Test
void aReadWithATimeoutFailsWhenThePeerStaysSilent() throws Exception {
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
SocketChannel ignored = server.accept()) {
socket.setSoTimeout(200);
long start = System.nanoTime();
assertThrows(SocketTimeoutException.class, () -> socket.getInputStream().read(new byte[16]));
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
assertTrue(elapsedMillis >= 150 && elapsedMillis < 5_000, "timed out after " + elapsedMillis + " ms");
}
}
@Test
void aReadWithoutATimeoutWaitsForDataAndWritesReachThePeer() throws Exception {
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
SocketChannel peer = server.accept()) {
socket.getOutputStream().write("ping".getBytes(StandardCharsets.UTF_8));
ByteBuffer received = ByteBuffer.allocate(4);
while (received.hasRemaining()) {
peer.read(received);
}
assertEquals("ping", new String(received.array(), StandardCharsets.UTF_8));
InputStream input = socket.getInputStream();
CompletableFuture<String> reply = CompletableFuture.supplyAsync(() -> {
try {
byte[] bytes = new byte[4];
int read = 0;
while (read < bytes.length) {
read += input.read(bytes, read, bytes.length - read);
}
return new String(bytes, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
assertThrows(TimeoutException.class, () -> reply.get(300, TimeUnit.MILLISECONDS),
"a read without a timeout should wait for the peer");
peer.write(ByteBuffer.wrap("pong".getBytes(StandardCharsets.UTF_8)));
assertEquals("pong", reply.get(5, TimeUnit.SECONDS));
}
}
// Catches: a close from another thread surfacing as the selector's unchecked
// ClosedSelectorException, which callers expecting an IOException do not handle.
@Test
void closingTheSocketEndsABlockedReadWithAnIOException() throws Exception {
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
SocketChannel ignored = server.accept()) {
InputStream input = socket.getInputStream();
CompletableFuture<Integer> read = CompletableFuture.supplyAsync(() -> {
try {
return input.read(new byte[16]);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
assertThrows(TimeoutException.class, () -> read.get(200, TimeUnit.MILLISECONDS));
socket.close();
ExecutionException failure = assertThrows(ExecutionException.class, () -> read.get(5, TimeUnit.SECONDS));
assertInstanceOf(UncheckedIOException.class, failure.getCause(), "got " + failure.getCause());
}
}
// Catches: an interrupted reader with no timeout spinning on a selector that returns at once
// while the interrupt flag is set.
@Test
void anInterruptedReadClosesTheSocketInsteadOfSpinning() throws Exception {
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
SocketChannel ignored = server.accept()) {
InputStream input = socket.getInputStream();
AtomicReference<Throwable> failure = new AtomicReference<>();
Thread reader = Thread.ofPlatform().start(() -> {
try {
input.read(new byte[16]);
} catch (IOException e) {
failure.set(e);
}
});
reader.join(200);
assertTrue(reader.isAlive(), "the read should be waiting for the peer");
reader.interrupt();
reader.join(5_000);
assertFalse(reader.isAlive(), "the interrupted read should end");
assertInstanceOf(ClosedByInterruptException.class, failure.get());
assertTrue(socket.isClosed());
}
}
@Test
void readingAfterThePeerClosesReturnsEndOfStream() throws Exception {
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString())) {
server.accept().close();
socket.setSoTimeout(2_000);
assertEquals(-1, socket.getInputStream().read());
}
}
}