From e92ec4f48f5bb13b48ccd43278cb29585288ce90 Mon Sep 17 00:00:00 2001 From: Ranjeet Singh Date: Thu, 3 Dec 2026 10:29:02 +0530 Subject: [PATCH] MLE-32953 Do not resend a one-shot request after a 502, 503 or 504 The client sends a request again after a 502, 503 or 504. Content that can only be read once had been consumed by the attempt that failed, so the request was sent again without it. An Optic plan that writes documents from an InputStreamHandle could store empty documents this way, without an error. - sendRequestWithRetry and the retry loops of search() and match(QueryDefinition) now throw a ResourceNotResendableException when the body of the failed request is one-shot. This covers the callers that had no check of their own: Optic plans with bound content, values() with a raw query, match() with a document, and search() and match() with a raw query. - Content that can be read again is still sent again. - OneShotRequestRetryTest covers each of these with a mock server, for each retryable status, along with the cases that must not change: a caller with a check of its own, a request without a body, a request in a transaction, a status that is not retried, an OutputStreamHandle marked as resendable, a resendable request while the server stays unavailable, and the ping before the next one-shot request with digest authentication. --- .../marklogic/client/impl/OkHttpServices.java | 18 + .../client/impl/OneShotRequestRetryTest.java | 368 ++++++++++++++++++ 2 files changed, 386 insertions(+) create mode 100644 marklogic-client-api/src/test/java/com/marklogic/client/impl/OneShotRequestRetryTest.java 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 7dae5f252..7c922c9ff 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 @@ -559,6 +559,21 @@ private Response sendRequestWithRetry(Request.Builder requestBldr, Function doFunction, Consumer resendableConsumer ) { @@ -610,6 +625,7 @@ private Response sendRequestWithRetry( * scenarios, we pass it as null and it is just a no-operation. */ if (resendableConsumer != null) resendableConsumer.accept(null); + throwIfRequestCannotBeSentAgain(response); /* * Calculate the delay before which we shouldn't retry */ @@ -1958,6 +1974,7 @@ Response getResponse() { int retryAfter = Utilities.parseInt(retryAfterRaw); closeResponse(response); + throwIfRequestCannotBeSentAgain(response); retryContext.calculateNextDelay(retryAfter, calculateDelay(retryContext.getRetry())); } @@ -4691,6 +4708,7 @@ public InputStream match(QueryDefinition queryDef, int retryAfter = Utilities.parseInt(retryAfterRaw); closeResponse(response); + throwIfRequestCannotBeSentAgain(response); retryContext.calculateNextDelay(retryAfter, calculateDelay(retryContext.getRetry())); } diff --git a/marklogic-client-api/src/test/java/com/marklogic/client/impl/OneShotRequestRetryTest.java b/marklogic-client-api/src/test/java/com/marklogic/client/impl/OneShotRequestRetryTest.java new file mode 100644 index 000000000..ced44c6e6 --- /dev/null +++ b/marklogic-client-api/src/test/java/com/marklogic/client/impl/OneShotRequestRetryTest.java @@ -0,0 +1,368 @@ +/* + * 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.DatabaseClient; +import com.marklogic.client.DatabaseClientFactory; +import com.marklogic.client.FailedRequestException; +import com.marklogic.client.FailedRetryException; +import com.marklogic.client.ResourceNotResendableException; +import com.marklogic.client.Transaction; +import com.marklogic.client.alerting.RuleDefinitionList; +import com.marklogic.client.document.DocumentWriteSet; +import com.marklogic.client.expression.PlanBuilder; +import com.marklogic.client.io.Format; +import com.marklogic.client.io.InputStreamHandle; +import com.marklogic.client.io.JacksonHandle; +import com.marklogic.client.io.OutputStreamHandle; +import com.marklogic.client.io.ReaderHandle; +import com.marklogic.client.io.SearchHandle; +import com.marklogic.client.io.StringHandle; +import com.marklogic.client.io.ValuesHandle; +import com.marklogic.client.io.marker.AbstractWriteHandle; +import com.marklogic.client.query.QueryManager; +import com.marklogic.client.query.ValuesDefinition; +import com.marklogic.client.row.RowManager; +import mockwebserver3.Dispatcher; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Uses a mock server that answers the first request with a 503, or with the status set by a test. The client sends a + * request again after a 502, 503 or 504, but content that can only be read once (e.g. an InputStream) has been + * consumed by the first attempt, so sending the request again would send it without that content. + */ +class OneShotRequestRetryTest { + + private static final String PAYLOAD = "content-that-can-only-be-read-once"; + + private MockWebServer mockWebServer; + private DatabaseClient client; + private int firstStatus = 503; + private boolean serverStaysUnavailable; + // The requests that the first status applies to; pings and the opening of a transaction are not among them + private final List requests = new CopyOnWriteArrayList<>(); + // Every authenticated request, including pings + private final List methods = new CopyOnWriteArrayList<>(); + + @BeforeEach + void beforeEach() throws IOException { + mockWebServer = new MockWebServer(); + mockWebServer.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + if (request.getHeaders().get("Authorization") == null) { + return new MockResponse.Builder().code(401) + .addHeader("WWW-Authenticate", "Digest realm=\"public\", qop=\"auth\", nonce=\"abc\", opaque=\"xyz\"") + .build(); + } + methods.add(request.getMethod()); + String path = request.getUrl().encodedPath(); + if ("HEAD".equals(request.getMethod())) { + return new MockResponse.Builder().code(200).build(); + } + if (path.endsWith("/v1/transactions")) { + return new MockResponse.Builder().code(303).addHeader("Location", "/v1/transactions/123").build(); + } + requests.add(request); + // A document write or delete is answered with "No Content" when it succeeds + int successStatus = "POST".equals(request.getMethod()) ? 200 : 204; + boolean fail = requests.size() == 1 || serverStaysUnavailable; + return new MockResponse.Builder().code(fail ? firstStatus : successStatus).build(); + } + }); + mockWebServer.start(); + client = DatabaseClientFactory.newClient("localhost", mockWebServer.getPort(), + new DatabaseClientFactory.BasicAuthContext("user", "password")); + } + + @AfterEach + void afterEach() { + client.release(); + mockWebServer.close(); + } + + // --- Requests that had no check before: sendRequestWithRetry without a check by its caller + + @Test + void opticPlanWithOneShotDocument() { + DocumentWriteSet writeSet = client.newDocumentManager().newWriteSet(); + writeSet.add("/a.txt", oneShotHandle(Format.TEXT)); + + assertIsNotSentAgain(() -> client.newRowManager().execute(planWritingDocuments(writeSet))); + } + + @Test + void opticPlanWithOneOneShotDocumentAmongResendableOnes() { + DocumentWriteSet writeSet = client.newDocumentManager().newWriteSet(); + writeSet.add("/a.txt", new StringHandle("resendable").withFormat(Format.TEXT)); + writeSet.add("/b.txt", oneShotHandle(Format.TEXT)); + writeSet.add("/c.txt", new StringHandle("resendable").withFormat(Format.TEXT)); + + assertIsNotSentAgain(() -> client.newRowManager().execute(planWritingDocuments(writeSet))); + } + + @Test + void opticPlanWithOneShotContentParam() { + assertIsNotSentAgain(() -> client.newRowManager().execute(planWithContent(oneShotHandle(Format.JSON)))); + } + + @Test + void opticPlanWithReaderContentParam() { + // A Reader is written by the handle itself, so this uses a different request body class than an InputStream + ReaderHandle handle = new ReaderHandle(new StringReader("[{\"a\":\"" + PAYLOAD + "\"}]")).withFormat(Format.JSON); + + assertIsNotSentAgain(() -> client.newRowManager().execute(planWithContent(handle))); + } + + @Test + void matchWithOneShotDocument() { + assertIsNotSentAgain(() -> client.newRuleManager().match(oneShotHandle(Format.XML), new RuleDefinitionList())); + } + + @Test + void valuesWithOneShotQuery() { + QueryManager queryManager = client.newQueryManager(); + ValuesDefinition valuesDefinition = queryManager.newValuesDefinition("myValues"); + valuesDefinition.setQueryDefinition(queryManager.newRawCombinedQueryDefinition(oneShotHandle(Format.XML))); + + assertIsNotSentAgain(() -> queryManager.values(valuesDefinition, new ValuesHandle())); + } + + // --- Requests that had no check before: retry loops of their own + + @Test + void searchWithOneShotQuery() { + QueryManager queryManager = client.newQueryManager(); + + assertIsNotSentAgain(() -> queryManager.search( + queryManager.newRawCombinedQueryDefinition(oneShotHandle(Format.XML)), new SearchHandle())); + } + + @Test + void matchWithOneShotQuery() { + QueryManager queryManager = client.newQueryManager(); + + assertIsNotSentAgain(() -> client.newRuleManager().match( + queryManager.newRawCombinedQueryDefinition(oneShotHandle(Format.XML)), new RuleDefinitionList())); + } + + // --- Requests that already had a check, which must keep working as before + + @Test + void documentWriteWithOneShotContent() { + assertIsNotSentAgain(() -> client.newTextDocumentManager().write("/a.txt", oneShotHandle(Format.TEXT))); + } + + @Test + void dataServiceWithStreamingParam() { + ResourceNotResendableException ex = assertIsNotSentAgain(() -> + 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()); + + assertTrue(ex.getMessage().contains("importContent.xqy"), + "A caller with a check of its own should still report its own message; message: " + ex.getMessage()); + } + + // --- Each status that the client retries + + @ParameterizedTest + @ValueSource(ints = {502, 503, 504}) + void oneShotRequestIsNotSentAgainAfterEachRetryableStatus(int status) { + firstStatus = status; + + assertIsNotSentAgain(() -> client.newRowManager().execute(planWithContent(oneShotHandle(Format.JSON)))); + } + + @ParameterizedTest + @ValueSource(ints = {502, 503, 504}) + void resendableRequestIsSentAgainAfterEachRetryableStatus(int status) { + firstStatus = status; + + client.newRowManager().execute(planWithContent(resendableHandle())); + + assertIsSentAgainWithContent(); + } + + // --- Requests that must still be sent again + + @Test + void matchWithResendableDocumentIsSentAgain() { + try { + client.newRuleManager().match(new StringHandle("" + PAYLOAD + "").withFormat(Format.XML), new RuleDefinitionList()); + } catch (RuntimeException e) { + // The mock server does not return a list of rules; what matters is what was sent + } + + assertIsSentAgainWithContent(); + } + + @Test + void documentWriteWithResendableContentIsSentAgain() { + client.newTextDocumentManager().write("/a.txt", new StringHandle(PAYLOAD).withFormat(Format.TEXT)); + + assertIsSentAgainWithContent(); + } + + @Test + void requestWithoutBodyIsSentAgain() { + client.newTextDocumentManager().delete("/a.txt"); + + assertEquals(List.of("DELETE", "DELETE"), methods, "A request without a body can always be sent again"); + } + + @Test + void resendableRequestIsSentAgainUntilTheRetryPeriodHasElapsed() { + serverStaysUnavailable = true; + // The limits are read when a client is created; the defaults would have this test wait for 2 minutes + System.setProperty(RESTServices.MAX_DELAY_PROP, "1"); + System.setProperty(RESTServices.MIN_RETRY_PROP, "2"); + try { + client.release(); + client = DatabaseClientFactory.newClient("localhost", mockWebServer.getPort(), + new DatabaseClientFactory.BasicAuthContext("user", "password")); + } finally { + System.clearProperty(RESTServices.MAX_DELAY_PROP); + System.clearProperty(RESTServices.MIN_RETRY_PROP); + } + + FailedRetryException ex = assertThrows(FailedRetryException.class, + () -> client.newRowManager().execute(planWithContent(resendableHandle()))); + + assertTrue(requests.size() >= 3, + "The request should be followed by at least the configured 2 retries; requests: " + requests.size()); + for (RecordedRequest request : requests) { + assertTrue(request.getBody().utf8().contains(PAYLOAD), "Every attempt should have the content"); + } + assertTrue(ex.getMessage().contains("maximum retry period elapsed"), "Unexpected message: " + ex.getMessage()); + } + + // --- A handle that cannot tell by itself whether its content can be written again + + @Test + void outputStreamHandleIsNotSentAgainByDefault() { + OutputStreamHandle handle = new OutputStreamHandle(out -> out.write(contentAsJson())).withFormat(Format.JSON); + + assertIsNotSentAgain(() -> client.newRowManager().execute(planWithContent(handle))); + } + + @Test + void outputStreamHandleMarkedAsResendableIsSentAgain() { + OutputStreamHandle handle = new OutputStreamHandle(out -> out.write(contentAsJson())).withFormat(Format.JSON); + handle.setResendable(true); + + client.newRowManager().execute(planWithContent(handle)); + + assertIsSentAgainWithContent(); + } + + // --- Cases where the client does not send a request again at all, so the new check must not change the outcome + + @Test + void statusThatIsNotRetriedIsReportedAsBefore() { + firstStatus = 500; + + // A 500 is not retried, so it should be reported as a failed request and not as one that cannot be sent again + assertThrows(FailedRequestException.class, + () -> client.newRowManager().execute(planWithContent(oneShotHandle(Format.JSON)))); + + assertEquals(1, requests.size()); + } + + @Test + void requestInTransactionIsReportedAsBefore() { + Transaction transaction = client.openTransaction(); + + // A request in a transaction is never sent again, so the 503 should be reported as a failed request + assertThrows(FailedRequestException.class, + () -> client.newRowManager().execute(planWithContent(oneShotHandle(Format.JSON)), transaction)); + + assertEquals(1, requests.size()); + } + + // --- Digest authentication + + @Test + void nextOneShotRequestIsPrecededByPingWithDigestAuthentication() { + client.release(); + client = DatabaseClientFactory.newClient("localhost", mockWebServer.getPort(), + new DatabaseClientFactory.DigestAuthContext("user", "password")); + + assertIsNotSentAgain(() -> client.newRowManager().execute(planWithContent(oneShotHandle(Format.JSON)))); + client.newRowManager().execute(planWithContent(oneShotHandle(Format.JSON))); + + assertEquals(List.of("HEAD", "POST", "HEAD", "POST"), methods, + "After a request could not be sent again, the next one-shot request should again be preceded by a ping, " + + "as a new 401 challenge would consume its content"); + assertTrue(requests.get(1).getBody().utf8().contains(PAYLOAD), "The second request should have its content"); + } + + private PlanBuilder.Plan planWithContent(AbstractWriteHandle content) { + PlanBuilder op = client.newRowManager().newPlanBuilder(); + return op.fromParam("myRows", "", op.colTypes(op.colType("a", "string"))).bindParam("myRows", content); + } + + private PlanBuilder.Plan planWritingDocuments(DocumentWriteSet writeSet) { + PlanBuilder op = client.newRowManager().newPlanBuilder(); + return op.fromParam("myDocs", "", op.docColTypes()).write().bindParam("myDocs", writeSet); + } + + private static byte[] contentAsJson() { + return ("[{\"a\":\"" + PAYLOAD + "\"}]").getBytes(StandardCharsets.UTF_8); + } + + private static JacksonHandle resendableHandle() { + return new JacksonHandle(new ObjectMapper().createArrayNode().addObject().put("a", PAYLOAD)); + } + + private static InputStreamHandle oneShotHandle(Format format) { + byte[] content = format == Format.JSON ? contentAsJson() : + (format == Format.XML ? "" + PAYLOAD + "" : PAYLOAD).getBytes(StandardCharsets.UTF_8); + return new InputStreamHandle(new ByteArrayInputStream(content)).withFormat(format); + } + + private void assertIsSentAgainWithContent() { + assertEquals(2, requests.size(), "Content that can be read again should still be sent again"); + assertTrue(requests.get(1).getBody().utf8().contains(PAYLOAD), "The second request should have the content"); + } + + private ResourceNotResendableException assertIsNotSentAgain(Executable call) { + Throwable thrown = null; + try { + call.execute(); + } catch (Throwable t) { + thrown = t; + } + + StringBuilder sent = new StringBuilder(); + for (int i = 0; i < requests.size(); i++) { + sent.append("; request ").append(i + 1) + .append(requests.get(i).getBody().utf8().contains(PAYLOAD) ? " had" : " DID NOT HAVE").append(" the content"); + } + assertEquals(1, requests.size(), "The request must not be sent again, as its content can only be read once" + sent); + return assertInstanceOf(ResourceNotResendableException.class, thrown, "Unexpected outcome: " + thrown); + } +}