Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -603,10 +604,24 @@ private static final class TransportRequestImpl implements TransportRequest {
private final HttpPost delegate;
private final Map<String, Object> config;
private final AtomicBoolean cancelled = new AtomicBoolean(false);
private final AtomicReference<Error> bodyWriteError;

TransportRequestImpl(HttpPost delegate, Map<String, Object> config) {
this(delegate, config, null);
}

TransportRequestImpl(HttpPost delegate, Map<String, Object> config,
AtomicReference<Error> bodyWriteError) {
this.delegate = delegate;
this.config = config;
this.bodyWriteError = bodyWriteError;
}

void rethrowBodyWriteError() {
Error error = bodyWriteError == null ? null : bodyWriteError.get();
if (error != null) {
throw error;
}
}

@Override
Expand Down Expand Up @@ -882,6 +897,9 @@ private TransportResponse doExecuteRequest(TransportRequest transportRequest, Sp
LOG.debug("Failed to connect to '{}': {}", req.getAuthority(), e.getMessage());
throw e;
} catch (Exception e) {
if (transportRequest instanceof TransportRequestImpl) {
((TransportRequestImpl) transportRequest).rethrowBodyWriteError();
}
LOG.debug("Failed to execute request to '{}': {}", req.getAuthority(), e.getMessage(), e);
if (e instanceof RequestFailedException && req.isCancelled()) {
throw new TransportException("Request was cancelled on client side", e, getQueryId(httpResponse, req));
Expand All @@ -897,16 +915,26 @@ private TransportResponse doExecuteRequest(TransportRequest transportRequest, Sp
public TransportRequest createRequest(Endpoint server, Map<String, Object> requestConfig, IOCallback<OutputStream> writeCallback) {
final URI uri = createRequestURI(server, requestConfig, false);
final HttpPost req = createPostRequest(uri, requestConfig);
final AtomicReference<Error> bodyWriteError = new AtomicReference<>();
try {
String contentEncoding = req.containsHeader(HttpHeaders.CONTENT_ENCODING) ? req.getHeader(HttpHeaders.CONTENT_ENCODING).getValue() : null;
req.setEntity(wrapRequestEntity(
new EntityTemplate(-1, CONTENT_TYPE, contentEncoding, writeCallback),
new EntityTemplate(-1, CONTENT_TYPE, contentEncoding, out -> {
try {
writeCallback.execute(out);
} catch (Error error) {
// MainClientExec closes the shared connection manager when an Error reaches it.
// Let it clean up this request as an IOException, then rethrow the Error above it.
bodyWriteError.compareAndSet(null, error);
throw new IOException("Request body callback failed", error);
}
}),
requestConfig));
} catch (ProtocolException e) {
throw new ClientException("failed to create request body entity", e);
}

return new TransportRequestImpl(req, requestConfig);
return new TransportRequestImpl(req, requestConfig, bodyWriteError);
}

private String getQueryId(HttpResponse httpResponse, HttpPost httpRequest) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,37 @@ public void testDataRequestKeepsContentEncodingWhenParamsInBodyEnabled() {
"an insert body is compressed, so the request must declare the content encoding");
}

/**
* Apache HttpClient closes its whole connection manager when an {@link Error} escapes while it writes a
* request body. The client must preserve and rethrow the original error without letting it cross the Apache
* execution boundary, so a failure of one streaming insert does not make every later request fail.
*/
@Test
public void testRequestBodyErrorDoesNotCloseConnectionPool() throws Exception {
WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort()
.notifier(new ConsoleNotifier(false)));
HttpAPIClientHelper helper = newHelper();
try {
server.start();
server.stubFor(WireMock.post(WireMock.anyUrl()).willReturn(WireMock.ok()));
Endpoint endpoint = new HttpEndpoint("localhost", server.port(), false, "/");
AssertionError expected = new AssertionError("request body failed");

AssertionError thrown = Assert.expectThrows(AssertionError.class,
() -> helper.executeRequest(helper.createRequest(endpoint, new HashMap<>(), out -> {
throw expected;
})));
assertSame(thrown, expected, "the caller must receive the original Error instance");

helper.executeRequest(helper.createRequest(endpoint, new HashMap<>(), "SELECT 1")).close();
server.verify(1, WireMock.postRequestedFor(WireMock.anyUrl())
.withRequestBody(WireMock.equalTo("SELECT 1")));
} finally {
helper.close();
server.stop();
}
}

private static HttpAPIClientHelper newHelper() {
return HttpAPIClientHelperFactory.newHelper(new HashMap<>(), LZ4Factory.fastestInstance());
}
Expand Down
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t
- MultiPoint type support: For ClickHouse `26.8+`, reads and writes the `MultiPoint` geo type, which is transmitted exactly like `Ring` and `LineString` (`Array(Point)`) and is represented as `double[][]` through generic records, binary readers, POJO binding, and SQL parameter formatting. A `MultiPoint` held in a `Dynamic` column is decoded on read; it cannot be written into a `Dynamic` column, because the client infers the type from the Java value and `double[][]` resolves to `Ring`.
- Nested type support: Un-flattened `Nested(f1 T1, ..., fN TN)` columns (tables created with `flatten_nested = 0`) can be written through the insert path (`Client#insert`) using `RowBinaryFormatWriter#setValue`, and are read back through the binary readers and generic records. The column is serialized the same way it is read — identically to `Array(Tuple(T1, ..., TN))`, a var-uint row count followed by one tuple per nested row — so the value supplied for the column is a `List` (or array) of tuples, one tuple per nested row, each carrying the N field values in declaration order.
- Insert APIs: Supports inserting registered POJOs, raw streams, and callback-driven writers, with optional column lists and format selection.
- Streaming insert failures are isolated to their request. If a request-body writer throws an `Error`, the caller receives the same `Error` and later requests through the same client remain usable.
- Insert controls: Supports insert-specific settings such as deduplication token, query id, compression behavior, and request headers.
- Command execution: Executes DDL or other non-result commands and exposes response summaries and operation metrics.
- Session handling: Supports client-wide and per-operation HTTP sessions, operation-level session overrides, runtime updates of client `session_id`, and server-side session validation through `session_check`.
Expand Down
5 changes: 5 additions & 0 deletions history/latest/3453.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Bug Fixes

- **[client-v2]** An `Error` thrown while a streaming insert writes its request body no longer closes the shared
HTTP connection pool. The failing insert still returns the same `Error`, and later requests through the same
`Client` continue to work. (https://github.com/ClickHouse/clickhouse-java/issues/3453)