use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project brave by openzipkin.
the class TracingClientInterceptor method interceptCall.
/**
* This sets as span in scope both for the interception and for the start of the request. It does
* not set a span in scope during the response listener as it is unexpected it would be used at
* that fine granularity. If users want access to the span in a response listener, they will need
* to wrap the executor with one that's aware of the current context.
*/
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) {
Span span = tracer.nextSpan();
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
injector.inject(span.context(), headers);
span.kind(Span.Kind.CLIENT).start();
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
parser.onStart(method, callOptions, headers, span.customizer());
super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onMessage(RespT message) {
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
parser.onMessageReceived(message, span.customizer());
delegate().onMessage(message);
}
}
@Override
public void onClose(Status status, Metadata trailers) {
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
super.onClose(status, trailers);
parser.onClose(status, trailers, span.customizer());
} finally {
span.finish();
}
}
}, headers);
}
}
@Override
public void sendMessage(ReqT message) {
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
super.sendMessage(message);
parser.onMessageSent(message, span.customizer());
}
}
};
} catch (RuntimeException | Error e) {
parser.onError(e, span.customizer());
span.finish();
throw e;
}
}
use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project jetcd by coreos.
the class ClientConnectionManager method defaultChannelBuilder.
@SuppressWarnings("rawtypes")
ManagedChannelBuilder<?> defaultChannelBuilder(String target) {
if (target == null) {
throw new IllegalArgumentException("At least one endpoint should be provided");
}
final Vertx vertx = Vertx.vertx();
final VertxChannelBuilder channelBuilder = VertxChannelBuilder.forTarget(vertx, target);
if (builder.authority() != null) {
channelBuilder.overrideAuthority(builder.authority());
}
if (builder.maxInboundMessageSize() != null) {
channelBuilder.maxInboundMessageSize(builder.maxInboundMessageSize());
}
if (builder.sslContext() != null) {
channelBuilder.nettyBuilder().negotiationType(NegotiationType.TLS);
channelBuilder.nettyBuilder().sslContext(builder.sslContext());
} else {
channelBuilder.nettyBuilder().negotiationType(NegotiationType.PLAINTEXT);
}
if (builder.keepaliveTime() != null) {
channelBuilder.keepAliveTime(builder.keepaliveTime().toMillis(), TimeUnit.MILLISECONDS);
}
if (builder.keepaliveTimeout() != null) {
channelBuilder.keepAliveTimeout(builder.keepaliveTimeout().toMillis(), TimeUnit.MILLISECONDS);
}
if (builder.keepaliveWithoutCalls() != null) {
channelBuilder.keepAliveWithoutCalls(builder.keepaliveWithoutCalls());
}
if (builder.connectTimeout() != null) {
channelBuilder.nettyBuilder().withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) builder.connectTimeout().toMillis());
}
if (builder.loadBalancerPolicy() != null) {
channelBuilder.defaultLoadBalancingPolicy(builder.loadBalancerPolicy());
} else {
channelBuilder.defaultLoadBalancingPolicy("pick_first");
}
if (builder.headers() != null) {
channelBuilder.intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
builder.headers().forEach((BiConsumer<Metadata.Key, Object>) headers::put);
super.start(responseListener, headers);
}
};
}
});
}
if (builder.interceptors() != null) {
channelBuilder.intercept(builder.interceptors());
}
return channelBuilder;
}
use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project grpc-java by grpc.
the class BinlogHelper method getClientInterceptor.
public ClientInterceptor getClientInterceptor(final long callId) {
return new ClientInterceptor() {
boolean trailersOnlyResponse = true;
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
final AtomicLong seq = new AtomicLong(1);
final String methodName = method.getFullMethodName();
final String authority = next.authority();
// The timeout should reflect the time remaining when the call is started, so do not
// compute remaining time here.
final Deadline deadline = min(callOptions.getDeadline(), Context.current().getDeadline());
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(final ClientCall.Listener<RespT> responseListener, Metadata headers) {
final Duration timeout = deadline == null ? null : Durations.fromNanos(deadline.timeRemaining(TimeUnit.NANOSECONDS));
writer.logClientHeader(seq.getAndIncrement(), methodName, authority, timeout, headers, GrpcLogEntry.Logger.LOGGER_CLIENT, callId, /*peerAddress=*/
null);
ClientCall.Listener<RespT> wListener = new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onMessage(RespT message) {
writer.logRpcMessage(seq.getAndIncrement(), EventType.EVENT_TYPE_SERVER_MESSAGE, method.getResponseMarshaller(), message, GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
super.onMessage(message);
}
@Override
public void onHeaders(Metadata headers) {
trailersOnlyResponse = false;
writer.logServerHeader(seq.getAndIncrement(), headers, GrpcLogEntry.Logger.LOGGER_CLIENT, callId, getPeerSocket(getAttributes()));
super.onHeaders(headers);
}
@Override
public void onClose(Status status, Metadata trailers) {
SocketAddress peer = trailersOnlyResponse ? getPeerSocket(getAttributes()) : null;
writer.logTrailer(seq.getAndIncrement(), status, trailers, GrpcLogEntry.Logger.LOGGER_CLIENT, callId, peer);
super.onClose(status, trailers);
}
};
super.start(wListener, headers);
}
@Override
public void sendMessage(ReqT message) {
writer.logRpcMessage(seq.getAndIncrement(), EventType.EVENT_TYPE_CLIENT_MESSAGE, method.getRequestMarshaller(), message, GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
super.sendMessage(message);
}
@Override
public void halfClose() {
writer.logHalfClose(seq.getAndIncrement(), GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
super.halfClose();
}
@Override
public void cancel(String message, Throwable cause) {
writer.logCancel(seq.getAndIncrement(), GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
super.cancel(message, cause);
}
};
}
};
}
use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project grpc-java by grpc.
the class HeaderServerInterceptorTest method serverHeaderDeliveredToClient.
@Test
public void serverHeaderDeliveredToClient() {
class SpyingClientInterceptor implements ClientInterceptor {
ClientCall.Listener<?> spyListener;
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
spyListener = responseListener = mock(ClientCall.Listener.class, delegatesTo(responseListener));
super.start(responseListener, headers);
}
};
}
}
SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel).withInterceptors(clientInterceptor);
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
blockingStub.sayHello(HelloRequest.getDefaultInstance());
assertNotNull(clientInterceptor.spyListener);
verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture());
assertEquals("customRespondValue", metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY));
}
use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project motan by weibocom.
the class GrpcClient method request.
@SuppressWarnings({ "unchecked", "rawtypes" })
public <ReqT, RespT> Response request(final Request request) {
MethodDescriptor<ReqT, RespT> methodDesc = methodDescMap.get(request.getMethodName());
if (methodDesc == null) {
throw new MotanServiceException("request method grpc descriptornot found.method:" + request.getMethodName());
}
int timeout = url.getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
if (timeout < 0) {
throw new MotanServiceException("request timeout invalid.method timeout:" + timeout);
}
ClientCall<ReqT, RespT> call = new SimpleForwardingClientCall(channel.newCall(methodDesc, callOption.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS))) {
public void start(Listener responseListener, Metadata headers) {
Map<String, String> attachments = request.getAttachments();
if (attachments != null && !attachments.isEmpty()) {
for (Entry<String, String> entry : attachments.entrySet()) {
headers.put(Metadata.Key.of(entry.getKey(), Metadata.ASCII_STRING_MARSHALLER), entry.getValue());
}
}
super.start(responseListener, headers);
}
};
GrpcResponseFuture<RespT> responseFuture = new GrpcResponseFuture<RespT>(request, timeout, url, call);
MethodType methodType = methodDesc.getType();
switch(methodType) {
case UNARY:
ClientCalls.asyncUnaryCall(call, (ReqT) request.getArguments()[0], responseFuture);
break;
case SERVER_STREAMING:
ClientCalls.asyncServerStreamingCall(call, (ReqT) request.getArguments()[0], (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[1]);
responseFuture.onCompleted();
break;
case CLIENT_STREAMING:
StreamObserver<ReqT> clientObserver = ClientCalls.asyncClientStreamingCall(call, (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[0]);
responseFuture.onNext(clientObserver);
responseFuture.onCompleted();
break;
case BIDI_STREAMING:
StreamObserver<ReqT> biObserver = ClientCalls.asyncBidiStreamingCall(call, (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[0]);
responseFuture.onNext(biObserver);
responseFuture.onCompleted();
break;
default:
throw new MotanServiceException("unknown grpc method type:" + methodType);
}
return responseFuture;
}
Aggregations