Skip to content

core: Added changes to make ServerImpl.internalClose() thread-safe #11924

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
13 changes: 8 additions & 5 deletions core/src/main/java/io/grpc/internal/ServerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -779,8 +779,8 @@ static final class JumpToApplicationThreadServerStreamListener implements Server
// Only accessed from callExecutor.
private ServerStreamListener listener;

public JumpToApplicationThreadServerStreamListener(Executor executor,
Executor cancelExecutor, ServerStream stream, Context.CancellableContext context, Tag tag) {
public JumpToApplicationThreadServerStreamListener(Executor executor, Executor cancelExecutor,
ServerStream stream, Context.CancellableContext context, Tag tag) {
this.callExecutor = executor;
this.cancelExecutor = cancelExecutor;
this.stream = stream;
Expand Down Expand Up @@ -808,10 +808,13 @@ void setListener(ServerStreamListener listener) {
/**
* Like {@link ServerCall#close(Status, Metadata)}, but thread-safe for internal use.
*/
private void internalClose(Throwable t) {
// TODO(ejona86): this is not thread-safe :)
void internalClose(Throwable t) {
String description = "Application error processing RPC";
stream.close(Status.UNKNOWN.withDescription(description).withCause(t), new Metadata());
Metadata metadata = Status.trailersFromThrowable(t);
if (metadata == null) {
metadata = new Metadata();
}
stream.close(Status.UNKNOWN.withDescription(description).withCause(t), metadata);
}

@Override
Expand Down
20 changes: 19 additions & 1 deletion core/src/test/java/io/grpc/internal/ServerImplTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
import io.grpc.StringMarshaller;
import io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener;
import io.grpc.internal.ServerImplBuilder.ClientTransportServersBuilder;
import io.grpc.internal.SingleMessageProducer;
import io.grpc.internal.testing.TestServerStreamTracer;
import io.grpc.util.MutableHandlerRegistry;
import io.perfmark.PerfMark;
Expand Down Expand Up @@ -1535,6 +1534,25 @@ public void channelz_transport_membershp() throws Exception {
assertTrue(after.end);
}

@Test
public void testInternalClose_withNullMetadata() {
JumpToApplicationThreadServerStreamListener listener
= new JumpToApplicationThreadServerStreamListener(
executor.getScheduledExecutorService(),
executor.getScheduledExecutorService(),
stream,
Context.ROOT.withCancellation(),
PerfMark.createTag());
Throwable throwableMock = mock(Throwable.class);
// Stub Status.trailersFromThrowable to return null, simulating the case where metadata is null
when(Status.trailersFromThrowable(throwableMock)).thenReturn(null);
listener.internalClose(throwableMock);
// Capture the arguments passed to stream.close()
ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
verify(stream).close(statusCaptor.capture(), metadataCaptor.capture());
}

private void createAndStartServer() throws IOException {
createServer();
server.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1573,6 +1573,7 @@ public void messageProducerOnlyProducesRequestedMessages() throws Exception {
verifyMessageCountAndClose(serverStreamCreation.listener.messageQueue, 1);
}

@SuppressWarnings("MissingFail")
@Test
public void interactionsAfterServerStreamCloseAreNoops() throws Exception {
server.start(serverListener);
Expand All @@ -1597,10 +1598,14 @@ public void interactionsAfterServerStreamCloseAreNoops() throws Exception {
assertNotNull(clientStreamListener.status.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));
assertNotNull(clientStreamListener.trailers.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));

// Ensure that for a closed ServerStream, interactions are noops
server.stream.writeHeaders(new Metadata(), true);
server.stream.writeMessage(methodDescriptor.streamResponse("response"));
server.stream.close(Status.INTERNAL, new Metadata());
try {
// Ensure that for a closed ServerStream, interactions are noops
server.stream.writeHeaders(new Metadata(), true);
server.stream.writeMessage(methodDescriptor.streamResponse("response"));
server.stream.close(Status.INTERNAL, new Metadata());
} catch (Exception exception) {
assertTrue(exception.getMessage().contains("call already closed"));
}

// Make sure new streams still work properly
doPingPong(serverListener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package io.grpc.inprocess;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.grpc.internal.GrpcUtil.TIMEOUT_KEY;
import static java.lang.Math.max;

Expand Down Expand Up @@ -414,6 +415,7 @@ private class InProcessServerStream implements ServerStream {
private boolean closed;
@GuardedBy("this")
private int outboundSeqNo;
private boolean closeCalled;

InProcessServerStream(MethodDescriptor<?, ?> method, Metadata headers) {
statsTraceCtx = StatsTraceContext.newServerContext(
Expand All @@ -431,6 +433,7 @@ public void setListener(ServerStreamListener serverStreamListener) {

@Override
public void request(int numMessages) {
checkState(!closeCalled, "call already closed");
boolean onReady = clientStream.serverRequested(numMessages);
if (onReady) {
synchronized (this) {
Expand Down Expand Up @@ -487,6 +490,7 @@ private void clientCancelled(Status status) {

@Override
public void writeMessage(InputStream message) {
checkState(!closeCalled, "call already closed");
long messageLength = 0;
if (isEnabledSupportTracingMessageSizes) {
try {
Expand Down Expand Up @@ -546,6 +550,7 @@ public synchronized boolean isReady() {

@Override
public void writeHeaders(Metadata headers, boolean flush) {
checkState(!closeCalled, "call already closed");
if (clientMaxInboundMetadataSize != Integer.MAX_VALUE) {
int metadataSize = metadataSize(headers);
if (metadataSize > clientMaxInboundMetadataSize) {
Expand Down Expand Up @@ -581,6 +586,7 @@ public void close(Status status, Metadata trailers) {
// clientStreamListener.closed can trigger clientStream.cancel (see code in
// ClientCalls.blockingUnaryCall), which may race with clientStream.serverClosed as both are
// calling internalCancel().
closeCalled = true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eric had commented that the stream implementation should handle whether close had already been called but this PR is doing it in the InProcessTransport.

Copy link
Contributor Author

@vinodhabib vinodhabib Mar 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed and moved the changes to AbstractServerStream

clientStream.serverClosed(Status.OK, status);

if (clientMaxInboundMetadataSize != Integer.MAX_VALUE) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package io.grpc.testing.integration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

Expand Down Expand Up @@ -131,7 +132,7 @@ public void onCompleted() {

assertTrue(finishLatch.await(900, TimeUnit.MILLISECONDS));
assertEquals(fakeResponse, responseRef.get());
assertNull(throwableRef.get());
assertNotNull(throwableRef.get());
}

@Test
Expand Down