
org.glowroot.agent.shaded.grpc.stub.ClientCalls Maven / Gradle / Ivy
Show all versions of glowroot-agent-it-harness Show documentation
/*
* Copyright 2014, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.glowroot.agent.shaded.grpc.stub;
import org.glowroot.agent.shaded.google.common.base.Preconditions;
import org.glowroot.agent.shaded.google.common.base.Throwables;
import org.glowroot.agent.shaded.google.common.util.concurrent.AbstractFuture;
import org.glowroot.agent.shaded.google.common.util.concurrent.ListenableFuture;
import org.glowroot.agent.shaded.grpc.CallOptions;
import org.glowroot.agent.shaded.grpc.Channel;
import org.glowroot.agent.shaded.grpc.ClientCall;
import org.glowroot.agent.shaded.grpc.Metadata;
import org.glowroot.agent.shaded.grpc.MethodDescriptor;
import org.glowroot.agent.shaded.grpc.Status;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import org.glowroot.agent.jul.Level;
import org.glowroot.agent.jul.Logger;
import javax.annotation.Nullable;
/**
* Utility functions for processing different call idioms. We have one-to-one correspondence
* between utilities in this class and the potential signatures in a generated stub class so
* that the runtime can vary behavior without requiring regeneration of the stub.
*/
public class ClientCalls {
private static final Logger log = Logger.getLogger(ClientCalls.class.getName());
// Prevent instantiation
private ClientCalls() {}
/**
* Executes a unary call with a response {@link StreamObserver}.
*/
public static void asyncUnaryCall(
ClientCall call,
ReqT param,
StreamObserver observer) {
asyncUnaryRequestCall(call, param, observer, false);
}
/**
* Executes a server-streaming call with a response {@link StreamObserver}.
*/
public static void asyncServerStreamingCall(
ClientCall call,
ReqT param,
StreamObserver responseObserver) {
asyncUnaryRequestCall(call, param, responseObserver, true);
}
/**
* Executes a client-streaming call returning a {@link StreamObserver} for the request messages.
* @return request stream observer.
*/
public static StreamObserver asyncClientStreamingCall(
ClientCall call,
StreamObserver responseObserver) {
return asyncStreamingRequestCall(call, responseObserver, false);
}
/**
* Executes a bidi-streaming call.
* @return request stream observer.
*/
public static StreamObserver asyncBidiStreamingCall(
ClientCall call, StreamObserver responseObserver) {
return asyncStreamingRequestCall(call, responseObserver, true);
}
/**
* Executes a unary call and blocks on the response.
* @return the single response message.
*/
public static RespT blockingUnaryCall(ClientCall call, ReqT param) {
try {
return getUnchecked(futureUnaryCall(call, param));
} catch (Throwable t) {
call.cancel();
throw Throwables.propagate(t);
}
}
/**
* Executes a unary call and blocks on the response.
*
* @return the single response message.
*/
public static RespT blockingUnaryCall(
Channel channel, MethodDescriptor method, CallOptions callOptions, ReqT param) {
ThreadlessExecutor executor = new ThreadlessExecutor();
ClientCall call = channel.newCall(method, callOptions.withExecutor(executor));
try {
ListenableFuture responseFuture = futureUnaryCall(call, param);
while (!responseFuture.isDone()) {
try {
executor.waitAndDrain();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Status.CANCELLED.withCause(e).asRuntimeException();
}
}
return getUnchecked(responseFuture);
} catch (Throwable t) {
call.cancel();
throw Throwables.propagate(t);
}
}
/**
* Executes a server-streaming call returning a blocking {@link Iterator} over the
* response stream.
* @return an iterator over the response stream.
*/
// TODO(louiscryan): Not clear if we want to use this idiom for 'simple' stubs.
public static Iterator blockingServerStreamingCall(
ClientCall call, ReqT param) {
BlockingResponseStream result = new BlockingResponseStream(call);
asyncUnaryRequestCall(call, param, result.listener(), true);
return result;
}
/**
* Executes a server-streaming call returning a blocking {@link Iterator} over the
* response stream.
*
* @return an iterator over the response stream.
*/
// TODO(louiscryan): Not clear if we want to use this idiom for 'simple' stubs.
public static Iterator blockingServerStreamingCall(
Channel channel, MethodDescriptor method, CallOptions callOptions, ReqT param) {
ThreadlessExecutor executor = new ThreadlessExecutor();
ClientCall call = channel.newCall(method, callOptions.withExecutor(executor));
BlockingResponseStream result = new BlockingResponseStream(call, executor);
asyncUnaryRequestCall(call, param, result.listener(), true);
return result;
}
/**
* Executes a unary call and returns a {@link ListenableFuture} to the response.
*
* @return a future for the single response message.
*/
public static ListenableFuture futureUnaryCall(
ClientCall call,
ReqT param) {
GrpcFuture responseFuture = new GrpcFuture(call);
asyncUnaryRequestCall(call, param, new UnaryStreamToFuture(responseFuture), false);
return responseFuture;
}
/**
* Returns the result of calling {@link Future#get()} interruptably on a task known not to throw a
* checked exception.
*
* If interrupted, the interrupt is restored before throwing an exception..
*
* @throws java.util.concurrent.CancellationException
* if {@code get} throws a {@code CancellationException}.
* @throws org.glowroot.agent.shaded.grpc.StatusRuntimeException if {@code get} throws an {@link ExecutionException}
* or an {@link InterruptedException}.
*/
private static V getUnchecked(Future future) {
try {
return future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Status.CANCELLED.withCause(e).asRuntimeException();
} catch (ExecutionException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
}
private static void asyncUnaryRequestCall(
ClientCall call, ReqT param, StreamObserver responseObserver,
boolean streamingResponse) {
asyncUnaryRequestCall(call, param,
new StreamObserverToCallListenerAdapter(call, responseObserver, streamingResponse),
streamingResponse);
}
private static void asyncUnaryRequestCall(
ClientCall call,
ReqT param,
ClientCall.Listener responseListener,
boolean streamingResponse) {
startCall(call, responseListener, streamingResponse);
try {
call.sendMessage(param);
call.halfClose();
} catch (Throwable t) {
call.cancel();
throw Throwables.propagate(t);
}
}
private static StreamObserver asyncStreamingRequestCall(
ClientCall call, StreamObserver responseObserver,
boolean streamingResponse) {
startCall(call, new StreamObserverToCallListenerAdapter(
call, responseObserver, streamingResponse), streamingResponse);
return new CallToStreamObserverAdapter(call);
}
private static void startCall(ClientCall call,
ClientCall.Listener responseListener, boolean streamingResponse) {
call.start(responseListener, new Metadata());
if (streamingResponse) {
call.request(1);
} else {
// Initially ask for two responses from flow-control so that if a misbehaving server sends
// more than one responses, we can catch it and fail it in the listener.
call.request(2);
}
}
private static class CallToStreamObserverAdapter implements StreamObserver {
private final ClientCall call;
public CallToStreamObserverAdapter(ClientCall call) {
this.call = call;
}
@Override
public void onNext(T value) {
call.sendMessage(value);
}
@Override
public void onError(Throwable t) {
// TODO(ejona86): log?
call.cancel();
}
@Override
public void onCompleted() {
call.halfClose();
}
}
private static class StreamObserverToCallListenerAdapter
extends ClientCall.Listener {
private final ClientCall, RespT> call;
private final StreamObserver observer;
private final boolean streamingResponse;
private boolean firstResponseReceived;
public StreamObserverToCallListenerAdapter(
ClientCall, RespT> call, StreamObserver observer, boolean streamingResponse) {
this.call = call;
this.observer = observer;
this.streamingResponse = streamingResponse;
}
@Override
public void onHeaders(Metadata headers) {
}
@Override
public void onMessage(RespT message) {
if (firstResponseReceived && !streamingResponse) {
throw Status.INTERNAL
.withDescription("More than one responses received for unary or client-streaming call")
.asRuntimeException();
}
firstResponseReceived = true;
observer.onNext(message);
if (streamingResponse) {
// Request delivery of the next inbound message.
call.request(1);
}
}
@Override
public void onClose(Status status, Metadata trailers) {
if (status.isOk()) {
observer.onCompleted();
} else {
observer.onError(status.asRuntimeException());
}
}
}
/**
* Complete a GrpcFuture using {@link StreamObserver} events.
*/
private static class UnaryStreamToFuture extends ClientCall.Listener {
private final GrpcFuture responseFuture;
private RespT value;
public UnaryStreamToFuture(GrpcFuture responseFuture) {
this.responseFuture = responseFuture;
}
@Override
public void onHeaders(Metadata headers) {
}
@Override
public void onMessage(RespT value) {
if (this.value != null) {
throw Status.INTERNAL.withDescription("More than one value received for unary call")
.asRuntimeException();
}
this.value = value;
}
@Override
public void onClose(Status status, Metadata trailers) {
if (status.isOk()) {
if (value == null) {
// No value received so mark the future as an error
responseFuture.setException(
Status.INTERNAL.withDescription("No value received for unary call")
.asRuntimeException());
}
responseFuture.set(value);
} else {
responseFuture.setException(status.asRuntimeException());
}
}
}
private static class GrpcFuture extends AbstractFuture {
private final ClientCall, RespT> call;
GrpcFuture(ClientCall, RespT> call) {
this.call = call;
}
@Override
protected void interruptTask() {
call.cancel();
}
@Override
protected boolean set(@Nullable RespT resp) {
return super.set(resp);
}
@Override
protected boolean setException(Throwable throwable) {
return super.setException(throwable);
}
}
/**
* Convert events on a {@link org.glowroot.agent.shaded.grpc.ClientCall.Listener} into a blocking
* {@link Iterator}.
*
* The class is not thread-safe, but it does permit {@link ClientCall.Listener} calls in a
* separate thread from {@code Iterator} calls.
*/
// TODO(ejona86): determine how to allow ClientCall.cancel() in case of application error.
private static class BlockingResponseStream implements Iterator {
// Due to flow control, only needs to hold up to 2 items: 1 for value, 1 for close.
private final BlockingQueue