use of org.apache.beam.vendor.grpc.v1p43p2.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 org.apache.beam.vendor.grpc.v1p43p2.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;
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project beam by apache.
the class GrpcContextHeaderAccessorProviderTest method testWorkerIdOnConnect.
@SuppressWarnings("unchecked")
@Test
public void testWorkerIdOnConnect() throws Exception {
final String worker1 = "worker1";
CompletableFuture<String> workerId = new CompletableFuture<>();
Consumer<StreamObserver<Elements>> consumer = elementsStreamObserver -> {
workerId.complete(GrpcContextHeaderAccessorProvider.getHeaderAccessor().getSdkWorkerId());
elementsStreamObserver.onCompleted();
};
TestDataService testService = new TestDataService(Mockito.mock(StreamObserver.class), consumer);
ApiServiceDescriptor serviceDescriptor = ApiServiceDescriptor.newBuilder().setUrl("testServer").build();
cleanupRule.register(InProcessServerFactory.create().create(ImmutableList.of(testService), serviceDescriptor));
final Metadata.Key<String> workerIdKey = Metadata.Key.of("worker_id", Metadata.ASCII_STRING_MARSHALLER);
Channel channel = cleanupRule.register(InProcessChannelBuilder.forName(serviceDescriptor.getUrl()).intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
return new SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override
public void start(ClientCall.Listener<RespT> responseListener, Metadata headers) {
headers.put(workerIdKey, worker1);
super.start(responseListener, headers);
}
};
}
}).build());
BeamFnDataGrpc.BeamFnDataStub stub = BeamFnDataGrpc.newStub(channel);
stub.data(Mockito.mock(StreamObserver.class)).onCompleted();
Assert.assertEquals(worker1, workerId.get());
}
use of org.apache.beam.vendor.grpc.v1p43p2.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 org.apache.beam.vendor.grpc.v1p43p2.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));
}
Aggregations