diff --git a/marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java b/marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java index 1de3b0bff..8d9f1eca2 100644 --- a/marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java +++ b/marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java @@ -19,12 +19,12 @@ import com.marklogic.client.eval.EvalResult; import com.marklogic.client.eval.EvalResultIterator; import com.marklogic.client.extra.okhttpclient.OkHttpClientConfigurator; +import com.marklogic.client.impl.okhttp.ChunkedGzipConnectionCloseInterceptor; import com.marklogic.client.impl.okhttp.HeaderUtil; import com.marklogic.client.impl.okhttp.HttpUrlBuilder; import com.marklogic.client.impl.okhttp.OkHttpUtil; import com.marklogic.client.impl.okhttp.PartIterator; import com.marklogic.client.impl.okhttp.RedactingHttpLogger; -import com.marklogic.client.impl.okhttp.RetryableRequestBody; import com.marklogic.client.io.*; import com.marklogic.client.io.marker.*; import com.marklogic.client.query.*; @@ -215,6 +215,8 @@ private OkHttpClient connect(ConnectionConfig config) { this.baseUri = HttpUrlBuilder.newBaseUrl(config.host, config.port, config.basePath, config.securityContext.getSSLContext()); OkHttpClient.Builder clientBuilder = OkHttpUtil.newOkHttpClientBuilder(config.host, config.securityContext, config.clientConfigurators); + // Added after the configurators so it sees the request headers they leave in place. + clientBuilder.addNetworkInterceptor(new ChunkedGzipConnectionCloseInterceptor()); Properties props = System.getProperties(); if (props.containsKey(LoggingUtil.OKHTTP_NETWORK_LEVEL)) { @@ -300,8 +302,30 @@ private void resetFirstRequestFlag() { } } - private int pingServerBeforeStreaming(int retry) { - return pingServer(baseUri, "ping", retry); + /** + * With digest authentication, the first request on a thread (or the first after a retry) is answered with a 401 + * challenge. OkHttp cannot send a one-shot body (e.g. a Reader) again to answer that challenge, so a body-less + * ping takes the challenge first. If the server is unavailable, this waits and pings again. If it stays + * unavailable, this fails without sending the body, so that content that can only be sent once is not consumed. + */ + private void pingServerBeforeOneShotRequest() { + final int maxPingRetries = 10; + int pingDelay = pingServer(baseUri, "ping", 0); + int pingRetries = 0; + while (pingDelay > 0 && pingRetries < maxPingRetries && !Thread.currentThread().isInterrupted()) { + try { + Thread.sleep(pingDelay); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new MarkLogicIOException("Interrupted while waiting to ping server before sending a one-shot request", e); + } + pingRetries++; + pingDelay = pingServer(baseUri, "ping", 0); + } + if (pingDelay > 0) { + throw new FailedRetryException( + "Service unavailable after " + pingRetries + " ping retries; did not send the request, as its content can only be sent once"); + } } private int pingServer(HttpUrl requestUri, String path, int retry) { @@ -501,6 +525,11 @@ private Response sendRequestOnce(Request request) { "You cannot use this connected object anymore--connection has already been released"); } + RequestBody body = request.body(); + if (body != null && body.isOneShot() && isFirstRequest()) { + pingServerBeforeOneShotRequest(); + } + try { return okHttpClient.newCall(request).execute(); } catch (IOException e) { @@ -1218,30 +1247,9 @@ private TemporalDescriptor putPostDocumentImpl(RequestLogger reqlog, String meth "Document write with null value for " + ((uri != null) ? uri : "new document")); } - if (isFirstRequest() && !isResendable && isStreaming(value)) { - int firstRequestDelay = pingServerBeforeStreaming(retryContext.getRetry()); - if (firstRequestDelay != 0) { - retryContext.calculateNextDelay(0, firstRequestDelay); - continue; - } - } - MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE)); - if (value instanceof OutputStreamSender) { - StreamingOutputImpl sentStream = - new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType); - requestBldr = - ("put".equals(method)) ? - requestBldr.put(sentStream) : - requestBldr.post(sentStream); - } else { - Object sentObj = (reqlog != null) ? - reqlog.copyContent(value) : value; - requestBldr = - ("put".equals(method)) ? - requestBldr.put(new ObjectRequestBody(sentObj, mediaType)) : - requestBldr.post(new ObjectRequestBody(sentObj, mediaType)); - } + RequestBody body = toRequestBody(value, isResendable, mediaType, reqlog); + requestBldr = ("put".equals(method)) ? requestBldr.put(body) : requestBldr.post(body); response = sendRequestOnce(requestBldr); status = response.code(); @@ -1370,14 +1378,6 @@ private TemporalDescriptor putPostDocumentImpl(RequestLogger reqlog, String meth new String[]{metadataMimetype, contentMimetype}, new AbstractWriteHandle[]{metadataHandle, contentHandle}); - if (isFirstRequest() && hasStreamingPart) { - int firstRequestDelay = pingServerBeforeStreaming(retryContext.getRetry()); - if (firstRequestDelay != 0) { - retryContext.calculateNextDelay(0, firstRequestDelay); - continue; - } - } - requestBldr = ("put".equals(method)) ? requestBldr.put(multiPart.build()) : requestBldr.post(multiPart.build()); response = sendRequestOnce(requestBldr); status = response.code(); @@ -1925,19 +1925,17 @@ Response getResponse() { retryContext.sleepIfNeeded(); if (queryDef instanceof StructuredQueryDefinition && !(queryDef instanceof RawQueryDefinition)) { - response = doPost(reqlog, requestBldr, structure); + response = doPost(requestBldr, toRequestBody(structure, true, contentTypeOf(requestBldr), reqlog)); } else if (queryDef instanceof CombinedQueryDefinition) { - response = doPost(reqlog, requestBldr, structure); + response = doPost(requestBldr, toRequestBody(structure, true, contentTypeOf(requestBldr), reqlog)); } else if (queryDef instanceof DeleteQueryDefinition) { response = doGet(requestBldr); - } else if (queryDef instanceof RawQueryDefinition) { - response = doPost(reqlog, requestBldr, baseHandle.sendContent()); - } else if (queryDef instanceof RawCtsQueryDefinition) { - response = doPost(reqlog, requestBldr, baseHandle.sendContent()); + } else if (queryDef instanceof RawQueryDefinition || queryDef instanceof RawCtsQueryDefinition) { + response = doPost(requestBldr, toRequestBody(baseHandle, contentTypeOf(requestBldr), reqlog)); } else if (queryDef instanceof StringQueryDefinition) { response = doGet(requestBldr); } else if (queryDef instanceof CtsQueryDefinition) { - response = doPost(reqlog, requestBldr, structure); + response = doPost(requestBldr, toRequestBody(structure, true, contentTypeOf(requestBldr), reqlog)); } else { throw new UnsupportedOperationException("Cannot search with " + queryDef.getClass().getName()); @@ -2190,9 +2188,9 @@ public Response apply(Request.Builder funcBuilder) { new Function() { public Response apply(Request.Builder funcBuilder) { String contentType = tempBaseHandle.getMimetype(); - return doPost(null, - (contentType == null) ? funcBuilder : funcBuilder.header(HEADER_CONTENT_TYPE, contentType), - tempBaseHandle.sendContent()); + Request.Builder typedBuilder = + (contentType == null) ? funcBuilder : funcBuilder.header(HEADER_CONTENT_TYPE, contentType); + return doPost(typedBuilder, toRequestBody(tempBaseHandle, contentTypeOf(typedBuilder), null)); } }; @@ -2454,29 +2452,10 @@ private void putPostValueImpl(RequestLogger reqlog, String method, Object nextValue = (handle != null) ? handle.sendContent() : value; - RequestBody sentValue; - if (nextValue instanceof OutputStreamSender) { - sentValue = new StreamingOutputImpl( - (OutputStreamSender) nextValue, reqlog, mediaType); - } else { - if (reqlog != null && retryContext.getRetry() == 0) { - sentValue = new ObjectRequestBody(reqlog.copyContent(nextValue), mediaType); - } else { - sentValue = new ObjectRequestBody(nextValue, mediaType); - } - } - - boolean isStreaming = (isFirstRequest() || handle == null) ? isStreaming(sentValue) : false; - - boolean isResendable = (handle == null) ? !isStreaming : handle.isResendable(); - - if (isFirstRequest() && !isResendable && isStreaming) { - int firstRequestDelay = pingServerBeforeStreaming(retryContext.getRetry()); - if (firstRequestDelay != 0) { - retryContext.calculateNextDelay(0, firstRequestDelay); - continue; - } - } + boolean isResendable = (handle != null) ? handle.isResendable() : !isStreaming(nextValue); + // Non-streaming content is copied to the logger, which is only done for the first attempt + RequestLogger bodyLogger = (nextValue instanceof OutputStreamSender || retryContext.getRetry() == 0) ? reqlog : null; + RequestBody sentValue = toRequestBody(nextValue, isResendable, mediaType, bodyLogger); if ("put".equals(method)) { if (requestBldr == null) { @@ -2831,7 +2810,9 @@ public R putResource(RequestLogger reqlog, Function doPutFunction = new Function() { public Response apply(Request.Builder funcBuilder) { - return doPut(reqlog, funcBuilder, inputBase.sendContent()); + Object value = inputBase.sendContent(); + if (value == null) throw new IllegalArgumentException("Resource write with null value"); + return doPut(funcBuilder, toRequestBody(value, isResendable, contentTypeOf(funcBuilder), reqlog)); } }; Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPutFunction, resendableConsumer); @@ -2881,7 +2862,7 @@ public R putResour requestBldr = addTransactionScopedCookies(requestBldr, transaction); requestBldr = addTelemetryAgentId(requestBldr); - response = doPut(requestBldr, multiPart, hasStreamingPart); + response = doPut(requestBldr, multiPart.build()); status = response.code(); if (transaction != null || !RETRYABLE_STATUS_CODES.contains(status)) { @@ -2980,7 +2961,10 @@ public void accept(Boolean resendable) { final Object value = inputBase == null ? null : inputBase.sendContent(); Function doPostFunction = new Function() { public Response apply(Request.Builder funcBuilder) { - return doPost(reqlog, funcBuilder, value); + RequestBody body = (value == null) ? + new ObjectRequestBody(null, null) : + toRequestBody(value, isResendable, contentTypeOf(funcBuilder), reqlog); + return doPost(funcBuilder, body); } }; @@ -3044,7 +3028,7 @@ public R postResou requestBldr = addTransactionScopedCookies(requestBldr, transaction); requestBldr = addTelemetryAgentId(requestBldr); - response = doPost(requestBldr, multiPart, hasStreamingPart); + response = doPost(requestBldr, multiPart.build()); status = response.code(); if (transaction != null || !RETRYABLE_STATUS_CODES.contains(status)) { @@ -3499,7 +3483,7 @@ public RESTServiceResultIterator postMultipartForm( requestBldr = addTrailerHeadersIfNecessary(requestBldr, path); Function doPostFunction = funcBuilder -> - doPost(reqlog, funcBuilder.header(HEADER_ACCEPT, multipartMixedWithBoundary()), multiBuilder.build()); + doPost(funcBuilder.header(HEADER_ACCEPT, multipartMixedWithBoundary()), multiBuilder.build()); // The construction of this was based on whether the primary input was resendable or not. We don't have a primary // input with a multipart request. So keeping this as null for now. @@ -3570,11 +3554,10 @@ private U postIteratedResourceImpl( } }; - Function doPostFunction = requestBuilder -> doPost( - reqlog, - requestBuilder.header(HEADER_ACCEPT, multipartMixedWithBoundary()), - inputBase.sendContent() - ); + Function doPostFunction = requestBuilder -> { + Request.Builder acceptBuilder = requestBuilder.header(HEADER_ACCEPT, multipartMixedWithBoundary()); + return doPost(acceptBuilder, toRequestBody(inputBase, contentTypeOf(acceptBuilder), reqlog)); + }; Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPostFunction, resendableConsumer); Objects.requireNonNull(response); @@ -3646,7 +3629,7 @@ private U postIt requestBldr = addTransactionScopedCookies(requestBldr, transaction); requestBldr = addTelemetryAgentId(requestBldr); - response = doPost(requestBldr, multiPart, hasStreamingPart); + response = doPost(requestBldr, multiPart.build()); status = response.code(); if (transaction != null || !RETRYABLE_STATUS_CODES.contains(status)) { @@ -3745,34 +3728,8 @@ private Request.Builder makePutWebResource(String path, return setupRequest(path, params); } - private Response doPut(RequestLogger reqlog, Request.Builder requestBldr, Object value) { - if (value == null) throw new IllegalArgumentException("Resource write with null value"); - - if (isFirstRequest() && isStreaming(value)) pingServerBeforeStreaming(0); - - MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE)); - if (value instanceof OutputStreamSender) { - requestBldr = requestBldr.put(new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType)); - } else { - if (reqlog != null) { - requestBldr = requestBldr.put(new ObjectRequestBody(reqlog.copyContent(value), mediaType)); - } else { - requestBldr = requestBldr.put(new ObjectRequestBody(value, mediaType)); - } - } - Response response = sendRequestOnce(requestBldr); - - if (isFirstRequest()) setFirstRequest(false); - - return response; - } - - private Response doPut(Request.Builder requestBldr, - MultipartBody.Builder multiPart, boolean hasStreamingPart) { - if (isFirstRequest() && hasStreamingPart) pingServerBeforeStreaming(0); - - requestBldr = requestBldr.put(multiPart.build()); - Response response = sendRequestOnce(requestBldr); + private Response doPut(Request.Builder requestBldr, RequestBody body) { + Response response = sendRequestOnce(requestBldr.put(body)); if (isFirstRequest()) setFirstRequest(false); @@ -3787,38 +3744,8 @@ private Request.Builder makePostWebResource(String path, RequestParameters param return setupRequest(path, params); } - private Response doPost(RequestLogger reqlog, Request.Builder requestBldr, Object value) { - if (isFirstRequest() && isStreaming(value)) { - pingServerBeforeStreaming(0); - } - - MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE)); - if (value == null) { - requestBldr = requestBldr.post(new ObjectRequestBody(null, null)); - } else if (value instanceof MultipartBody) { - requestBldr = requestBldr.post((MultipartBody) value); - } else if (value instanceof OutputStreamSender) { - requestBldr = requestBldr - .post(new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType)); - } else { - if (reqlog != null) { - requestBldr = requestBldr.post(new ObjectRequestBody(reqlog.copyContent(value), mediaType)); - } else { - requestBldr = requestBldr.post(new ObjectRequestBody(value, mediaType)); - } - } - Response response = sendRequestOnce(requestBldr); - - if (isFirstRequest()) setFirstRequest(false); - - return response; - } - - private Response doPost(Request.Builder requestBldr, - MultipartBody.Builder multiPart, boolean hasStreamingPart) { - if (isFirstRequest() && hasStreamingPart) pingServerBeforeStreaming(0); - - Response response = sendRequestOnce(requestBldr.post(multiPart.build())); + private Response doPost(Request.Builder requestBldr, RequestBody body) { + Response response = sendRequestOnce(requestBldr.post(body)); if (isFirstRequest()) setFirstRequest(false); @@ -4000,19 +3927,8 @@ private boolean addParts( } } - Part bodyPart = null; - if (value instanceof OutputStreamSender) { - bodyPart = Part.create(partHeaders.build(), new StreamingOutputImpl( - (OutputStreamSender) value, reqlog, mediaType)); - } else { - if (reqlog != null) { - bodyPart = Part.create(partHeaders.build(), new ObjectRequestBody(reqlog.copyContent(value), mediaType)); - } else { - bodyPart = Part.create(partHeaders.build(), new ObjectRequestBody(value, mediaType)); - } - } - - multiPart = multiPart.addPart(bodyPart); + RequestBody partBody = toRequestBody(value, handleBase.isResendable(), mediaType, reqlog); + multiPart = multiPart.addPart(Part.create(partHeaders.build(), partBody)); } return hasStreamingPart; @@ -4653,7 +4569,7 @@ public InputStream match(StructureWriteHandle document, Function doPostFunction = new Function() { public Response apply(Request.Builder funcBuilder) { - return doPost(null, funcBuilder, baseHandle.sendContent()); + return doPost(funcBuilder, toRequestBody(baseHandle, contentTypeOf(funcBuilder), null)); } }; Response response = sendRequestWithRetry(requestBldr, doPostFunction, null); @@ -4749,9 +4665,9 @@ public InputStream match(QueryDefinition queryDef, retryContext.sleepIfNeeded(); if (queryDef instanceof StructuredQueryDefinition) { - response = doPost(null, requestBldr, structure); + response = doPost(requestBldr, toRequestBody(structure, true, contentTypeOf(requestBldr), null)); } else if (queryDef instanceof RawQueryDefinition) { - response = doPost(null, requestBldr, baseHandle.sendContent()); + response = doPost(requestBldr, toRequestBody(baseHandle, contentTypeOf(requestBldr), null)); } else if (queryDef instanceof StringQueryDefinition) { response = sendRequestOnce(requestBldr.get()); } else { @@ -5194,10 +5110,10 @@ static private List getPartList(MimeMultipart multipart) { } } - static private class ObjectRequestBody extends RequestBody implements RetryableRequestBody { + static private class ObjectRequestBody extends RequestBody { - private Object obj; - private MediaType contentType; + private final Object obj; + private final MediaType contentType; ObjectRequestBody(Object obj, MediaType contentType) { super(); @@ -5231,10 +5147,10 @@ public void writeTo(BufferedSink sink) throws IOException { } @Override - public boolean isRetryable() { - // Added in 8.0.0 to work with the retry interceptor so it knows whether the body can be retried or not. - // InputStreams cannot be retried as they are consumed on first read. - return !(obj instanceof InputStream); + public boolean isOneShot() { + // An InputStream is consumed by the first write. Using OkHttp's own contract means that a MultipartBody + // containing this body is also reported as one-shot. + return obj instanceof InputStream; } } @@ -5275,15 +5191,36 @@ public static RequestBody makeRequestBodyForContent(AbstractWriteHandle content) if (content == null) { return new EmptyRequestBody(); } - HandleImplementation handleBase = HandleAccessor.as(content); + HandleImplementation handleBase = HandleAccessor.as(content); Format format = handleBase.getFormat(); String mimetype = (format == Format.BINARY) ? null : handleBase.getMimetype(); MediaType mediaType = MediaType.parse( (mimetype != null) ? mimetype : "application/x-unknown-content-type" ); - return (content instanceof OutputStreamSender) ? - new StreamingOutputImpl((OutputStreamSender) content, null, mediaType) : - new ObjectRequestBody(HandleAccessor.sendContent(content), mediaType); + return toRequestBody(handleBase, mediaType, null); + } + + private static MediaType contentTypeOf(Request.Builder requestBldr) { + return makeType(requestBldr.build().header(HEADER_CONTENT_TYPE)); + } + + /** + * The one place where a handle's content becomes a request body, so that the handle's resendability is always + * reflected in {@code isOneShot()}. + */ + private static RequestBody toRequestBody(HandleImplementation handle, MediaType mediaType, RequestLogger reqlog) { + return toRequestBody(handle.sendContent(), handle.isResendable(), mediaType, reqlog); + } + + /** + * @param content already obtained from a handle's {@code sendContent()}, or any other content that is sent as is + * @param resendable whether {@code content}, if it is an {@code OutputStreamSender}, can be written again + */ + private static RequestBody toRequestBody(Object content, boolean resendable, MediaType mediaType, RequestLogger reqlog) { + if (content instanceof OutputStreamSender sender) { + return new StreamingOutputImpl(sender, reqlog, mediaType, resendable); + } + return new ObjectRequestBody(reqlog != null ? reqlog.copyContent(content) : content, mediaType); } class CallRequestImpl implements CallRequest { @@ -5389,25 +5326,6 @@ private void executeRequest(CallResponseImpl responseImpl) { }; Function sendRequestFunction = requestBldr -> { - if (isFirstRequest() && hasStreamingPart) { - // Ping the server before streaming; if unavailable, wait and retry the ping - int pingDelay = pingServer(callBaseUri, "", 0); - int pingRetries = 0; - int maxPingRetries = 10; // Prevent infinite loop - while (pingDelay > 0 && pingRetries < maxPingRetries && !Thread.currentThread().isInterrupted()) { - try { - Thread.sleep(pingDelay); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted while waiting to ping server before streaming", e); - } - pingRetries++; - pingDelay = pingServer(callBaseUri, "", 0); - } - if (pingRetries >= maxPingRetries) { - logger.warn("Server still unavailable after {} ping attempts before streaming", maxPingRetries); - } - } Response response = sendRequestOnce(requestBldr); if (isFirstRequest()) setFirstRequest(false); return response; @@ -5493,21 +5411,6 @@ private RequestBody makeRequestBody(String value) { return new AtomicRequestBody(value, MediaType.parse("text/plain")); } - private RequestBody makeRequestBody(AbstractWriteHandle document) { - if (document == null) { - return new EmptyRequestBody(); - } - HandleImplementation handleBase = HandleAccessor.as(document); - Format format = handleBase.getFormat(); - String mimetype = (format == Format.BINARY) ? null : handleBase.getMimetype(); - MediaType mediaType = MediaType.parse( - (mimetype != null) ? mimetype : "application/x-unknown-content-type" - ); - return (document instanceof OutputStreamSender) ? - new StreamingOutputImpl((OutputStreamSender) document, null, mediaType) : - new ObjectRequestBody(HandleAccessor.sendContent(document), mediaType); - } - private RequestBody makeRequestBody(CallField[] params) { if (params == null || params.length == 0) { return new EmptyRequestBody(); @@ -5564,7 +5467,7 @@ private RequestBody makeRequestBody(CallField[] params) { hasStreamingPartCondition.set(); } hasValue.set(); - multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue)); + multiBldr.addFormDataPart(paramName, null, makeRequestBodyForContent(paramValue)); }); } } else if (param instanceof BufferedMultipleNodeCallField) { @@ -5588,7 +5491,7 @@ private RequestBody makeRequestBody(CallField[] params) { paramValues[i] = paramValue; } hasValue.set(); - multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue)); + multiBldr.addFormDataPart(paramName, null, makeRequestBodyForContent(paramValue)); } } } diff --git a/marklogic-client-api/src/main/java/com/marklogic/client/impl/StreamingOutputImpl.java b/marklogic-client-api/src/main/java/com/marklogic/client/impl/StreamingOutputImpl.java index 5fd30e6d0..e87345658 100644 --- a/marklogic-client-api/src/main/java/com/marklogic/client/impl/StreamingOutputImpl.java +++ b/marklogic-client-api/src/main/java/com/marklogic/client/impl/StreamingOutputImpl.java @@ -1,9 +1,8 @@ /* - * Copyright (c) 2010-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ package com.marklogic.client.impl; -import com.marklogic.client.impl.okhttp.RetryableRequestBody; import com.marklogic.client.io.OutputStreamSender; import com.marklogic.client.util.RequestLogger; import okhttp3.MediaType; @@ -13,17 +12,23 @@ import java.io.IOException; import java.io.OutputStream; -class StreamingOutputImpl extends RequestBody implements RetryableRequestBody { +class StreamingOutputImpl extends RequestBody { - private OutputStreamSender handle; - private RequestLogger logger; - private MediaType contentType; + private final OutputStreamSender handle; + private final RequestLogger logger; + private final MediaType contentType; + private final boolean resendable; - StreamingOutputImpl(OutputStreamSender handle, RequestLogger logger, MediaType contentType) { + /** + * @param resendable the originating handle's {@code isResendable()}; if false, the content is assumed to be + * consumed by the first write and this body is reported to OkHttp as one-shot + */ + StreamingOutputImpl(OutputStreamSender handle, RequestLogger logger, MediaType contentType, boolean resendable) { super(); this.handle = handle; this.logger = logger; this.contentType = contentType; + this.resendable = resendable; } @Override @@ -49,8 +54,9 @@ public void writeTo(BufferedSink sink) throws IOException { } @Override - public boolean isRetryable() { - // Added in 8.0.0; streaming output cannot be retried as the stream is consumed on first write. - return false; + public boolean isOneShot() { + // Using OkHttp's own contract means that a MultipartBody containing this body is also reported as one-shot, which + // OkHttp and RetryIOExceptionInterceptor both honor. + return !resendable; } } diff --git a/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/ChunkedGzipConnectionCloseInterceptor.java b/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/ChunkedGzipConnectionCloseInterceptor.java new file mode 100644 index 000000000..85ba65abb --- /dev/null +++ b/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/ChunkedGzipConnectionCloseInterceptor.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + */ +package com.marklogic.client.impl.okhttp; + +import okhttp3.Connection; +import okhttp3.Interceptor; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; +import java.util.Locale; + +/** + * Workaround for a MarkLogic server bug. When a request has both "TE: trailers" and "Accept-Encoding: gzip", MarkLogic + * sends a chunked, gzipped response marked "Connection: Keep-Alive", but then closes the connection. OkHttp keeps that + * dead connection in its pool, so the next request on it fails, and a request with a one-shot body (e.g. a Reader) + * cannot be resent. With "Connection: close" on the request, OkHttp does not return the connection to its pool, and + * MarkLogic also answers "Connection: close". + *

+ * This must be a network interceptor so that it sees the headers that are actually sent: OkHttp adds + * "Accept-Encoding: gzip" after application interceptors run, and a client configurator may remove it. + *

+ * Only HTTP/1.1 connections are affected. On HTTP/2 (e.g. to a load balancer in front of MarkLogic) the header is not + * sent, yet OkHttp would still stop reusing a healthy connection because of it. + *

+ * TODO Remove this once the MarkLogic server bug is fixed (HTTPRequest::finishResponse closes every compressed + * connection, even after sendKeepAliveHeader) and the oldest MarkLogic version supported by this client has the fix. + */ +public class ChunkedGzipConnectionCloseInterceptor implements Interceptor { + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + if (isHttp11(chain.connection()) && headerContains(request, "TE", "trailers") && headerContains(request, "Accept-Encoding", "gzip")) { + request = request.newBuilder().header("Connection", "close").build(); + } + return chain.proceed(request); + } + + private static boolean isHttp11(Connection connection) { + return connection != null && connection.protocol() == Protocol.HTTP_1_1; + } + + private static boolean headerContains(Request request, String name, String token) { + String value = request.header(name); + return value != null && value.toLowerCase(Locale.ROOT).contains(token); + } +} diff --git a/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryIOExceptionInterceptor.java b/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryIOExceptionInterceptor.java index b2f57e0c3..82b928216 100644 --- a/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryIOExceptionInterceptor.java +++ b/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryIOExceptionInterceptor.java @@ -1,11 +1,12 @@ /* - * Copyright (c) 2010-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ package com.marklogic.client.impl.okhttp; import com.marklogic.client.MarkLogicIOException; import okhttp3.Interceptor; import okhttp3.Request; +import okhttp3.RequestBody; import okhttp3.Response; import org.slf4j.Logger; @@ -40,8 +41,9 @@ public RetryIOExceptionInterceptor(int maxRetries, long initialDelayMs, double b @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); + RequestBody requestBody = request.body(); - if (request.body() instanceof RetryableRequestBody body && !body.isRetryable()) { + if (requestBody != null && cannotBeSentAgain(requestBody)) { return chain.proceed(request); } @@ -66,6 +68,13 @@ public Response intercept(Chain chain) throws IOException { throw new IllegalStateException("Unexpected end of retry loop"); } + @SuppressWarnings("deprecation") + private static boolean cannotBeSentAgain(RequestBody requestBody) { + // RetryableRequestBody is deprecated, but is honored until it is removed for bodies that do not override isOneShot() + return requestBody.isOneShot() || + (requestBody instanceof RetryableRequestBody legacyBody && !legacyBody.isRetryable()); + } + private boolean isRetryableIOException(Exception e) { return e instanceof ConnectException || e instanceof SocketTimeoutException || diff --git a/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryableRequestBody.java b/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryableRequestBody.java index ad35a07c3..a3a3d610c 100644 --- a/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryableRequestBody.java +++ b/marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryableRequestBody.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ package com.marklogic.client.impl.okhttp; @@ -7,7 +7,12 @@ * Interface for RequestBody implementations to signal whether they can be retried after an IOException. * This is used by RetryIOExceptionInterceptor to determine if a failed request can be retried. * Added in 8.0.0. + * + * @deprecated since 8.3.0; override {@link okhttp3.RequestBody#isOneShot()} instead, as it is also honored by OkHttp + * itself and propagates through a {@code MultipartBody}. The request bodies in this library no longer implement this + * interface. RetryIOExceptionInterceptor still honors it until it is removed. */ +@Deprecated public interface RetryableRequestBody { /** * @return false if this request body cannot be retried (e.g., because it consumes a stream that can only be diff --git a/marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingOutputImplTest.java b/marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingOutputImplTest.java new file mode 100644 index 000000000..2b7e093d8 --- /dev/null +++ b/marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingOutputImplTest.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + */ +package com.marklogic.client.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.marklogic.client.impl.okhttp.RetryIOExceptionInterceptor; +import com.marklogic.client.impl.okhttp.RetryableRequestBody; +import com.marklogic.client.io.BytesHandle; +import com.marklogic.client.io.FileHandle; +import com.marklogic.client.io.InputStreamHandle; +import com.marklogic.client.io.JacksonHandle; +import com.marklogic.client.io.ReaderHandle; +import com.marklogic.client.io.StringHandle; +import com.marklogic.client.io.marker.AbstractWriteHandle; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okio.BufferedSink; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.stream.Stream; + +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; + +/** + * Verifies that the request body built for a handle reports {@code isOneShot()} according to whether the handle's + * content can be written more than once, and that OkHttp-based retry honours that. + */ +class StreamingOutputImplTest { + + static Stream handlesAndOneShotFlags() { + return Stream.of( + new Object[]{"StringHandle", new StringHandle(""), false}, + new Object[]{"JacksonHandle", new JacksonHandle(new ObjectMapper().createObjectNode()), false}, + new Object[]{"BytesHandle", new BytesHandle("".getBytes(StandardCharsets.UTF_8)), false}, + new Object[]{"FileHandle", new FileHandle(new File("pom.xml")), false}, + new Object[]{"ReaderHandle", new ReaderHandle(new StringReader("")), true}, + new Object[]{"InputStreamHandle", + new InputStreamHandle(new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8))), true} + ); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("handlesAndOneShotFlags") + void oneShotMatchesWhetherTheHandleCanBeResent(String name, AbstractWriteHandle handle, boolean expectedOneShot) { + assertEquals(expectedOneShot, OkHttpServices.makeRequestBodyForContent(handle).isOneShot()); + } + + @Test + void multipartWithAnyOneShotPartIsOneShot() { + MultipartBody body = multipart( + OkHttpServices.makeRequestBodyForContent(new StringHandle("")), + OkHttpServices.makeRequestBodyForContent(new ReaderHandle(new StringReader(""))) + ); + assertTrue(body.isOneShot()); + } + + @Test + void multipartWithOnlyResendablePartsIsNotOneShot() { + MultipartBody body = multipart( + OkHttpServices.makeRequestBodyForContent(new StringHandle("")), + OkHttpServices.makeRequestBodyForContent(new JacksonHandle(new ObjectMapper().createObjectNode())) + ); + assertFalse(body.isOneShot()); + } + + @Test + void oneShotMultipartIsNotRetried() { + MultipartBody body = multipart( + OkHttpServices.makeRequestBodyForContent(new ReaderHandle(new StringReader(""))) + ); + CountingFailure failure = new CountingFailure(Integer.MAX_VALUE); + + assertThrows(IOException.class, () -> client(failure).newCall(post(body)).execute()); + assertEquals(1, failure.attempts); + } + + @Test + void resendableMultipartIsRetried() throws IOException { + MultipartBody body = multipart( + OkHttpServices.makeRequestBodyForContent(new StringHandle("")) + ); + CountingFailure failure = new CountingFailure(1); + + try (Response response = client(failure).newCall(post(body)).execute()) { + assertEquals(200, response.code()); + } + assertEquals(2, failure.attempts); + } + + @Test + void bodyUsingDeprecatedRetryableRequestBodyIsNotRetried() { + CountingFailure failure = new CountingFailure(Integer.MAX_VALUE); + + assertThrows(IOException.class, () -> client(failure).newCall(post(new LegacyNonRetryableBody())).execute()); + assertEquals(1, failure.attempts); + } + + /** + * A body written before 8.3.0, which says it cannot be retried without overriding {@code isOneShot()}. + */ + @SuppressWarnings("deprecation") + private static class LegacyNonRetryableBody extends RequestBody implements RetryableRequestBody { + @Override + public MediaType contentType() { + return null; + } + + @Override + public void writeTo(BufferedSink sink) { + } + + @Override + public boolean isRetryable() { + return false; + } + } + + private static MultipartBody multipart(RequestBody... parts) { + MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (int i = 0; i < parts.length; i++) { + builder.addFormDataPart("part" + i, null, parts[i]); + } + return builder.build(); + } + + private static Request post(RequestBody body) { + return new Request.Builder().url("http://localhost/").post(body).build(); + } + + private static OkHttpClient client(CountingFailure failure) { + return new OkHttpClient.Builder() + .addInterceptor(new RetryIOExceptionInterceptor(3, 0, 1, 0)) + .addInterceptor(failure) + .build(); + } + + /** + * Fails the first {@code failuresBeforeSuccess} attempts with an IOException, then returns a 200. + */ + private static class CountingFailure implements okhttp3.Interceptor { + private final int failuresBeforeSuccess; + int attempts; + + CountingFailure(int failuresBeforeSuccess) { + this.failuresBeforeSuccess = failuresBeforeSuccess; + } + + @Override + public Response intercept(Chain chain) throws IOException { + if (++attempts <= failuresBeforeSuccess) { + throw new IOException("unexpected end of stream"); + } + return new Response.Builder() + .request(chain.request()) + .protocol(Protocol.HTTP_1_1) + .code(200) + .message("OK") + .body(ResponseBody.create("", null)) + .build(); + } + } +} diff --git a/marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingPartRequestTest.java b/marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingPartRequestTest.java new file mode 100644 index 000000000..a0e325317 --- /dev/null +++ b/marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingPartRequestTest.java @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + */ +package com.marklogic.client.impl; + +import com.marklogic.client.DatabaseClient; +import com.marklogic.client.DatabaseClientFactory; +import com.marklogic.client.FailedRetryException; +import com.marklogic.client.MarkLogicIOException; +import com.marklogic.client.extra.okhttpclient.RemoveAcceptEncodingConfigurator; +import com.marklogic.client.row.RowManager; +import com.marklogic.client.row.RowRecord; +import com.marklogic.client.row.RowSet; +import mockwebserver3.Dispatcher; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; +import mockwebserver3.SocketEffect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.StringReader; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Function; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Uses a mock server to verify how requests with non-resendable content (e.g. a Reader) are sent. MarkLogic answers a + * Row Manager request with a chunked, gzipped response that says "Connection: Keep-Alive", yet closes the connection + * after it. If a one-shot request is the next one on that connection, it fails and cannot be resent. + */ +class StreamingPartRequestTest { + + private static final String PAYLOAD = "{\"a\":1}"; + private static final String ROWS_BOUNDARY = "rows-boundary"; + + private MockWebServer mockWebServer; + private final List requests = new CopyOnWriteArrayList<>(); + private DatabaseClient client; + + @BeforeEach + void beforeEach() throws IOException { + mockWebServer = new MockWebServer(); + mockWebServer.start(); + client = DatabaseClientFactory.newClient("localhost", mockWebServer.getPort(), + new DatabaseClientFactory.BasicAuthContext("user", "password")); + } + + @AfterEach + void afterEach() { + client.release(); + mockWebServer.close(); + } + + @Test + void streamingRequestAfterRowsRequestSucceeds() throws IOException { + serve(request -> isRowsRequest(request) ? rowsResponseThatClosesConnectionLikeMarkLogic(request) : + new MockResponse.Builder().code(200).build()); + + queryRows(); + callWithStreamingPart(); + + List posts = requests.stream() + .filter(r -> "POST".equals(r.getMethod()) && !isRowsRequest(r)).toList(); + assertEquals(1, posts.size(), "The streaming request should have been sent exactly once"); + assertEquals(1, countOccurrences(posts.get(0).getBody().utf8(), PAYLOAD), + "The body must arrive once and intact: " + posts.get(0).getBody().utf8()); + assertEquals(0, requests.stream().filter(r -> "HEAD".equals(r.getMethod())).count(), + "No ping should be sent before a one-shot request when not using digest authentication"); + + RecordedRequest rows = requests.get(0); + assertEquals("close", rows.getHeaders().get("Connection"), + "The client should ask to close the connection that MarkLogic would close anyway"); + assertNotEquals(rows.getConnectionIndex(), posts.get(0).getConnectionIndex(), + "The streaming request should not reuse the connection from the rows request"); + } + + @Test + void rowsRequestKeepsConnectionWhenGzipIsDisabled() throws IOException { + DatabaseClientFactory.addConfigurator(new RemoveAcceptEncodingConfigurator()); + try { + client.release(); + client = DatabaseClientFactory.newClient("localhost", mockWebServer.getPort(), + new DatabaseClientFactory.BasicAuthContext("user", "password")); + } finally { + DatabaseClientFactory.removeConfigurators(); + } + serve(request -> isRowsRequest(request) ? rowsResponseThatClosesConnectionLikeMarkLogic(request) : + new MockResponse.Builder().code(200).build()); + + queryRows(); + callWithStreamingPart(); + + RecordedRequest rows = requests.get(0); + assertNotEquals("close", rows.getHeaders().get("Connection"), + "Without gzip, MarkLogic keeps the connection open, so the client should not ask to close it"); + assertEquals(rows.getConnectionIndex(), requests.get(1).getConnectionIndex(), + "The streaming request should reuse the connection from the rows request"); + } + + @Test + void failedStreamingRequestIsNotResent() { + serve(request -> "POST".equals(request.getMethod()) ? + new MockResponse.Builder().onResponseStart(new SocketEffect.CloseSocket()).build() : + new MockResponse.Builder().code(200).build()); + + MarkLogicIOException ex = assertThrows(MarkLogicIOException.class, this::callWithStreamingPart); + + assertFalse(ex.getMessage().contains("Stream closed"), + "The stream cannot be resent, so the original failure should be reported; message: " + ex.getMessage()); + assertEquals(1, requests.stream().filter(r -> "POST".equals(r.getMethod())).count(), + "The streaming request must not be sent a second time"); + } + + @Test + void digestAuthenticationPingsOnlyBeforeFirstStreamingRequest() { + useDigestClient(); + serve(request -> request.getHeaders().get("Authorization") == null ? + digestChallenge() : new MockResponse.Builder().code(200).build()); + + callWithStreamingPart(); + callWithStreamingPart(); + + List methods = requests.stream().map(RecordedRequest::getMethod).toList(); + int firstPost = methods.indexOf("POST"); + assertTrue(methods.subList(0, firstPost).contains("HEAD"), "The first one-shot request should be preceded by a ping: " + methods); + assertFalse(methods.subList(firstPost, methods.size()).contains("HEAD"), "Only the first one-shot request needs a ping: " + methods); + assertEquals(2, methods.stream().filter("POST"::equals).count(), "Each body should be sent once: " + methods); + } + + @Test + void failedStreamingRequestIsNotResentWithDigestAuthentication() { + useDigestClient(); + serve(request -> { + if (request.getHeaders().get("Authorization") == null) { + return digestChallenge(); + } + return "POST".equals(request.getMethod()) ? + new MockResponse.Builder().onResponseStart(new SocketEffect.CloseSocket()).build() : + new MockResponse.Builder().code(200).build(); + }); + + assertThrows(MarkLogicIOException.class, this::callWithStreamingPart); + + assertEquals(1, requests.stream() + .filter(r -> "POST".equals(r.getMethod()) && r.getHeaders().get("Authorization") != null).count(), + "The authenticated streaming request must not be sent a second time"); + } + + @Test + void streamingRequestIsNotSentWhenPingsFindServerUnavailable() { + useDigestClient(); + serve(request -> { + if (request.getHeaders().get("Authorization") == null) { + return digestChallenge(); + } + return new MockResponse.Builder().code("HEAD".equals(request.getMethod()) ? 503 : 200).build(); + }); + + assertThrows(FailedRetryException.class, this::callWithStreamingPart); + + assertEquals(0, requests.stream().filter(r -> "POST".equals(r.getMethod())).count(), + "Content that can only be sent once must not be sent while the server is unavailable"); + } + + private void useDigestClient() { + client.release(); + client = DatabaseClientFactory.newClient("localhost", mockWebServer.getPort(), + new DatabaseClientFactory.DigestAuthContext("user", "password")); + } + + private static MockResponse digestChallenge() { + return new MockResponse.Builder().code(401) + .addHeader("WWW-Authenticate", "Digest realm=\"public\", qop=\"auth\", nonce=\"abc\", opaque=\"xyz\"") + .build(); + } + + private static boolean isRowsRequest(RecordedRequest request) { + return request.getUrl().encodedPath().endsWith("/v1/rows"); + } + + /** + * Mimics MarkLogic: a response to "TE: trailers" with "Accept-Encoding: gzip" is chunked and gzipped, and unless + * the client asked for "Connection: close", it says "Keep-Alive" yet the server closes the connection after it. + */ + private static MockResponse rowsResponseThatClosesConnectionLikeMarkLogic(RecordedRequest request) { + String body = "--" + ROWS_BOUNDARY + "\r\n" + + "Content-Type: application/json\r\n\r\n" + + "{\"columns\":[{\"name\":\"a\"}]}\r\n" + + "--" + ROWS_BOUNDARY + "--\r\n"; + MockResponse.Builder builder = new MockResponse.Builder().code(200) + .addHeader("Content-Type", "multipart/mixed; boundary=" + ROWS_BOUNDARY) + .body(body); + boolean chunkedAndGzipped = "trailers".equals(request.getHeaders().get("TE")) && + "gzip".equals(request.getHeaders().get("Accept-Encoding")); + if (chunkedAndGzipped && !"close".equalsIgnoreCase(request.getHeaders().get("Connection"))) { + builder.addHeader("Connection", "Keep-Alive").onResponseEnd(new SocketEffect.CloseSocket()); + } + return builder.build(); + } + + private void queryRows() throws IOException { + RowManager rowManager = client.newRowManager(); + try (RowSet rows = rowManager.resultRows(rowManager.newPlanBuilder().fromView("schema", "view"))) { + rows.forEach(row -> { + }); + } + } + + private void serve(Function responder) { + mockWebServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + requests.add(request); + return responder.apply(request); + } + }); + } + + private void callWithStreamingPart() { + BaseProxy.request("/ds/custom-content/", "importContent.xqy", BaseProxy.ParameterValuesKind.MULTIPLE_NODES) + .on(client) + .withSession() + .withParams(BaseProxy.documentParam("content", false, + Stream.of(new StringReader(PAYLOAD)).map(BaseProxy.JsonDocumentType::fromReader))) + .responseNone(); + } + + private static int countOccurrences(String text, String token) { + int count = 0; + for (int i = text.indexOf(token); i >= 0; i = text.indexOf(token, i + token.length())) { + count++; + } + return count; + } +} diff --git a/marklogic-client-api/src/test/java/com/marklogic/client/impl/okhttp/ChunkedGzipConnectionCloseInterceptorTest.java b/marklogic-client-api/src/test/java/com/marklogic/client/impl/okhttp/ChunkedGzipConnectionCloseInterceptorTest.java new file mode 100644 index 000000000..1ffdda7f0 --- /dev/null +++ b/marklogic-client-api/src/test/java/com/marklogic/client/impl/okhttp/ChunkedGzipConnectionCloseInterceptorTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. + */ +package com.marklogic.client.impl.okhttp; + +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * The server bug that the interceptor works around is specific to HTTP/1.1, so the interceptor must leave other + * connections alone. How a DatabaseClient behaves on HTTP/1.1 is covered by StreamingPartRequestTest. + */ +class ChunkedGzipConnectionCloseInterceptorTest { + + @Test + void http11ConnectionIsNotReused() throws Exception { + List requests = sendTwoRowsRequests(Protocol.HTTP_1_1); + + assertEquals("close", requests.get(0).getHeaders().get("Connection")); + assertNotEquals(requests.get(0).getConnectionIndex(), requests.get(1).getConnectionIndex()); + } + + @Test + void http2ConnectionIsReused() throws Exception { + List requests = sendTwoRowsRequests(Protocol.H2_PRIOR_KNOWLEDGE); + + assertEquals(requests.get(0).getConnectionIndex(), requests.get(1).getConnectionIndex(), + "An HTTP/2 connection is not affected by the server bug, so it should stay in the pool"); + } + + private static List sendTwoRowsRequests(Protocol protocol) throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.setProtocols(List.of(protocol)); + server.enqueue(new MockResponse.Builder().code(200).body("{}").build()); + server.enqueue(new MockResponse.Builder().code(200).body("{}").build()); + server.start(); + + OkHttpClient client = new OkHttpClient.Builder() + .protocols(List.of(protocol)) + .addNetworkInterceptor(new ChunkedGzipConnectionCloseInterceptor()) + .build(); + try { + for (int i = 0; i < 2; i++) { + // OkHttp adds "Accept-Encoding: gzip" itself + Request request = new Request.Builder().url(server.url("/v1/rows")) + .header("TE", "trailers") + .post(RequestBody.create("{}", MediaType.parse("application/json"))) + .build(); + try (Response response = client.newCall(request).execute()) { + assertEquals(200, response.code()); + response.body().string(); + } + } + return List.of(server.takeRequest(), server.takeRequest()); + } finally { + client.connectionPool().evictAll(); + } + } + } +}