Search in sources :

Example 26 with MethodDescriptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project ballerina by ballerina-lang.

the class NonBlockingExecute method execute.

@Override
public void execute(Context context) {
    BStruct serviceStub = (BStruct) context.getRefArgument(SERVICE_STUB_REF_INDEX);
    if (serviceStub == null) {
        notifyErrorReply(context, "Error while getting connector. gRPC Client connector is " + "not initialized properly");
        return;
    }
    Object connectionStub = serviceStub.getNativeData(SERVICE_STUB);
    if (connectionStub == null) {
        notifyErrorReply(context, "Error while getting connection stub. gRPC Client connector " + "is not initialized properly");
        return;
    }
    String methodName = context.getStringArgument(0);
    if (methodName == null) {
        notifyErrorReply(context, "Error while processing the request. RPC endpoint doesn't " + "set properly");
        return;
    }
    com.google.protobuf.Descriptors.MethodDescriptor methodDescriptor = MessageRegistry.getInstance().getMethodDescriptor(methodName);
    if (methodDescriptor == null) {
        notifyErrorReply(context, "No registered method descriptor for '" + methodName + "'");
        return;
    }
    if (connectionStub instanceof GrpcNonBlockingStub) {
        BValue payloadBValue = context.getRefArgument(1);
        Message requestMsg = MessageUtils.generateProtoMessage(payloadBValue, methodDescriptor.getInputType());
        GrpcNonBlockingStub grpcNonBlockingStub = (GrpcNonBlockingStub) connectionStub;
        BTypeDescValue serviceType = (BTypeDescValue) context.getRefArgument(2);
        Service callbackService = BLangConnectorSPIUtil.getServiceFromType(context.getProgramFile(), getTypeField(serviceType));
        try {
            MethodDescriptor.MethodType methodType = getMethodType(methodDescriptor);
            if (methodType.equals(MethodDescriptor.MethodType.UNARY)) {
                grpcNonBlockingStub.executeUnary(requestMsg, new DefaultStreamObserver(callbackService), methodName);
            } else if (methodType.equals(MethodDescriptor.MethodType.SERVER_STREAMING)) {
                grpcNonBlockingStub.executeServerStreaming(requestMsg, new DefaultStreamObserver(callbackService), methodName);
            } else {
                notifyErrorReply(context, "Error while executing the client call. Method type " + methodType.name() + " not supported");
                return;
            }
            context.setReturnValues();
            return;
        } catch (RuntimeException | GrpcClientException e) {
            notifyErrorReply(context, "gRPC Client Connector Error :" + e.getMessage());
            return;
        }
    }
    notifyErrorReply(context, "Error while processing the request message. Connection Sub " + "type not supported");
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) Message(org.ballerinalang.net.grpc.Message) DefaultStreamObserver(org.ballerinalang.net.grpc.stubs.DefaultStreamObserver) BValue(org.ballerinalang.model.values.BValue) Service(org.ballerinalang.connector.api.Service) MethodDescriptor(io.grpc.MethodDescriptor) BTypeDescValue(org.ballerinalang.model.values.BTypeDescValue) GrpcClientException(org.ballerinalang.net.grpc.exception.GrpcClientException) GrpcNonBlockingStub(org.ballerinalang.net.grpc.stubs.GrpcNonBlockingStub)

Example 27 with MethodDescriptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor 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 28 with MethodDescriptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.

the class ManagedChannelImplTest method interceptor.

@Test
public void interceptor() throws Exception {
    final AtomicLong atomic = new AtomicLong();
    ClientInterceptor interceptor = new ClientInterceptor() {

        @Override
        public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> interceptCall(MethodDescriptor<RequestT, ResponseT> method, CallOptions callOptions, Channel next) {
            atomic.set(1);
            return next.newCall(method, callOptions);
        }
    };
    createChannel(interceptor);
    assertNotNull(channel.newCall(method, CallOptions.DEFAULT));
    assertEquals(1, atomic.get());
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) ClientInterceptor(io.grpc.ClientInterceptor) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) Test(org.junit.Test)

Example 29 with MethodDescriptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.

the class ConfigSelectingClientCallTest method configSelectorInterceptsCall.

@Test
public void configSelectorInterceptsCall() {
    Map<String, ?> rawMethodConfig = ImmutableMap.of("retryPolicy", ImmutableMap.of("maxAttempts", 3.0D, "initialBackoff", "1s", "maxBackoff", "10s", "backoffMultiplier", 1.5D, "retryableStatusCodes", ImmutableList.of("UNAVAILABLE")));
    final MethodInfo methodInfo = new MethodInfo(rawMethodConfig, true, 4, 4);
    final Metadata.Key<String> metadataKey = Metadata.Key.of("test", Metadata.ASCII_STRING_MARSHALLER);
    final CallOptions.Key<String> callOptionsKey = CallOptions.Key.create("test");
    InternalConfigSelector configSelector = new InternalConfigSelector() {

        @Override
        public Result selectConfig(final PickSubchannelArgs args) {
            ManagedChannelServiceConfig config = new ManagedChannelServiceConfig(methodInfo, ImmutableMap.<String, MethodInfo>of(), ImmutableMap.<String, MethodInfo>of(), null, null, null);
            return Result.newBuilder().setConfig(config).setInterceptor(// An interceptor that mutates CallOptions based on headers value.
            new ClientInterceptor() {

                String value = args.getHeaders().get(metadataKey);

                @Override
                public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
                    callOptions = callOptions.withOption(callOptionsKey, value);
                    return next.newCall(method, callOptions);
                }
            }).build();
        }
    };
    ClientCall<Void, Void> configSelectingClientCall = new ConfigSelectingClientCall<>(configSelector, channel, MoreExecutors.directExecutor(), method, CallOptions.DEFAULT.withAuthority("bar.authority"));
    Metadata metadata = new Metadata();
    metadata.put(metadataKey, "fooValue");
    configSelectingClientCall.start(callListener, metadata);
    assertThat(call.callOptions.getAuthority()).isEqualTo("bar.authority");
    assertThat(call.callOptions.getOption(MethodInfo.KEY)).isEqualTo(methodInfo);
    assertThat(call.callOptions.getOption(callOptionsKey)).isEqualTo("fooValue");
}
Also used : Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) InternalConfigSelector(io.grpc.InternalConfigSelector) ClientInterceptor(io.grpc.ClientInterceptor) ConfigSelectingClientCall(io.grpc.internal.ManagedChannelImpl.ConfigSelectingClientCall) MethodInfo(io.grpc.internal.ManagedChannelServiceConfig.MethodInfo) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) Test(org.junit.Test)

Example 30 with MethodDescriptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.

the class TransportCompressionTest method createChannelBuilder.

@Override
protected NettyChannelBuilder createChannelBuilder() {
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(getListenAddress()).maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE).decompressorRegistry(decompressors).compressorRegistry(compressors).intercept(new ClientInterceptor() {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            final ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
            return new ForwardingClientCall<ReqT, RespT>() {

                @Override
                protected ClientCall<ReqT, RespT> delegate() {
                    return call;
                }

                @Override
                public void start(final ClientCall.Listener<RespT> responseListener, Metadata headers) {
                    ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {

                        @Override
                        protected io.grpc.ClientCall.Listener<RespT> delegate() {
                            return responseListener;
                        }

                        @Override
                        public void onHeaders(Metadata headers) {
                            super.onHeaders(headers);
                            if (expectFzip) {
                                String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
                                assertEquals(encoding, FZIPPER.getMessageEncoding());
                            }
                        }
                    };
                    super.start(listener, headers);
                    setMessageCompression(true);
                }
            };
        }
    }).usePlaintext();
    // Disable the default census stats interceptor, use testing interceptor instead.
    InternalNettyChannelBuilder.setStatsEnabled(builder, false);
    return builder.intercept(createCensusStatsClientInterceptor());
}
Also used : ForwardingClientCallListener(io.grpc.ForwardingClientCallListener) Listener(io.grpc.ServerCall.Listener) Channel(io.grpc.Channel) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) MethodDescriptor(io.grpc.MethodDescriptor) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) InternalNettyChannelBuilder(io.grpc.netty.InternalNettyChannelBuilder) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) ForwardingClientCallListener(io.grpc.ForwardingClientCallListener)

Aggregations

MethodDescriptor (io.grpc.MethodDescriptor)35 CallOptions (io.grpc.CallOptions)20 Metadata (io.grpc.Metadata)19 Channel (io.grpc.Channel)18 Test (org.junit.Test)17 ClientInterceptor (io.grpc.ClientInterceptor)13 ClientCall (io.grpc.ClientCall)9 Status (io.grpc.Status)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 ByteString (com.google.protobuf.ByteString)6 ManagedChannel (io.grpc.ManagedChannel)6 Duration (com.google.protobuf.Duration)5 NoopClientCall (io.grpc.internal.NoopClientCall)5 SocketAddress (java.net.SocketAddress)5 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)4 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)4 InetSocketAddress (java.net.InetSocketAddress)4 AtomicLong (java.util.concurrent.atomic.AtomicLong)4 ClientStreamTracer (io.grpc.ClientStreamTracer)3 ForwardingClientCall (io.grpc.ForwardingClientCall)3