From 2ef7ddc12152a39598e3c245633e82415a63ab7a Mon Sep 17 00:00:00 2001 From: 7487 <1042653432@qq.com> Date: Wed, 2 Dec 2026 11:09:28 +0800 Subject: [PATCH] Fix request body errors closing connection pool Signed-off-by: 7487 <1042653432@qq.com> --- .../api/internal/HttpAPIClientHelper.java | 32 +++++++++++++++++-- .../api/internal/HttpAPIClientHelperTest.java | 31 ++++++++++++++++++ docs/features.md | 1 + history/latest/3453.md | 5 +++ 4 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 history/latest/3453.md diff --git a/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java b/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java index 05d4866e6..08a13c188 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java @@ -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; @@ -603,10 +604,24 @@ private static final class TransportRequestImpl implements TransportRequest { private final HttpPost delegate; private final Map config; private final AtomicBoolean cancelled = new AtomicBoolean(false); + private final AtomicReference bodyWriteError; TransportRequestImpl(HttpPost delegate, Map config) { + this(delegate, config, null); + } + + TransportRequestImpl(HttpPost delegate, Map config, + AtomicReference 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 @@ -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)); @@ -897,16 +915,26 @@ private TransportResponse doExecuteRequest(TransportRequest transportRequest, Sp public TransportRequest createRequest(Endpoint server, Map requestConfig, IOCallback writeCallback) { final URI uri = createRequestURI(server, requestConfig, false); final HttpPost req = createPostRequest(uri, requestConfig); + final AtomicReference 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) { diff --git a/client-v2/src/test/java/com/clickhouse/client/api/internal/HttpAPIClientHelperTest.java b/client-v2/src/test/java/com/clickhouse/client/api/internal/HttpAPIClientHelperTest.java index 138777bc8..59fcb8824 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/internal/HttpAPIClientHelperTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/internal/HttpAPIClientHelperTest.java @@ -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()); } diff --git a/docs/features.md b/docs/features.md index aab3e3ddf..6d28836f2 100644 --- a/docs/features.md +++ b/docs/features.md @@ -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`. diff --git a/history/latest/3453.md b/history/latest/3453.md new file mode 100644 index 000000000..a45166297 --- /dev/null +++ b/history/latest/3453.md @@ -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)