This is an automated email from the ASF dual-hosted git repository.

jbonofre pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-java.git


The following commit(s) were added to refs/heads/main by this push:
     new aa4f57617 MINOR: Block instead of spinning while waiting for Flight 
handshake messages (#1506)
aa4f57617 is described below

commit aa4f576170308931d81e92231db89afabcf5418d
Author: Abdul Rawoof Khan <[email protected]>
AuthorDate: Thu Nov 26 20:19:19 2026 +0530

    MINOR: Block instead of spinning while waiting for Flight handshake 
messages (#1506)
    
    ## What's Changed
    
    `ServerAuthWrapper` gives the legacy `ServerAuthHandler` an iterator
    whose `next()` spins on `LinkedBlockingQueue.poll()` until the client
    sends a handshake message or closes the stream. `ServerAuthInterceptor`
    lets Handshake through without a token, so on a server configured with a
    legacy handler such as `BasicServerAuthHandler`, an unauthenticated
    client can open Handshake streams, send nothing, and keep one executor
    thread per stream at full CPU for as long as the stream stays open.
    `ClientAuthWrapper` spins the same way on the client while waiting for
    the server's reply.
    
    `next()` now blocks on `take()`. `onCompleted`/`onError` enqueue an
    end-of-stream marker so a waiting reader wakes up and throws the same
    exceptions as before, and `hasNext()` ignores the marker. Valid
    handshakes are unaffected.
    
    Measured against a `FlightServer` with `BasicServerAuthHandler`, with 4
    Handshake streams opened and left idle for 3 s:
    
    ```
    before: wall=3.04s, server executor CPU=8.09s
    after:  wall=3.03s, server executor CPU=0.01s
    ```
    
    `TestBasicAuth.handshakeBlocksWhileWaitingForClient` opens an idle
    Handshake and checks that the server thread is `WAITING`. It fails
    without the fix (`expected: <WAITING> but was: <RUNNABLE>`). The
    flight-core tests pass with the fix.
---
 .../arrow/flight/auth/ClientAuthWrapper.java       |  28 ++++--
 .../arrow/flight/auth/ServerAuthWrapper.java       |  30 +++---
 .../apache/arrow/flight/auth/TestBasicAuth.java    | 109 +++++++++++++++++++++
 3 files changed, 146 insertions(+), 21 deletions(-)

diff --git 
a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java
 
b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java
index 19d4f77a0..d3df09e6c 100644
--- 
a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java
+++ 
b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java
@@ -63,6 +63,9 @@ public class ClientAuthWrapper {
 
   private static class AuthObserver implements 
StreamObserver<HandshakeResponse> {
 
+    // Queued after the last message so a blocked reader wakes up when the 
server is done.
+    private static final byte[] END_OF_STREAM = new byte[0];
+
     private volatile StreamObserver<HandshakeRequest> responseObserver;
     private final LinkedBlockingQueue<byte[]> messages = new 
LinkedBlockingQueue<>();
     private final AuthSender sender = new AuthSender();
@@ -84,15 +87,19 @@ public class ClientAuthWrapper {
 
           @Override
           public byte[] next() {
-            while (!completed.isDone() || !messages.isEmpty()) {
-              byte[] bytes = messages.poll();
-              if (bytes == null) {
-                // busy wait.
-                continue;
-              } else {
-                return bytes;
-              }
+            final byte[] bytes;
+            try {
+              bytes = messages.take();
+            } catch (InterruptedException e) {
+              Thread.currentThread().interrupt();
+              // Fail the request stream, otherwise the server keeps waiting 
for a message from us.
+              sender.onError(e);
+              throw new RuntimeException(e);
+            }
+            if (bytes != END_OF_STREAM) {
+              return bytes;
             }
+            messages.add(END_OF_STREAM);
 
             if (completed.isCompletedExceptionally()) {
               // Preserve prior exception behavior
@@ -116,13 +123,15 @@ public class ClientAuthWrapper {
 
           @Override
           public boolean hasNext() {
-            return !messages.isEmpty();
+            final byte[] head = messages.peek();
+            return head != null && head != END_OF_STREAM;
           }
         };
 
     @Override
     public void onError(Throwable t) {
       completed.completeExceptionally(t);
+      messages.add(END_OF_STREAM);
     }
 
     private class AuthSender implements ClientAuthSender {
@@ -149,6 +158,7 @@ public class ClientAuthWrapper {
     @Override
     public void onCompleted() {
       completed.complete(true);
+      messages.add(END_OF_STREAM);
     }
   }
 }
diff --git 
a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java
 
b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java
index fba9f9bab..73a560a9d 100644
--- 
a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java
+++ 
b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java
@@ -70,9 +70,11 @@ public class ServerAuthWrapper {
 
   private static class AuthObserver implements 
StreamObserver<HandshakeRequest> {
 
+    // Queued after the last message so a blocked reader wakes up when the 
client is done.
+    private static final byte[] END_OF_STREAM = new byte[0];
+
     private final StreamObserver<HandshakeResponse> responseObserver;
     private volatile Future<?> future;
-    private volatile boolean completed = false;
     private final LinkedBlockingQueue<byte[]> messages = new 
LinkedBlockingQueue<>();
     private final AuthSender sender = new AuthSender();
 
@@ -92,26 +94,30 @@ public class ServerAuthWrapper {
 
           @Override
           public byte[] next() {
-            while (!completed || !messages.isEmpty()) {
-              byte[] bytes = messages.poll();
-              if (bytes == null) {
-                // busy wait.
-                continue;
-              }
-              return bytes;
+            final byte[] bytes;
+            try {
+              bytes = messages.take();
+            } catch (InterruptedException e) {
+              Thread.currentThread().interrupt();
+              throw new IllegalStateException("Interrupted while waiting for a 
message.", e);
+            }
+            if (bytes == END_OF_STREAM) {
+              messages.add(END_OF_STREAM);
+              throw new IllegalStateException("Requesting more messages than 
client sent.");
             }
-            throw new IllegalStateException("Requesting more messages than 
client sent.");
+            return bytes;
           }
 
           @Override
           public boolean hasNext() {
-            return !messages.isEmpty();
+            final byte[] head = messages.peek();
+            return head != null && head != END_OF_STREAM;
           }
         };
 
     @Override
     public void onError(Throwable t) {
-      completed = true;
+      messages.add(END_OF_STREAM);
       while (future == null) {
         /* busy wait */
       }
@@ -120,7 +126,7 @@ public class ServerAuthWrapper {
 
     @Override
     public void onCompleted() {
-      completed = true;
+      messages.add(END_OF_STREAM);
     }
 
     private class AuthSender implements ServerAuthSender {
diff --git 
a/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java
 
b/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java
index 0f202ba2d..61dd5f8ce 100644
--- 
a/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java
+++ 
b/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java
@@ -19,13 +19,23 @@ package org.apache.arrow.flight.auth;
 import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST;
 import static org.apache.arrow.flight.Location.forGrpcInsecure;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.fail;
 
 import com.google.common.collect.ImmutableList;
+import io.grpc.ManagedChannel;
+import io.grpc.ManagedChannelBuilder;
+import io.grpc.stub.StreamObserver;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Map;
 import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 import org.apache.arrow.flight.Criteria;
 import org.apache.arrow.flight.FlightClient;
 import org.apache.arrow.flight.FlightInfo;
@@ -35,6 +45,8 @@ import org.apache.arrow.flight.FlightStream;
 import org.apache.arrow.flight.FlightTestUtil;
 import org.apache.arrow.flight.NoOpFlightProducer;
 import org.apache.arrow.flight.Ticket;
+import org.apache.arrow.flight.impl.Flight.HandshakeResponse;
+import org.apache.arrow.flight.impl.FlightServiceGrpc;
 import org.apache.arrow.memory.BufferAllocator;
 import org.apache.arrow.memory.RootAllocator;
 import org.apache.arrow.util.AutoCloseables;
@@ -99,6 +111,103 @@ public class TestBasicAuth {
         });
   }
 
+  @Test
+  public void handshakeBlocksWhileWaitingForClient() throws Exception {
+    final ManagedChannel channel =
+        ManagedChannelBuilder.forAddress(LOCALHOST, 
server.getPort()).usePlaintext().build();
+    try {
+      // Open a handshake but never send a message, so the server waits for 
the first one.
+      FlightServiceGrpc.newStub(channel)
+          .handshake(
+              new StreamObserver<HandshakeResponse>() {
+                @Override
+                public void onNext(HandshakeResponse value) {}
+
+                @Override
+                public void onError(Throwable t) {}
+
+                @Override
+                public void onCompleted() {}
+              });
+
+      final Thread handshakeThread = awaitServerHandshakeThread();
+      assertNotNull(handshakeThread, "server handshake did not start");
+      Thread.sleep(200);
+      // The thread must park until a message arrives rather than spin on the 
queue.
+      assertEquals(Thread.State.WAITING, handshakeThread.getState());
+    } finally {
+      channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
+    }
+  }
+
+  @Test
+  public void interruptedClientHandshakeEndsServerStream() throws Exception {
+    final AtomicReference<Thread> serverThread = new AtomicReference<>();
+    try {
+      assertThrows(
+          RuntimeException.class,
+          () ->
+              client.authenticate(
+                  new ClientAuthHandler() {
+                    @Override
+                    public void authenticate(ClientAuthSender outgoing, 
Iterator<byte[]> incoming) {
+                      // Let the server park on our first message, then stop 
mid-handshake.
+                      serverThread.set(awaitServerHandshakeThread());
+                      Thread.currentThread().interrupt();
+                      incoming.next();
+                    }
+
+                    @Override
+                    public byte[] getCallToken() {
+                      return VALID_TOKEN;
+                    }
+                  }));
+    } finally {
+      // next() re-raises the flag before propagating, so clear it for the 
rest of the suite.
+      Thread.interrupted();
+    }
+    assertNotNull(serverThread.get(), "server handshake did not start");
+
+    // The interrupted client errors the request stream, so the server gives 
up on the message.
+    for (int i = 0; i < 100 && 
isWaitingForHandshakeMessage(serverThread.get()); i++) {
+      Thread.sleep(50);
+    }
+    assertFalse(
+        isWaitingForHandshakeMessage(serverThread.get()),
+        "server handshake stayed blocked after the client was interrupted");
+  }
+
+  private static Thread awaitServerHandshakeThread() {
+    for (int i = 0; i < 100; i++) {
+      for (Map.Entry<Thread, StackTraceElement[]> entry : 
Thread.getAllStackTraces().entrySet()) {
+        if (isWaitingForHandshakeMessage(entry.getValue())) {
+          return entry.getKey();
+        }
+      }
+      try {
+        Thread.sleep(50);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        return null;
+      }
+    }
+    return null;
+  }
+
+  private static boolean isWaitingForHandshakeMessage(Thread thread) {
+    return isWaitingForHandshakeMessage(thread.getStackTrace());
+  }
+
+  private static boolean isWaitingForHandshakeMessage(StackTraceElement[] 
stack) {
+    for (StackTraceElement frame : stack) {
+      if (frame.getClassName().startsWith(ServerAuthWrapper.class.getName())
+          && frame.getMethodName().equals("next")) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   @BeforeEach
   public void testSetup() throws IOException {
     client = FlightClient.builder(allocator, server.getLocation()).build();

Reply via email to