Skip to content

Commit a41b4a6

Browse files
hmadala001Copilot
andcommitted
MLE-32970 Ping before every streaming Data Services request
The Java client always sends Accept-Encoding: gzip, and MarkLogic can close a connection after replying to such a request even though OkHttp keeps it pooled. A Data Services call that streams a one-shot body (e.g. a Reader), made right after another call such as RowManager.resultRows(), could be written to that closed connection. The body was consumed before the failure was noticed, so the retry failed with 'Stream closed'. The ping that guards against this only ran for the first request on a thread, and only for digest authentication, so it had already been used up by the earlier call. It now runs before every request that has a streaming part, so a closed connection is found by a ping that has no body to lose. This relies on StreamingOutputImpl reporting one-shot bodies as such: with the ping but without that, a failure after the ping is resent by OkHttp and reports 'Stream closed' again. StreamingPartRequestTest (mock server) checks that the ping happens before each streaming request and that a failed streaming request is not resent. followup-fix Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent cdb2f2c commit a41b4a6

7 files changed

Lines changed: 488 additions & 357 deletions

File tree

‎marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java‎

Lines changed: 108 additions & 220 deletions
Large diffs are not rendered by default.

‎marklogic-client-api/src/main/java/com/marklogic/client/impl/StreamingOutputImpl.java‎

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
*/
44
package com.marklogic.client.impl;
55

6-
import com.marklogic.client.impl.okhttp.RetryableRequestBody;
76
import com.marklogic.client.io.OutputStreamSender;
87
import com.marklogic.client.util.RequestLogger;
98
import okhttp3.MediaType;
@@ -13,25 +12,16 @@
1312
import java.io.IOException;
1413
import java.io.OutputStream;
1514

16-
class StreamingOutputImpl extends RequestBody implements RetryableRequestBody {
15+
class StreamingOutputImpl extends RequestBody {
1716

18-
private OutputStreamSender handle;
19-
private RequestLogger logger;
20-
private MediaType contentType;
21-
private boolean resendable;
17+
private final OutputStreamSender handle;
18+
private final RequestLogger logger;
19+
private final MediaType contentType;
20+
private final boolean resendable;
2221

2322
/**
24-
* Assumes the wrapped handle cannot be resent, which is the safe default for callers that have not determined
25-
* whether the underlying content can be sent again (e.g. because it is backed by a one-shot stream).
26-
*/
27-
StreamingOutputImpl(OutputStreamSender handle, RequestLogger logger, MediaType contentType) {
28-
this(handle, logger, contentType, false);
29-
}
30-
31-
/**
32-
* @param resendable whether the wrapped handle's content can be written again if the request must be retried;
33-
* should reflect the originating handle's own {@code isResendable()} value rather than
34-
* always assuming the content is one-shot.
23+
* @param resendable the originating handle's {@code isResendable()}; if false, the content is assumed to be
24+
* consumed by the first write and this body is reported to OkHttp as one-shot
3525
*/
3626
StreamingOutputImpl(OutputStreamSender handle, RequestLogger logger, MediaType contentType, boolean resendable) {
3727
super();
@@ -63,21 +53,10 @@ public void writeTo(BufferedSink sink) throws IOException {
6353
handle.write(out);
6454
}
6555

66-
@Override
67-
public boolean isRetryable() {
68-
// Added in 8.0.0. Originally always returned false, on the assumption that the wrapped stream is consumed
69-
// on first write. That is not true for handles whose content is fully buffered (e.g. JacksonHandle,
70-
// StringHandle) and which report isResendable() == true; for those, the content can safely be written
71-
// again, so we defer to the resendable flag supplied by the caller instead of hardcoding false.
72-
return resendable;
73-
}
74-
7556
@Override
7657
public boolean isOneShot() {
77-
// Declares this body as one-shot via OkHttp's own contract so that when this body is nested inside another
78-
// RequestBody (e.g. a MultipartBody part for a Data Services call), OkHttp and RetryIOExceptionInterceptor
79-
// both recognize the outer body as non-retryable too; isRetryable() above is only checked when this is the
80-
// top-level request body and would otherwise be bypassed for a nested streaming part.
58+
// Using OkHttp's own contract means that a MultipartBody containing this body is also reported as one-shot, which
59+
// OkHttp and RetryIOExceptionInterceptor both honor.
8160
return !resendable;
8261
}
8362
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
3+
*/
4+
package com.marklogic.client.impl.okhttp;
5+
6+
import okhttp3.Interceptor;
7+
import okhttp3.Request;
8+
import okhttp3.Response;
9+
10+
import java.io.IOException;
11+
import java.util.Locale;
12+
13+
/**
14+
* Workaround for a MarkLogic server bug. When a request has both "TE: trailers" and "Accept-Encoding: gzip", MarkLogic
15+
* sends a chunked, gzipped response marked "Connection: Keep-Alive", but then closes the connection. OkHttp keeps that
16+
* dead connection in its pool, so the next request on it fails, and a request with a one-shot body (e.g. a Reader)
17+
* cannot be resent. Asking for "Connection: close" makes MarkLogic say that it will close the connection, so OkHttp
18+
* discards it.
19+
* <p>
20+
* This must be a network interceptor so that it sees the headers that are actually sent: OkHttp adds
21+
* "Accept-Encoding: gzip" after application interceptors run, and a client configurator may remove it.
22+
* <p>
23+
* TODO Remove this once the MarkLogic server bug is fixed (HTTPRequest::finishResponse closes every compressed
24+
* connection, even after sendKeepAliveHeader) and the oldest MarkLogic version supported by this client has the fix.
25+
*/
26+
public class ChunkedGzipConnectionCloseInterceptor implements Interceptor {
27+
28+
@Override
29+
public Response intercept(Chain chain) throws IOException {
30+
Request request = chain.request();
31+
if (headerContains(request, "TE", "trailers") && headerContains(request, "Accept-Encoding", "gzip")) {
32+
request = request.newBuilder().header("Connection", "close").build();
33+
}
34+
return chain.proceed(request);
35+
}
36+
37+
private static boolean headerContains(Request request, String name, String token) {
38+
String value = request.header(name);
39+
return value != null && value.toLowerCase(Locale.ROOT).contains(token);
40+
}
41+
}

‎marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryIOExceptionInterceptor.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ public Response intercept(Chain chain) throws IOException {
4343
Request request = chain.request();
4444
RequestBody requestBody = request.body();
4545

46-
if (requestBody != null && (requestBody.isOneShot() ||
47-
requestBody instanceof RetryableRequestBody body && !body.isRetryable())) {
46+
if (requestBody != null && requestBody.isOneShot()) {
4847
return chain.proceed(request);
4948
}
5049

‎marklogic-client-api/src/main/java/com/marklogic/client/impl/okhttp/RetryableRequestBody.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
/*
2-
* Copyright (c) 2010-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
2+
* Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
33
*/
44
package com.marklogic.client.impl.okhttp;
55

66
/**
77
* Interface for RequestBody implementations to signal whether they can be retried after an IOException.
88
* This is used by RetryIOExceptionInterceptor to determine if a failed request can be retried.
99
* Added in 8.0.0.
10+
*
11+
* @deprecated since 8.3.0; no longer used. {@link okhttp3.RequestBody#isOneShot()} is now the only signal that a request
12+
* body cannot be sent again, as it is also honored by OkHttp itself and propagates through a {@code MultipartBody}.
1013
*/
14+
@Deprecated
1115
public interface RetryableRequestBody {
1216
/**
1317
* @return false if this request body cannot be retried (e.g., because it consumes a stream that can only be

‎marklogic-client-api/src/test/java/com/marklogic/client/impl/StreamingOutputImplTest.java‎

Lines changed: 106 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -3,144 +3,146 @@
33
*/
44
package com.marklogic.client.impl;
55

6+
import com.fasterxml.jackson.databind.ObjectMapper;
67
import com.marklogic.client.impl.okhttp.RetryIOExceptionInterceptor;
7-
import okhttp3.MediaType;
8+
import com.marklogic.client.io.BytesHandle;
9+
import com.marklogic.client.io.FileHandle;
10+
import com.marklogic.client.io.InputStreamHandle;
11+
import com.marklogic.client.io.JacksonHandle;
12+
import com.marklogic.client.io.ReaderHandle;
13+
import com.marklogic.client.io.StringHandle;
14+
import com.marklogic.client.io.marker.AbstractWriteHandle;
815
import okhttp3.MultipartBody;
916
import okhttp3.OkHttpClient;
17+
import okhttp3.Protocol;
1018
import okhttp3.Request;
19+
import okhttp3.RequestBody;
20+
import okhttp3.Response;
21+
import okhttp3.ResponseBody;
1122
import org.junit.jupiter.api.Test;
23+
import org.junit.jupiter.params.ParameterizedTest;
24+
import org.junit.jupiter.params.provider.MethodSource;
1225

1326
import java.io.ByteArrayInputStream;
27+
import java.io.File;
1428
import java.io.IOException;
15-
import java.io.InputStream;
29+
import java.io.StringReader;
1630
import java.nio.charset.StandardCharsets;
17-
import java.util.concurrent.atomic.AtomicInteger;
31+
import java.util.stream.Stream;
1832

1933
import static org.junit.jupiter.api.Assertions.assertEquals;
2034
import static org.junit.jupiter.api.Assertions.assertFalse;
2135
import static org.junit.jupiter.api.Assertions.assertThrows;
2236
import static org.junit.jupiter.api.Assertions.assertTrue;
2337

38+
/**
39+
* Verifies that the request body built for a handle reports {@code isOneShot()} according to whether the handle's
40+
* content can be written more than once, and that OkHttp-based retry honours that.
41+
*/
2442
class StreamingOutputImplTest {
2543

26-
@Test
27-
void multipartBodyWithStreamingPartIsNotRetried() {
28-
StreamingOutputImpl streamingBody = new StreamingOutputImpl(
29-
outputStream -> outputStream.write("content".getBytes(StandardCharsets.UTF_8)),
30-
null,
31-
MediaType.get("application/xml")
44+
static Stream<Object[]> handlesAndOneShotFlags() {
45+
return Stream.of(
46+
new Object[]{"StringHandle", new StringHandle("<a/>"), false},
47+
new Object[]{"JacksonHandle", new JacksonHandle(new ObjectMapper().createObjectNode()), false},
48+
new Object[]{"BytesHandle", new BytesHandle("<a/>".getBytes(StandardCharsets.UTF_8)), false},
49+
new Object[]{"FileHandle", new FileHandle(new File("pom.xml")), false},
50+
new Object[]{"ReaderHandle", new ReaderHandle(new StringReader("<a/>")), true},
51+
new Object[]{"InputStreamHandle",
52+
new InputStreamHandle(new ByteArrayInputStream("<a/>".getBytes(StandardCharsets.UTF_8))), true}
3253
);
33-
MultipartBody multipartBody = new MultipartBody.Builder()
34-
.setType(MultipartBody.FORM)
35-
.addFormDataPart("body", null, streamingBody)
36-
.build();
37-
assertTrue(multipartBody.isOneShot());
54+
}
3855

39-
AtomicInteger attempts = new AtomicInteger();
40-
OkHttpClient client = new OkHttpClient.Builder()
41-
.addInterceptor(new RetryIOExceptionInterceptor(3, 0, 1, 0))
42-
.addInterceptor(chain -> {
43-
attempts.incrementAndGet();
44-
throw new IOException("unexpected end of stream");
45-
})
46-
.build();
47-
Request request = new Request.Builder()
48-
.url("http://localhost/")
49-
.post(multipartBody)
50-
.build();
56+
@ParameterizedTest(name = "{0}")
57+
@MethodSource("handlesAndOneShotFlags")
58+
void oneShotMatchesWhetherTheHandleCanBeResent(String name, AbstractWriteHandle handle, boolean expectedOneShot) {
59+
assertEquals(expectedOneShot, OkHttpServices.makeRequestBodyForContent(handle).isOneShot());
60+
}
5161

52-
assertThrows(IOException.class, () -> client.newCall(request).execute());
53-
assertEquals(1, attempts.get());
62+
@Test
63+
void multipartWithAnyOneShotPartIsOneShot() {
64+
MultipartBody body = multipart(
65+
OkHttpServices.makeRequestBodyForContent(new StringHandle("<a/>")),
66+
OkHttpServices.makeRequestBodyForContent(new ReaderHandle(new StringReader("<b/>")))
67+
);
68+
assertTrue(body.isOneShot());
5469
}
5570

5671
@Test
57-
void multipartBodyWithInputStreamPartIsNotRetried() {
58-
InputStream inputStream = new ByteArrayInputStream("content".getBytes(StandardCharsets.UTF_8));
59-
OkHttpServices.ObjectRequestBody inputStreamBody =
60-
new OkHttpServices.ObjectRequestBody(inputStream, MediaType.get("application/xml"));
61-
MultipartBody multipartBody = new MultipartBody.Builder()
62-
.setType(MultipartBody.FORM)
63-
.addFormDataPart("body", null, inputStreamBody)
64-
.build();
65-
assertTrue(multipartBody.isOneShot(),
66-
"A multipart body containing an InputStream-backed part must be one-shot so the retry interceptor does " +
67-
"not replay an already-consumed stream.");
72+
void multipartWithOnlyResendablePartsIsNotOneShot() {
73+
MultipartBody body = multipart(
74+
OkHttpServices.makeRequestBodyForContent(new StringHandle("<a/>")),
75+
OkHttpServices.makeRequestBodyForContent(new JacksonHandle(new ObjectMapper().createObjectNode()))
76+
);
77+
assertFalse(body.isOneShot());
78+
}
6879

69-
AtomicInteger attempts = new AtomicInteger();
70-
OkHttpClient client = new OkHttpClient.Builder()
71-
.addInterceptor(new RetryIOExceptionInterceptor(3, 0, 1, 0))
72-
.addInterceptor(chain -> {
73-
attempts.incrementAndGet();
74-
throw new IOException("unexpected end of stream");
75-
})
76-
.build();
77-
Request request = new Request.Builder()
78-
.url("http://localhost/")
79-
.post(multipartBody)
80-
.build();
80+
@Test
81+
void oneShotMultipartIsNotRetried() {
82+
MultipartBody body = multipart(
83+
OkHttpServices.makeRequestBodyForContent(new ReaderHandle(new StringReader("<a/>")))
84+
);
85+
CountingFailure failure = new CountingFailure(Integer.MAX_VALUE);
8186

82-
assertThrows(IOException.class, () -> client.newCall(request).execute());
83-
assertEquals(1, attempts.get());
87+
assertThrows(IOException.class, () -> client(failure).newCall(post(body)).execute());
88+
assertEquals(1, failure.attempts);
8489
}
8590

8691
@Test
87-
void resendableStreamingBodyIsRetried() {
88-
StreamingOutputImpl resendableBody = new StreamingOutputImpl(
89-
outputStream -> outputStream.write("content".getBytes(StandardCharsets.UTF_8)),
90-
null,
91-
MediaType.get("application/xml"),
92-
true
92+
void resendableMultipartIsRetried() throws IOException {
93+
MultipartBody body = multipart(
94+
OkHttpServices.makeRequestBodyForContent(new StringHandle("<a/>"))
9395
);
94-
assertTrue(resendableBody.isRetryable(),
95-
"A handle that reports isResendable() == true should allow its StreamingOutputImpl wrapper to be retried.");
96-
assertFalse(resendableBody.isOneShot(),
97-
"A resendable StreamingOutputImpl should not be marked one-shot, so OkHttp permits rewriting its body.");
96+
CountingFailure failure = new CountingFailure(1);
9897

99-
AtomicInteger attempts = new AtomicInteger();
100-
OkHttpClient client = new OkHttpClient.Builder()
101-
.addInterceptor(new RetryIOExceptionInterceptor(3, 0, 1, 0))
102-
.addInterceptor(chain -> {
103-
if (attempts.incrementAndGet() < 2) {
104-
throw new IOException("unexpected end of stream");
105-
}
106-
return new okhttp3.Response.Builder()
107-
.request(chain.request())
108-
.protocol(okhttp3.Protocol.HTTP_1_1)
109-
.code(200)
110-
.message("OK")
111-
.body(okhttp3.ResponseBody.create("", null))
112-
.build();
113-
})
114-
.build();
115-
Request request = new Request.Builder()
116-
.url("http://localhost/")
117-
.post(resendableBody)
118-
.build();
119-
120-
try (okhttp3.Response response = client.newCall(request).execute()) {
98+
try (Response response = client(failure).newCall(post(body)).execute()) {
12199
assertEquals(200, response.code());
122-
} catch (IOException e) {
123-
throw new RuntimeException(e);
124100
}
125-
assertEquals(2, attempts.get(),
126-
"The request should have been retried once after the first simulated connection failure.");
101+
assertEquals(2, failure.attempts);
127102
}
128103

129-
@Test
130-
void nonResendableHandleInMultipartIsNotRetried() {
131-
// Mirrors how OkHttpServices wraps a non-resendable handle (e.g. ReaderHandle) in a Data Services multipart
132-
// request: the per-part resendable flag should propagate up through MultipartBody.isOneShot().
133-
StreamingOutputImpl nonResendablePart = new StreamingOutputImpl(
134-
outputStream -> outputStream.write("content".getBytes(StandardCharsets.UTF_8)),
135-
null,
136-
MediaType.get("application/xml"),
137-
false
138-
);
139-
MultipartBody multipartBody = new MultipartBody.Builder()
140-
.setType(MultipartBody.FORM)
141-
.addFormDataPart("body", null, nonResendablePart)
104+
private static MultipartBody multipart(RequestBody... parts) {
105+
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
106+
for (int i = 0; i < parts.length; i++) {
107+
builder.addFormDataPart("part" + i, null, parts[i]);
108+
}
109+
return builder.build();
110+
}
111+
112+
private static Request post(RequestBody body) {
113+
return new Request.Builder().url("http://localhost/").post(body).build();
114+
}
115+
116+
private static OkHttpClient client(CountingFailure failure) {
117+
return new OkHttpClient.Builder()
118+
.addInterceptor(new RetryIOExceptionInterceptor(3, 0, 1, 0))
119+
.addInterceptor(failure)
142120
.build();
143-
assertTrue(multipartBody.isOneShot(),
144-
"A multipart request containing even one non-resendable part must remain one-shot overall.");
121+
}
122+
123+
/**
124+
* Fails the first {@code failuresBeforeSuccess} attempts with an IOException, then returns a 200.
125+
*/
126+
private static class CountingFailure implements okhttp3.Interceptor {
127+
private final int failuresBeforeSuccess;
128+
int attempts;
129+
130+
CountingFailure(int failuresBeforeSuccess) {
131+
this.failuresBeforeSuccess = failuresBeforeSuccess;
132+
}
133+
134+
@Override
135+
public Response intercept(Chain chain) throws IOException {
136+
if (++attempts <= failuresBeforeSuccess) {
137+
throw new IOException("unexpected end of stream");
138+
}
139+
return new Response.Builder()
140+
.request(chain.request())
141+
.protocol(Protocol.HTTP_1_1)
142+
.code(200)
143+
.message("OK")
144+
.body(ResponseBody.create("", null))
145+
.build();
146+
}
145147
}
146148
}

0 commit comments

Comments
 (0)