Skip to content
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

Server-side timeout mechanism #10360

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 175 additions & 0 deletions util/src/main/java/io/grpc/util/SerializingServerCall.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*
* Copyright 2017 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.grpc.util;

import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.Attributes;
import io.grpc.ExperimentalApi;
import io.grpc.ForwardingServerCall;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.Status;
import io.grpc.internal.SerializingExecutor;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;

/**
* A {@link ServerCall} that wraps around a non thread safe delegate and provides thread safe
* access by serializing everything on an executor.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2189")
class SerializingServerCall<ReqT, RespT> extends
Copy link
Author

Choose a reason for hiding this comment

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

This class is extracted from TransmitStatusRuntimeExceptionInterceptor.

ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private static final String ERROR_MSG = "Encountered error during serialized access";
private final SerializingExecutor serializingExecutor =
new SerializingExecutor(MoreExecutors.directExecutor());
private boolean closeCalled = false;

SerializingServerCall(ServerCall<ReqT, RespT> delegate) {
super(delegate);
}

@Override
public void sendMessage(final RespT message) {
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
SerializingServerCall.super.sendMessage(message);
}
});
}

@Override
public void request(final int numMessages) {
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
SerializingServerCall.super.request(numMessages);
}
});
}

@Override
public void sendHeaders(final Metadata headers) {
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
SerializingServerCall.super.sendHeaders(headers);
}
});
}

@Override
public void close(final Status status, final Metadata trailers) {
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
if (!closeCalled) {
closeCalled = true;

SerializingServerCall.super.close(status, trailers);
}
}
});
}

@Override
public boolean isReady() {
final SettableFuture<Boolean> retVal = SettableFuture.create();
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
retVal.set(SerializingServerCall.super.isReady());
}
});
try {
return retVal.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(ERROR_MSG, e);

Check warning on line 103 in util/src/main/java/io/grpc/util/SerializingServerCall.java

View check run for this annotation

Codecov / codecov/patch

util/src/main/java/io/grpc/util/SerializingServerCall.java#L102-L103

Added lines #L102 - L103 were not covered by tests
}
}

@Override
public boolean isCancelled() {
final SettableFuture<Boolean> retVal = SettableFuture.create();
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
retVal.set(SerializingServerCall.super.isCancelled());
}
});
try {
return retVal.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(ERROR_MSG, e);

Check warning on line 119 in util/src/main/java/io/grpc/util/SerializingServerCall.java

View check run for this annotation

Codecov / codecov/patch

util/src/main/java/io/grpc/util/SerializingServerCall.java#L118-L119

Added lines #L118 - L119 were not covered by tests
}
}

@Override
public void setMessageCompression(final boolean enabled) {
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
SerializingServerCall.super.setMessageCompression(enabled);
}
});
}

@Override
public void setCompression(final String compressor) {
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
SerializingServerCall.super.setCompression(compressor);
}
});
}

@Override
public Attributes getAttributes() {
final SettableFuture<Attributes> retVal = SettableFuture.create();
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
retVal.set(SerializingServerCall.super.getAttributes());
}
});
try {
return retVal.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(ERROR_MSG, e);

Check warning on line 155 in util/src/main/java/io/grpc/util/SerializingServerCall.java

View check run for this annotation

Codecov / codecov/patch

util/src/main/java/io/grpc/util/SerializingServerCall.java#L154-L155

Added lines #L154 - L155 were not covered by tests
}
}

@Nullable
@Override
public String getAuthority() {
final SettableFuture<String> retVal = SettableFuture.create();
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
retVal.set(SerializingServerCall.super.getAuthority());
}
});
try {
return retVal.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(ERROR_MSG, e);

Check warning on line 172 in util/src/main/java/io/grpc/util/SerializingServerCall.java

View check run for this annotation

Codecov / codecov/patch

util/src/main/java/io/grpc/util/SerializingServerCall.java#L171-L172

Added lines #L171 - L172 were not covered by tests
}
}
}
120 changes: 120 additions & 0 deletions util/src/main/java/io/grpc/util/ServerCallTimeoutInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright 2023 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.grpc.util;

import io.grpc.Context;
import io.grpc.ExperimentalApi;
import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;

/**
* An optional ServerInterceptor to stop server calls at best effort when the timeout is reached.
* In this way, it prevents problematic code from excessively using up all threads in the pool.
*
* <p>How to use: install it to your server using ServerBuilder#intercept(ServerInterceptor).
*
* <p>Limitation: it only applies the timeout to unary calls
* (long-running streaming calls are allowed, so they can run without this timeout limit).
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/10361")
public class ServerCallTimeoutInterceptor implements ServerInterceptor {

private final ServerTimeoutManager serverTimeoutManager;

public ServerCallTimeoutInterceptor(ServerTimeoutManager serverTimeoutManager) {
this.serverTimeoutManager = serverTimeoutManager;
}

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> serverCall,
Metadata metadata,
ServerCallHandler<ReqT, RespT> serverCallHandler) {
// Only intercepts unary calls because the timeout is inapplicable to streaming calls.
if (serverCall.getMethodDescriptor().getType().clientSendsOneMessage()) {
ServerCall<ReqT, RespT> serializingServerCall = new SerializingServerCall<>(serverCall);
Context.CancellableContext timeoutContext =
serverTimeoutManager.startTimeoutContext(serializingServerCall);
if (timeoutContext != null) {
return new TimeoutServerCallListener<>(
serverCallHandler.startCall(serializingServerCall, metadata),
timeoutContext,
serverTimeoutManager);
}
}
return serverCallHandler.startCall(serverCall, metadata);
}

/** A listener that intercepts RPC callbacks for timeout control. */
static class TimeoutServerCallListener<ReqT>
extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {

private final Context.CancellableContext context;
private final ServerTimeoutManager serverTimeoutManager;

private TimeoutServerCallListener(
ServerCall.Listener<ReqT> delegate,
Context.CancellableContext context,
ServerTimeoutManager serverTimeoutManager) {
super(delegate);
this.context = context;
this.serverTimeoutManager = serverTimeoutManager;
}

@Override
public void onMessage(ReqT message) {
serverTimeoutManager.runWithContext(context, () -> super.onMessage(message));
}

/**
* Adds interruption here because the application RPC method is called in halfClose(). See
* io.grpc.stub.ServerCalls.UnaryServerCallHandler.UnaryServerCallListener
*/
@Override
public void onHalfClose() {
serverTimeoutManager.runWithContextInterruptibly(context, super::onHalfClose);
}

@Override
public void onCancel() {
try {
serverTimeoutManager.runWithContext(context, super::onCancel);
} finally {
// Cancel the timeout when the call is finished.
context.close();
}
}

@Override
public void onComplete() {
try {
serverTimeoutManager.runWithContext(context, super::onComplete);
} finally {
// Cancel the timeout when the call is finished.
context.close();
}
}

@Override
public void onReady() {
serverTimeoutManager.runWithContext(context, super::onReady);
}
}
}
Loading