Search in sources :

Example 6 with SimpleForwardingClientCall

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;
    }
}
Also used : Status(io.grpc.Status) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Tracer(brave.Tracer) Metadata(io.grpc.Metadata) Span(brave.Span) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 7 with SimpleForwardingClientCall

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;
}
Also used : MethodType(io.grpc.MethodDescriptor.MethodType) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 8 with SimpleForwardingClientCall

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());
}
Also used : StreamObserver(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver) ClientInterceptor(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientInterceptor) Elements(org.apache.beam.model.fnexecution.v1.BeamFnApi.Elements) RunWith(org.junit.runner.RunWith) Channel(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Channel) CompletableFuture(java.util.concurrent.CompletableFuture) BeamFnDataGrpc(org.apache.beam.model.fnexecution.v1.BeamFnDataGrpc) GrpcContextHeaderAccessorProvider(org.apache.beam.sdk.fn.server.GrpcContextHeaderAccessorProvider) InProcessChannelBuilder(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.inprocess.InProcessChannelBuilder) MethodDescriptor(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor) ClientCall(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientCall) ApiServiceDescriptor(org.apache.beam.model.pipeline.v1.Endpoints.ApiServiceDescriptor) InProcessServerFactory(org.apache.beam.sdk.fn.server.InProcessServerFactory) Metadata(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Metadata) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) BeamFnApi(org.apache.beam.model.fnexecution.v1.BeamFnApi) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CallOptions(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions) GrpcCleanupRule(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.testing.GrpcCleanupRule) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) StreamObserver(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver) SimpleForwardingClientCall(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ImmutableList(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList) Assert(org.junit.Assert) ApiServiceDescriptor(org.apache.beam.model.pipeline.v1.Endpoints.ApiServiceDescriptor) Channel(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Channel) Metadata(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Metadata) CallOptions(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions) CompletableFuture(java.util.concurrent.CompletableFuture) ClientCall(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientCall) SimpleForwardingClientCall(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientInterceptor(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientInterceptor) BeamFnDataGrpc(org.apache.beam.model.fnexecution.v1.BeamFnDataGrpc) Test(org.junit.Test)

Example 9 with SimpleForwardingClientCall

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);
                }
            };
        }
    };
}
Also used : Status(io.grpc.Status) SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Channel(io.grpc.Channel) Deadline(io.grpc.Deadline) Metadata(io.grpc.Metadata) InternalMetadata(io.grpc.InternalMetadata) Duration(com.google.protobuf.Duration) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) MethodDescriptor(io.grpc.MethodDescriptor) AtomicLong(java.util.concurrent.atomic.AtomicLong) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 10 with SimpleForwardingClientCall

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));
}
Also used : GreeterBlockingStub(io.grpc.examples.helloworld.GreeterGrpc.GreeterBlockingStub) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) Test(org.junit.Test)

Aggregations

SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)10 Metadata (io.grpc.Metadata)9 CallOptions (io.grpc.CallOptions)8 Channel (io.grpc.Channel)8 ClientInterceptor (io.grpc.ClientInterceptor)8 ClientCall (io.grpc.ClientCall)6 ManagedChannel (io.grpc.ManagedChannel)6 MethodDescriptor (io.grpc.MethodDescriptor)5 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)4 Test (org.junit.Test)4 Status (io.grpc.Status)3 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 Span (zipkin2.Span)2 CurrentSpanCustomizer (brave.CurrentSpanCustomizer)1 Span (brave.Span)1 SpanCustomizer (brave.SpanCustomizer)1 Tracer (brave.Tracer)1 TopicAdminClient (com.google.cloud.pubsub.spi.v1.TopicAdminClient)1 ByteString (com.google.protobuf.ByteString)1 Duration (com.google.protobuf.Duration)1