Skip to content
Draft
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

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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
Expand All @@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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".
* <p>
* 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.
* <p>
* 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.
* <p>
* 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);
}
}
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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);
}

Expand All @@ -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 ||
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
/*
* 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;

/**
* 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Object[]> handlesAndOneShotFlags() {
return Stream.of(
new Object[]{"StringHandle", new StringHandle("<a/>"), false},
new Object[]{"JacksonHandle", new JacksonHandle(new ObjectMapper().createObjectNode()), false},
new Object[]{"BytesHandle", new BytesHandle("<a/>".getBytes(StandardCharsets.UTF_8)), false},
new Object[]{"FileHandle", new FileHandle(new File("pom.xml")), false},
new Object[]{"ReaderHandle", new ReaderHandle(new StringReader("<a/>")), true},
new Object[]{"InputStreamHandle",
new InputStreamHandle(new ByteArrayInputStream("<a/>".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("<a/>")),
OkHttpServices.makeRequestBodyForContent(new ReaderHandle(new StringReader("<b/>")))
);
assertTrue(body.isOneShot());
}

@Test
void multipartWithOnlyResendablePartsIsNotOneShot() {
MultipartBody body = multipart(
OkHttpServices.makeRequestBodyForContent(new StringHandle("<a/>")),
OkHttpServices.makeRequestBodyForContent(new JacksonHandle(new ObjectMapper().createObjectNode()))
);
assertFalse(body.isOneShot());
}

@Test
void oneShotMultipartIsNotRetried() {
MultipartBody body = multipart(
OkHttpServices.makeRequestBodyForContent(new ReaderHandle(new StringReader("<a/>")))
);
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("<a/>"))
);
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();
}
}
}
Loading
Loading