From 48f3197de5cbfe0cc0110d95b8d53e3d2c527fe4 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Mon, 30 Nov 2026 19:55:55 +0000
Subject: [PATCH] Preserve LDAP Search response order across Bind (#1350)

---
 opendj-server-legacy/src/main/java/org/opends/server/core/WorkQueueStrategy.java                                   |    9 +
 opendj-server-legacy/src/main/java/org/opends/server/api/ClientConnection.java                                     |   10 +
 opendj-server-legacy/src/main/java/org/opends/server/core/QueueingStrategy.java                                    |   11 +
 opendj-server-legacy/src/test/java/org/forgerock/opendj/reactive/LDAPBindResponseOrderTest.java                    |  309 ++++++++++++++++++++++++++++++++++
 opendj-server-legacy/src/main/java/org/opends/server/workflowelement/localbackend/LocalBackendSearchOperation.java |    3 
 opendj-server-legacy/src/main/java/org/opends/server/types/AbstractOperation.java                                  |    4 
 opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPClientConnection2.java                        |  187 ++++++++++++++++----
 opendj-server-legacy/src/main/java/org/opends/server/core/PersistentSearch.java                                    |    4 
 8 files changed, 498 insertions(+), 39 deletions(-)

diff --git a/opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPClientConnection2.java b/opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPClientConnection2.java
index 4e0438a..796e342 100644
--- a/opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPClientConnection2.java
+++ b/opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPClientConnection2.java
@@ -33,12 +33,17 @@
 import java.nio.channels.SocketChannel;
 import java.security.cert.Certificate;
 import java.util.ArrayDeque;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
@@ -66,6 +71,7 @@
 import org.forgerock.opendj.ldap.spi.LdapMessages.LdapRequestEnvelope;
 import org.opends.server.api.ClientConnection;
 import org.opends.server.api.ConnectionHandler;
+import org.opends.server.api.DirectoryThread;
 import org.opends.server.core.AbandonOperationBasis;
 import org.opends.server.core.AddOperationBasis;
 import org.opends.server.core.BindOperationBasis;
@@ -114,7 +120,9 @@
 import com.forgerock.reactive.ReactiveHandler;
 import com.forgerock.reactive.Stream;
 
+import io.reactivex.rxjava3.core.Completable;
 import io.reactivex.rxjava3.exceptions.Exceptions;
+import io.reactivex.rxjava3.subjects.CompletableSubject;
 
 /**
  * This class defines an LDAP client connection, which is a type of client connection that will be accepted by an
@@ -123,6 +131,16 @@
 public final class LDAPClientConnection2 extends ClientConnection implements TLSCapableConnection,
         ReactiveHandler<QueueingStrategy, LdapRequestEnvelope, Stream<Response>> {
     private static final String REACTIVE_OUT = "reactive.out";
+    private static final CancelRequest CANCEL_OPERATIONS_FOR_BIND =
+            new CancelRequest(true, INFO_CANCELED_BY_BIND_REQUEST.get());
+
+    /** Submit deferred Binds without making the Search writer wait for work-queue capacity. */
+    private static final ThreadPoolExecutor DEFERRED_BIND_SUBMISSIONS = new ThreadPoolExecutor(
+            0, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(32), task -> {
+                final Thread worker = new DirectoryThread(task, "LDAP deferred Bind submission");
+                worker.setDaemon(true);
+                return worker;
+            });
 
     /** The tracer object for the debug logger. */
     private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
@@ -155,6 +173,9 @@
     /** The set of all operations currently in progress on this connection. */
     private final ConcurrentHashMap<Integer, Operation> operationsInProgress;
 
+    /** Search responses can still be in flight after the operation leaves the work queue. */
+    private final Set<BlockingBackpressureSubscription> searchResponses = ConcurrentHashMap.newKeySet();
+
     /**
      * The number of operations performed on this connection. Used to compare with the resource limits of the network
      * group.
@@ -406,7 +427,7 @@
         // A persistent search is the other way around: its search operation is no longer in
         // progress once the search phase is over, and yet it still owes the client a response if
         // the server terminates it.
-        if (removeOperationInProgress(operation.getMessageID())
+        if (removeOperationInProgress(operation)
                 || hasPersistentSearch(operation.getMessageID())) {
             getAttachedResponses(operation).complete(operationToResponse(operation));
         }
@@ -768,7 +789,7 @@
         } catch (DirectoryException de) {
             logger.traceException(de);
 
-            operationsInProgress.remove(messageID);
+            operationsInProgress.remove(messageID, operation);
             lastCompletionTime.set(TimeThread.getTime());
 
             throw de;
@@ -791,7 +812,15 @@
      */
     @Override
     public boolean removeOperationInProgress(int messageID) {
-        Operation operation = operationsInProgress.remove(messageID);
+        return operationRemoved(operationsInProgress.remove(messageID));
+    }
+
+    @Override
+    public boolean removeOperationInProgress(Operation operation) {
+        return operationsInProgress.remove(operation.getMessageID(), operation) && operationRemoved(operation);
+    }
+
+    private boolean operationRemoved(Operation operation) {
         if (operation == null) {
             return false;
         }
@@ -910,19 +939,17 @@
                     operationsInProgress.remove(msgID);
                     lastCompletionTime.set(TimeThread.getTime());
                 }
-
-                for (PersistentSearch persistentSearch : getPersistentSearches()) {
-                    if (persistentSearch.getMessageID() == messageID) {
-                        continue;
-                    }
-
-                    persistentSearch.cancel();
-                    lastCompletionTime.set(TimeThread.getTime());
-                }
             } catch (Exception e) {
                 logger.traceException(e);
             }
         }
+        // A persistent search can be publishing to the transport while it is being cancelled.
+        for (PersistentSearch persistentSearch : getPersistentSearches()) {
+            if (persistentSearch.getMessageID() != messageID) {
+                persistentSearch.cancel();
+                lastCompletionTime.set(TimeThread.getTime());
+            }
+        }
     }
 
     @Override
@@ -997,8 +1024,13 @@
             cancelFirstRequestTimer();
         }
         final Publisher<Response> responses = subscriber -> {
+            final boolean search = message.getMessageType() == OP_TYPE_SEARCH_REQUEST;
             final BlockingBackpressureSubscription out =
-                    new BlockingBackpressureSubscription(connectionHandler.getMaxBlockedWriteTimeLimit(), subscriber);
+                    new BlockingBackpressureSubscription(connectionHandler.getMaxBlockedWriteTimeLimit(), subscriber,
+                            search);
+            if (search) {
+                searchResponses.add(out);
+            }
             try {
                 subscriber.onSubscribe(out);
                 if (!out.cancelled) {
@@ -1284,26 +1316,71 @@
 
         // Add the operation into the work queue.
         bindOp.setAttachment(REACTIVE_OUT, out);
-        try {
-            addOperationInProgress(queueingStrategy, bindOp);
-        } catch (DirectoryException de) {
-            logger.traceException(de);
-
-            final Result result = Responses.newBindResult(de.getResultCode());
-            setDetails(result, de, bindOp.getResponseControls());
-            out.complete(result);
-
-            // If it was a protocol error, then terminate the connection.
-            if (de.getResultCode() == ResultCode.PROTOCOL_ERROR) {
-                LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_BIND_PROTOCOL_ERROR.get(message.getMessageID(),
-                        de.getMessageObject());
-                disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg);
-            }
+        final List<Completable> searchHandoffs = new ArrayList<>();
+        for (BlockingBackpressureSubscription search : searchResponses) {
+            search.discardBufferedResponses();
+            searchHandoffs.add(search.searchTerminated);
         }
-
+        if (searchHandoffs.isEmpty()) {
+            enqueueBind(queueingStrategy, bindOp, out, false);
+        } else {
+            // Keep request admission closed until the old Search responses have reached the transport.
+            Completable.merge(searchHandoffs).subscribe(
+                    () -> submitDeferredBind(queueingStrategy, bindOp, out), out::terminate);
+        }
         return connectionValid;
     }
 
+    private void submitDeferredBind(QueueingStrategy queueingStrategy, BindOperationBasis bind,
+            BlockingBackpressureSubscription out) {
+        try {
+            DEFERRED_BIND_SUBMISSIONS.execute(() -> enqueueBind(queueingStrategy::enqueueDeferredRequest,
+                    bind, out, true));
+        } catch (RejectedExecutionException e) {
+            // The connection cannot continue with Search responses already abandoned and cleanup unavailable.
+            final ClosedChannelException failure = new ClosedChannelException();
+            failure.initCause(e);
+            out.terminate(failure);
+        }
+    }
+
+    private void enqueueBind(QueueingStrategy queueingStrategy, BindOperationBasis bind,
+            BlockingBackpressureSubscription out, boolean discardedSearches) {
+        if (out.cancelled) {
+            return;
+        }
+        if (!connectionValid) {
+            out.complete(null);
+            return;
+        }
+        try {
+            addOperationInProgress(queueingStrategy, bind);
+        } catch (DirectoryException de) {
+            setUnauthenticated();
+            setSASLAuthStateInfo(null);
+            if (discardedSearches && de.getResultCode() != ResultCode.PROTOCOL_ERROR) {
+                // The Bind did not reach a worker to cancel the operations whose responses were discarded.
+                cancelAllOperationsExcept(CANCEL_OPERATIONS_FOR_BIND, bind.getMessageID());
+            }
+            rejectBind(bind, out, de);
+        }
+    }
+
+    private void rejectBind(BindOperationBasis bind, BlockingBackpressureSubscription out, DirectoryException error) {
+        logger.traceException(error);
+        final Result result = Responses.newBindResult(error.getResultCode());
+        setDetails(result, error, bind.getResponseControls());
+        finishSaslBind();
+        finishBind();
+        out.complete(result);
+
+        if (error.getResultCode() == ResultCode.PROTOCOL_ERROR) {
+            LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_BIND_PROTOCOL_ERROR.get(bind.getMessageID(),
+                    error.getMessageObject());
+            disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg);
+        }
+    }
+
     /**
      * Processes the provided LDAP message as a compare request.
      *
@@ -1704,20 +1781,22 @@
      * Queues responses before publishing them. A persistent search can receive changes from several workers at once.
      * The bounded queue accepts concurrent producers, and only the drain calls the downstream subscriber.
      */
-    private static final class BlockingBackpressureSubscription implements Subscription {
+    private final class BlockingBackpressureSubscription implements Subscription {
         private static final int QUEUE_CAPACITY = 32;
         private final AtomicLong pendingRequests = new AtomicLong();
         private final AtomicInteger missedDrain = new AtomicInteger();
         private final ArrayDeque<Response> queue = new ArrayDeque<>(QUEUE_CAPACITY);
         private final Subscriber<? super Response> downstream;
         private final long writeTimeoutNanos;
+        private final CompletableSubject searchTerminated;
         private volatile boolean done;
         private Throwable error;
         private volatile boolean cancelled;
 
         BlockingBackpressureSubscription(final long maxBlockedWriteTimeLimit,
-                final Subscriber<? super Response> downstream) {
+                final Subscriber<? super Response> downstream, boolean search) {
             this.downstream = downstream;
+            searchTerminated = search ? CompletableSubject.create() : null;
             // Do not wait indefinitely.
             this.writeTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(
                     maxBlockedWriteTimeLimit == 0 ? 30000 : maxBlockedWriteTimeLimit);
@@ -1750,18 +1829,28 @@
                     if (response == null) {
                         break;
                     }
-                    downstream.onNext(response);
+                    try {
+                        downstream.onNext(response);
+                    } catch (RuntimeException | Error e) {
+                        finishSearch(e);
+                        throw e;
+                    }
                     emitted++;
                 }
 
                 if (cancelled) {
+                    finishSearch(null);
                     return;
                 }
                 if (done && isQueueEmpty()) {
-                    if (error != null) {
-                        downstream.onError(error);
-                    } else {
-                        downstream.onComplete();
+                    try {
+                        if (error != null) {
+                            downstream.onError(error);
+                        } else {
+                            downstream.onComplete();
+                        }
+                    } finally {
+                        finishSearch(error);
                     }
                     return;
                 }
@@ -1775,6 +1864,29 @@
             }
         }
 
+        private void finishSearch(Throwable failure) {
+            if (searchTerminated != null) {
+                if (failure == null) {
+                    searchTerminated.onComplete();
+                } else {
+                    searchTerminated.onError(failure);
+                }
+                searchResponses.remove(this);
+            }
+        }
+
+        private void discardBufferedResponses() {
+            synchronized (queue) {
+                queue.clear();
+                if (done) {
+                    queue.notifyAll();
+                } else {
+                    finish(null);
+                }
+            }
+            drain();
+        }
+
         private Response poll() {
             synchronized (queue) {
                 final Response response = queue.pollFirst();
@@ -1863,6 +1975,9 @@
                 queue.clear();
                 queue.notifyAll();
             }
+            if (searchTerminated != null) {
+                drain();
+            }
         }
     }
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/api/ClientConnection.java b/opendj-server-legacy/src/main/java/org/opends/server/api/ClientConnection.java
index 376578b..555474d 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/api/ClientConnection.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/api/ClientConnection.java
@@ -644,6 +644,16 @@
    */
   public abstract boolean removeOperationInProgress(int messageID);
 
+  /**
+   * Removes a completed operation from this connection.
+   *
+   * @param operation The operation to remove.
+   * @return Whether the operation was removed.
+   */
+  public boolean removeOperationInProgress(Operation operation)
+  {
+    return removeOperationInProgress(operation.getMessageID());
+  }
 
 
   /**
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/core/PersistentSearch.java b/opendj-server-legacy/src/main/java/org/opends/server/core/PersistentSearch.java
index 5d97e32..c12009a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/core/PersistentSearch.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/core/PersistentSearch.java
@@ -178,10 +178,12 @@
       // Cancel any other persistent searches which are associated
       // with this one. For example, a persistent search may be
       // distributed across multiple proxies.
+      final long operationID = searchOperation.getOperationID();
       for (PersistentSearch psearch : searchOperation.getClientConnection()
           .getPersistentSearches())
       {
-        if (psearch.getMessageID() == getMessageID())
+        // A later operation on this connection can reuse the LDAP message ID.
+        if (psearch.searchOperation.getOperationID() == operationID)
         {
           cancel(psearch);
         }
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/core/QueueingStrategy.java b/opendj-server-legacy/src/main/java/org/opends/server/core/QueueingStrategy.java
index 534ecea..a823e52 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/core/QueueingStrategy.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/core/QueueingStrategy.java
@@ -13,6 +13,7 @@
  *
  * Copyright 2006-2008 Sun Microsystems, Inc.
  * Portions Copyright 2013-2015 ForgeRock AS.
+ * Portions Copyright 2026 3A Systems, LLC.
  */
 package org.opends.server.core;
 
@@ -33,4 +34,14 @@
    */
   void enqueueRequest(Operation operation) throws DirectoryException;
 
+  /**
+   * Submits a request after its response-ordering dependencies have finished.
+   *
+   * @param operation Operation to put in the queue.
+   * @throws DirectoryException If the request cannot be submitted.
+   */
+  default void enqueueDeferredRequest(Operation operation) throws DirectoryException
+  {
+    enqueueRequest(operation);
+  }
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/core/WorkQueueStrategy.java b/opendj-server-legacy/src/main/java/org/opends/server/core/WorkQueueStrategy.java
index acafb2b..bea0d2e 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/core/WorkQueueStrategy.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/core/WorkQueueStrategy.java
@@ -13,9 +13,11 @@
  *
  * Copyright 2006-2008 Sun Microsystems, Inc.
  * Portions Copyright 2013 ForgeRock AS.
+ * Portions Copyright 2026 3A Systems, LLC.
  */
 package org.opends.server.core;
 
+import org.forgerock.opendj.ldap.ResultCode;
 import org.opends.server.types.DirectoryException;
 import org.opends.server.types.Operation;
 
@@ -36,4 +38,11 @@
   public void enqueueRequest(Operation operation) throws DirectoryException {
     DirectoryServer.enqueueRequest(operation);
   }
+
+  @Override
+  public void enqueueDeferredRequest(Operation operation) throws DirectoryException {
+    if (!DirectoryServer.tryEnqueueRequest(operation)) {
+      throw new DirectoryException(ResultCode.BUSY, ResultCode.BUSY.getName());
+    }
+  }
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/types/AbstractOperation.java b/opendj-server-legacy/src/main/java/org/opends/server/types/AbstractOperation.java
index 5f5c67c..4f61277 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/types/AbstractOperation.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/types/AbstractOperation.java
@@ -13,7 +13,7 @@
  *
  * Copyright 2006-2010 Sun Microsystems, Inc.
  * Portions Copyright 2011-2016 ForgeRock AS.
- * Portions Copyright 2023-2025 3A Systems, LLC.
+ * Portions Copyright 2023-2026 3A Systems, LLC.
  */
 package org.opends.server.types;
 
@@ -493,7 +493,7 @@
   {
     // Notify the client connection that this operation is complete
     // and that it no longer needs to be retained.
-    clientConnection.removeOperationInProgress(messageID);
+    clientConnection.removeOperationInProgress(this);
     completed=true;
   }
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/workflowelement/localbackend/LocalBackendSearchOperation.java b/opendj-server-legacy/src/main/java/org/opends/server/workflowelement/localbackend/LocalBackendSearchOperation.java
index 7b47d98..c253e2f 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/workflowelement/localbackend/LocalBackendSearchOperation.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/workflowelement/localbackend/LocalBackendSearchOperation.java
@@ -250,6 +250,9 @@
         }
         backend.registerPersistentSearch(persistentSearch);
         persistentSearch.enable();
+
+        // A Bind can cancel the Search while it is being registered with the backend.
+        checkIfCanceled(false);
       }
 
 
diff --git a/opendj-server-legacy/src/test/java/org/forgerock/opendj/reactive/LDAPBindResponseOrderTest.java b/opendj-server-legacy/src/test/java/org/forgerock/opendj/reactive/LDAPBindResponseOrderTest.java
new file mode 100644
index 0000000..7f9492a
--- /dev/null
+++ b/opendj-server-legacy/src/test/java/org/forgerock/opendj/reactive/LDAPBindResponseOrderTest.java
@@ -0,0 +1,309 @@
+/*
+ * The contents of this file are subject to the terms of the Common Development and
+ * Distribution License (the License). You may not use this file except in compliance with the
+ * License.
+ *
+ * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
+ * specific language governing permission and limitations under the License.
+ *
+ * When distributing Covered Software, include this CDDL Header Notice in each file and include
+ * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
+ * Header, with the fields enclosed by brackets [] replaced by your own identifying
+ * information: "Portions copyright [year] [name of copyright owner]".
+ *
+ * Copyright 2026 3A Systems, LLC.
+ */
+package org.forgerock.opendj.reactive;
+
+import static org.forgerock.opendj.ldap.spi.LdapMessages.newRequestEnvelope;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Collections;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import io.reactivex.rxjava3.subscribers.TestSubscriber;
+import org.forgerock.opendj.io.ASN1;
+import org.forgerock.opendj.ldap.ByteString;
+import org.forgerock.opendj.ldap.ByteStringBuilder;
+import org.forgerock.opendj.ldap.DereferenceAliasesPolicy;
+import org.forgerock.opendj.ldap.LDAPClientContext;
+import org.forgerock.opendj.ldap.ResultCode;
+import org.forgerock.opendj.ldap.SearchScope;
+import org.forgerock.opendj.ldap.responses.BindResult;
+import org.forgerock.opendj.ldap.responses.Response;
+import org.forgerock.opendj.ldap.responses.SearchResultEntry;
+import org.forgerock.opendj.ldap.spi.LdapMessages.LdapRequestEnvelope;
+import org.opends.server.DirectoryServerTestCase;
+import org.opends.server.TestCaseUtils;
+import org.opends.server.core.DirectoryServer;
+import org.opends.server.core.PersistentSearch;
+import org.opends.server.core.QueueingStrategy;
+import org.opends.server.core.SearchOperation;
+import org.opends.server.protocols.ldap.BindRequestProtocolOp;
+import org.opends.server.protocols.ldap.LDAPFilter;
+import org.opends.server.protocols.ldap.LDAPMessage;
+import org.opends.server.protocols.ldap.ProtocolOp;
+import org.opends.server.protocols.ldap.SearchRequestProtocolOp;
+import org.opends.server.types.AuthenticationInfo;
+import org.opends.server.types.DirectoryException;
+import org.opends.server.types.DisconnectReason;
+import org.opends.server.types.Operation;
+import org.opends.server.workflowelement.localbackend.LocalBackendSearchOperation;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+/** Checks Bind and Search response ordering with a controlled subscriber and work queue. */
+@Test(groups = { "precommit" }, sequential = true)
+public class LDAPBindResponseOrderTest extends DirectoryServerTestCase {
+    private LDAPClientConnection2 connection;
+
+    @BeforeClass
+    public void startServer() throws Exception {
+        TestCaseUtils.startServer();
+    }
+
+    @BeforeMethod
+    public void openConnection() {
+        final LDAPConnectionHandler2 handler = DirectoryServer.getConnectionHandlers().stream()
+                .filter(LDAPConnectionHandler2.class::isInstance)
+                .map(LDAPConnectionHandler2.class::cast)
+                .findFirst().orElseThrow();
+        final LDAPClientContext context = mock(LDAPClientContext.class);
+        final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 389);
+        when(context.getPeerAddress()).thenReturn(address);
+        when(context.getLocalAddress()).thenReturn(address);
+        connection = new LDAPClientConnection2(handler, context, "LDAP", false);
+    }
+
+    @AfterMethod
+    public void closeConnection() {
+        connection.disconnect(DisconnectReason.CLIENT_DISCONNECT, false, null);
+    }
+
+    @DataProvider
+    public Object[][] bindResults() {
+        return new Object[][] {
+            { ResultCode.SUCCESS, true }, { ResultCode.BUSY, true }, { ResultCode.BUSY, false }
+        };
+    }
+
+    @Test(dataProvider = "bindResults")
+    public void bindWaitsForAnOrdinarySearchResponseHandoff(ResultCode expected, boolean searchCompleted)
+            throws Exception {
+        final PausedSearchResponses searchResponses = new PausedSearchResponses();
+        final AtomicBoolean searchHandedOffBeforeBind = new AtomicBoolean();
+        final TestSubscriber<Response> bindResponses = new TestSubscriber<Response>() {
+            @Override
+            public void onNext(Response response) {
+                searchHandedOffBeforeBind.set(searchResponses.responseHandedOff);
+                super.onNext(response);
+            }
+        };
+        try {
+            final SearchOperation search = submitSearch(1, searchResponses);
+            final org.opends.server.types.SearchResultEntry entry = searchEntry();
+            final CompletableFuture<Void> firstEntry =
+                    CompletableFuture.runAsync(() -> connection.sendSearchEntry(search, entry));
+            searchResponses.responseStarted.get(5, TimeUnit.SECONDS);
+
+            connection.sendSearchEntry(search, entry);
+            if (searchCompleted) {
+                search.setResultCode(ResultCode.SUCCESS);
+                search.sendSearchResultDone();
+                search.operationCompleted();
+                assertNull(connection.getOperationInProgress(1));
+            }
+
+            final LdapRequestEnvelope bindRequest = bindRequest();
+            final QueueingStrategy queue = operation -> {
+                if (expected == ResultCode.BUSY) {
+                    throw new DirectoryException(ResultCode.BUSY, ResultCode.BUSY.getName());
+                }
+                operation.run();
+                operation.operationCompleted();
+            };
+            // The request handler must return even while the earlier writer remains in the subscriber.
+            CompletableFuture.runAsync(() -> connection.handle(queue, bindRequest).subscribe(bindResponses))
+                    .get(5, TimeUnit.SECONDS);
+            bindResponses.assertEmpty();
+
+            searchResponses.finishResponse.complete(null);
+            firstEntry.get(5, TimeUnit.SECONDS);
+            bindResponses.awaitDone(5, TimeUnit.SECONDS)
+                    .assertValue(response -> response instanceof BindResult
+                            && ((BindResult) response).getResultCode() == expected)
+                    .assertComplete().assertNoErrors();
+            assertTrue(searchHandedOffBeforeBind.get(), "BindResponse arrived before the Search handoff");
+            searchResponses.request(Long.MAX_VALUE);
+            searchResponses.assertValueCount(1).assertValueAt(0, SearchResultEntry.class::isInstance)
+                    .assertComplete().assertNoErrors();
+            if (!searchCompleted) {
+                assertNotNull(search.getCancelRequest(), "The rejected Bind left a Search without its response stream");
+                assertNull(connection.getOperationInProgress(1));
+            }
+
+            final TestSubscriber<Response> nextResponses = new TestSubscriber<>();
+            try {
+                final SearchOperation nextSearch = submitSearch(1, nextResponses);
+                assertNotNull(nextSearch);
+                if (!searchCompleted) {
+                    search.operationCompleted();
+                    assertSame(connection.getOperationInProgress(1), nextSearch);
+                }
+            } finally {
+                nextResponses.cancel();
+            }
+        } finally {
+            searchResponses.finishResponse.complete(null);
+            bindResponses.cancel();
+            searchResponses.cancel();
+        }
+    }
+
+    @Test
+    public void disconnectCompletesADeferredBindWithoutEnqueueingIt() throws Exception {
+        final PausedSearchResponses searchResponses = new PausedSearchResponses();
+        final TestSubscriber<Response> bindResponses = new TestSubscriber<>();
+        try {
+            final SearchOperation search = submitSearch(1, searchResponses);
+            final org.opends.server.types.SearchResultEntry entry = searchEntry();
+            final CompletableFuture<Void> firstEntry =
+                    CompletableFuture.runAsync(() -> connection.sendSearchEntry(search, entry));
+            searchResponses.responseStarted.get(5, TimeUnit.SECONDS);
+
+            final LdapRequestEnvelope bindRequest = bindRequest();
+            final QueueingStrategy queue = operation -> fail("Disconnected Bind reached the work queue");
+            CompletableFuture.runAsync(() -> connection.handle(queue, bindRequest).subscribe(bindResponses))
+                    .get(5, TimeUnit.SECONDS);
+            bindResponses.assertEmpty();
+            connection.disconnect(DisconnectReason.CLIENT_DISCONNECT, false, null);
+
+            searchResponses.finishResponse.complete(null);
+            firstEntry.get(5, TimeUnit.SECONDS);
+            bindResponses.awaitDone(5, TimeUnit.SECONDS).assertResult();
+        } finally {
+            searchResponses.finishResponse.complete(null);
+            searchResponses.cancel();
+            bindResponses.cancel();
+        }
+    }
+
+    private static final class PausedSearchResponses extends TestSubscriber<Response> {
+        private final CompletableFuture<Void> responseStarted = new CompletableFuture<>();
+        private final CompletableFuture<Void> finishResponse = new CompletableFuture<>();
+        private volatile boolean responseHandedOff;
+
+        PausedSearchResponses() {
+            super(1);
+        }
+
+        @Override
+        public void onNext(Response response) {
+            responseStarted.complete(null);
+            finishResponse.join();
+            super.onNext(response);
+            responseHandedOff = true;
+        }
+    }
+
+    @Test
+    public void queueRejectedBindWithoutSearchClearsAuthorizationAndSaslState() throws Exception {
+        connection.setAuthenticationInfo(new AuthenticationInfo(
+                TestCaseUtils.makeEntry("dn: cn=bound-user", "objectClass: top", "cn: bound-user"), false));
+        connection.setSASLAuthStateInfo(new Object());
+        assertTrue(connection.getAuthenticationInfo().isAuthenticated());
+
+        final TestSubscriber<Response> bindResponses = new TestSubscriber<>();
+        final AtomicReference<AuthenticationInfo> authenticationAtResponse = new AtomicReference<>();
+        final AtomicReference<Object> saslStateAtResponse = new AtomicReference<>();
+        connection.handle(operation -> {
+            throw new DirectoryException(ResultCode.BUSY, ResultCode.BUSY.getName());
+        }, bindRequest()).onNext(response -> {
+            authenticationAtResponse.set(connection.getAuthenticationInfo());
+            saslStateAtResponse.set(connection.getSASLAuthStateInfo());
+        }).subscribe(bindResponses);
+
+        bindResponses.assertValue(response -> response instanceof BindResult
+                && ((BindResult) response).getResultCode() == ResultCode.BUSY).assertComplete().assertNoErrors();
+        assertFalse(authenticationAtResponse.get().isAuthenticated());
+        assertNull(authenticationAtResponse.get().getAuthorizationDN());
+        assertNull(saslStateAtResponse.get());
+        final TestSubscriber<Response> searchResponses = new TestSubscriber<>();
+        try {
+            assertNotNull(submitSearch(1, searchResponses));
+            assertFalse(connection.getAuthenticationInfo().isAuthenticated());
+        } finally {
+            searchResponses.cancel();
+        }
+    }
+
+    @Test
+    public void latePersistentSearchCancellationKeepsReplacementWithReusedMessageId() throws Exception {
+        final TestSubscriber<Response> originalResponses = new TestSubscriber<>();
+        final TestSubscriber<Response> replacementResponses = new TestSubscriber<>();
+        final SearchOperation original = submitSearch(1, originalResponses);
+        original.operationCompleted();
+        final SearchOperation replacement = submitSearch(1, replacementResponses);
+
+        // Backend registrations can wrap the same logical operation independently.
+        final PersistentSearch oldSearch = new PersistentSearch(
+                new LocalBackendSearchOperation(original), Collections.emptySet(), true, false);
+        final PersistentSearch sibling = new PersistentSearch(
+                new LocalBackendSearchOperation(original), Collections.emptySet(), true, false);
+        final PersistentSearch replacementSearch = new PersistentSearch(
+                new LocalBackendSearchOperation(replacement), Collections.emptySet(), true, false);
+        replacementSearch.enable();
+        oldSearch.enable();
+        sibling.enable();
+        try {
+            oldSearch.cancel();
+
+            assertEquals(connection.getPersistentSearches(), Collections.singletonList(replacementSearch));
+        } finally {
+            connection.getPersistentSearches().forEach(PersistentSearch::cancel);
+            originalResponses.cancel();
+            replacementResponses.cancel();
+            replacement.operationCompleted();
+        }
+    }
+
+    private static org.opends.server.types.SearchResultEntry searchEntry() throws Exception {
+        return new org.opends.server.types.SearchResultEntry(
+                TestCaseUtils.makeEntry("dn: cn=test", "objectClass: top", "cn: test"));
+    }
+
+    private static LdapRequestEnvelope bindRequest() throws IOException {
+        return request(2, new BindRequestProtocolOp(ByteString.empty(), 3, ByteString.empty()));
+    }
+
+    private SearchOperation submitSearch(int messageId, TestSubscriber<Response> responses) throws Exception {
+        final AtomicReference<Operation> operation = new AtomicReference<>();
+        final SearchRequestProtocolOp search = new SearchRequestProtocolOp(ByteString.empty(),
+                SearchScope.BASE_OBJECT, DereferenceAliasesPolicy.NEVER, 0, 0, false,
+                LDAPFilter.decode("(objectClass=*)"), Collections.emptySet());
+        connection.handle(operation::set, request(messageId, search)).subscribe(responses);
+        return (SearchOperation) operation.get();
+    }
+
+    private static LdapRequestEnvelope request(int messageId, ProtocolOp protocolOp) throws IOException {
+        final ByteStringBuilder encoded = new ByteStringBuilder();
+        new LDAPMessage(messageId, protocolOp).write(ASN1.getWriter(encoded));
+        return newRequestEnvelope(protocolOp.getType(), messageId, 3, null, ASN1.getReader(encoded.toByteString()));
+    }
+}

--
Gitblit v1.10.0