Search in sources :

Example 11 with ClientCall

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

the class FaultFilter method buildClientInterceptor.

@Nullable
@Override
public ClientInterceptor buildClientInterceptor(FilterConfig config, @Nullable FilterConfig overrideConfig, PickSubchannelArgs args, final ScheduledExecutorService scheduler) {
    checkNotNull(config, "config");
    if (overrideConfig != null) {
        config = overrideConfig;
    }
    FaultConfig faultConfig = (FaultConfig) config;
    Long delayNanos = null;
    Status abortStatus = null;
    if (faultConfig.maxActiveFaults() == null || activeFaultCounter.get() < faultConfig.maxActiveFaults()) {
        Metadata headers = args.getHeaders();
        if (faultConfig.faultDelay() != null) {
            delayNanos = determineFaultDelayNanos(faultConfig.faultDelay(), headers);
        }
        if (faultConfig.faultAbort() != null) {
            abortStatus = determineFaultAbortStatus(faultConfig.faultAbort(), headers);
        }
    }
    if (delayNanos == null && abortStatus == null) {
        return null;
    }
    final Long finalDelayNanos = delayNanos;
    final Status finalAbortStatus = getAbortStatusWithDescription(abortStatus);
    final class FaultInjectionInterceptor implements ClientInterceptor {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) {
            Executor callExecutor = callOptions.getExecutor();
            if (callExecutor == null) {
                // This should never happen in practice because
                // ManagedChannelImpl.ConfigSelectingClientCall always provides CallOptions with
                // a callExecutor.
                // TODO(https://github.com/grpc/grpc-java/issues/7868)
                callExecutor = MoreExecutors.directExecutor();
            }
            if (finalDelayNanos != null) {
                Supplier<? extends ClientCall<ReqT, RespT>> callSupplier;
                if (finalAbortStatus != null) {
                    callSupplier = Suppliers.ofInstance(new FailingClientCall<ReqT, RespT>(finalAbortStatus, callExecutor));
                } else {
                    callSupplier = new Supplier<ClientCall<ReqT, RespT>>() {

                        @Override
                        public ClientCall<ReqT, RespT> get() {
                            return next.newCall(method, callOptions);
                        }
                    };
                }
                final DelayInjectedCall<ReqT, RespT> delayInjectedCall = new DelayInjectedCall<>(finalDelayNanos, callExecutor, scheduler, callOptions.getDeadline(), callSupplier);
                final class DeadlineInsightForwardingCall extends ForwardingClientCall<ReqT, RespT> {

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

                    @Override
                    public void start(Listener<RespT> listener, Metadata headers) {
                        Listener<RespT> finalListener = new SimpleForwardingClientCallListener<RespT>(listener) {

                            @Override
                            public void onClose(Status status, Metadata trailers) {
                                if (status.getCode().equals(Code.DEADLINE_EXCEEDED)) {
                                    // TODO(zdapeng:) check effective deadline locally, and
                                    // do the following only if the local deadline is exceeded.
                                    // (If the server sends DEADLINE_EXCEEDED for its own deadline, then the
                                    // injected delay does not contribute to the error, because the request is
                                    // only sent out after the delay. There could be a race between local and
                                    // remote, but it is rather rare.)
                                    String description = String.format("Deadline exceeded after up to %d ns of fault-injected delay", finalDelayNanos);
                                    if (status.getDescription() != null) {
                                        description = description + ": " + status.getDescription();
                                    }
                                    status = Status.DEADLINE_EXCEEDED.withDescription(description).withCause(status.getCause());
                                    // Replace trailers to prevent mixing sources of status and trailers.
                                    trailers = new Metadata();
                                }
                                delegate().onClose(status, trailers);
                            }
                        };
                        delegate().start(finalListener, headers);
                    }
                }
                return new DeadlineInsightForwardingCall();
            } else {
                return new FailingClientCall<>(finalAbortStatus, callExecutor);
            }
        }
    }
    return new FaultInjectionInterceptor();
}
Also used : SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Executor(java.util.concurrent.Executor) DelayedClientCall(io.grpc.internal.DelayedClientCall) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Status(io.grpc.Status) Channel(io.grpc.Channel) MethodDescriptor(io.grpc.MethodDescriptor) AtomicLong(java.util.concurrent.atomic.AtomicLong) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Nullable(javax.annotation.Nullable)

Example 12 with ClientCall

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientCall in project jetcd by coreos.

the class ClientConnectionManagerTest method testHeaders.

@Test
public void testHeaders() throws InterruptedException, ExecutionException {
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientBuilder builder = TestUtil.client(cluster).header("MyHeader1", "MyHeaderVal1").header("MyHeader2", "MyHeaderVal2").interceptor(new ClientInterceptor() {

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

                @Override
                public void start(Listener<RespT> responseListener, Metadata headers) {
                    super.start(responseListener, headers);
                    assertThat(headers.get(Metadata.Key.of("MyHeader1", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyHeaderVal1");
                    assertThat(headers.get(Metadata.Key.of("MyHeader2", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyHeaderVal2");
                    latch.countDown();
                }
            };
        }
    });
    try (Client client = builder.build()) {
        CompletableFuture<PutResponse> future = client.getKVClient().put(bytesOf("sample_key"), bytesOf("sample_key"));
        latch.await(1, TimeUnit.MINUTES);
        future.get();
    }
}
Also used : Channel(io.grpc.Channel) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) CountDownLatch(java.util.concurrent.CountDownLatch) PutResponse(io.etcd.jetcd.kv.PutResponse) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Client(io.etcd.jetcd.Client) ClientBuilder(io.etcd.jetcd.ClientBuilder) Test(org.junit.jupiter.api.Test)

Example 13 with ClientCall

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

the class InteropTester method serverStreamingShouldBeFlowControlled.

public void serverStreamingShouldBeFlowControlled() throws Exception {
    final StreamingOutputCallRequest request = new StreamingOutputCallRequest();
    request.responseType = Messages.COMPRESSABLE;
    request.responseParameters = new ResponseParameters[2];
    request.responseParameters[0] = new ResponseParameters();
    request.responseParameters[0].size = 100000;
    request.responseParameters[1] = new ResponseParameters();
    request.responseParameters[1].size = 100001;
    final StreamingOutputCallResponse[] goldenResponses = new StreamingOutputCallResponse[2];
    goldenResponses[0] = new StreamingOutputCallResponse();
    goldenResponses[0].payload = new Payload();
    goldenResponses[0].payload.type = Messages.COMPRESSABLE;
    goldenResponses[0].payload.body = new byte[100000];
    goldenResponses[1] = new StreamingOutputCallResponse();
    goldenResponses[1].payload = new Payload();
    goldenResponses[1].payload.type = Messages.COMPRESSABLE;
    goldenResponses[1].payload.body = new byte[100001];
    long start = System.nanoTime();
    final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(10);
    ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call = channel.newCall(TestServiceGrpc.METHOD_STREAMING_OUTPUT_CALL, CallOptions.DEFAULT);
    call.start(new ClientCall.Listener<StreamingOutputCallResponse>() {

        @Override
        public void onHeaders(Metadata headers) {
        }

        @Override
        public void onMessage(final StreamingOutputCallResponse message) {
            queue.add(message);
        }

        @Override
        public void onClose(io.grpc.Status status, Metadata trailers) {
            queue.add(status);
        }
    }, new Metadata());
    call.sendMessage(request);
    call.halfClose();
    // Time how long it takes to get the first response.
    call.request(1);
    assertMessageEquals(goldenResponses[0], (StreamingOutputCallResponse) queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
    long firstCallDuration = System.nanoTime() - start;
    // Without giving additional flow control, make sure that we don't get another response. We wait
    // until we are comfortable the next message isn't coming. We may have very low nanoTime
    // resolution (like on Windows) or be using a testing, in-process transport where message
    // handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time
    // to at least 1ms.
    assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS));
    // Make sure that everything still completes.
    call.request(1);
    assertMessageEquals(goldenResponses[1], (StreamingOutputCallResponse) queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
    assertCodeEquals(io.grpc.Status.OK, (io.grpc.Status) queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
Also used : ResponseParameters(io.grpc.android.integrationtest.nano.Messages.ResponseParameters) Metadata(io.grpc.Metadata) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ClientCall(io.grpc.ClientCall) Payload(io.grpc.android.integrationtest.nano.Messages.Payload) StreamingOutputCallRequest(io.grpc.android.integrationtest.nano.Messages.StreamingOutputCallRequest) StreamingOutputCallResponse(io.grpc.android.integrationtest.nano.Messages.StreamingOutputCallResponse)

Example 14 with ClientCall

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientCall 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;
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Vertx(io.vertx.core.Vertx) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) VertxChannelBuilder(io.vertx.grpc.VertxChannelBuilder) BiConsumer(java.util.function.BiConsumer)

Example 15 with ClientCall

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

ClientCall (io.grpc.ClientCall)21 Metadata (io.grpc.Metadata)21 CallOptions (io.grpc.CallOptions)14 Channel (io.grpc.Channel)14 ClientInterceptor (io.grpc.ClientInterceptor)10 Test (org.junit.Test)10 MethodDescriptor (io.grpc.MethodDescriptor)9 Status (io.grpc.Status)9 ByteString (com.google.protobuf.ByteString)6 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)6 ManagedChannel (io.grpc.ManagedChannel)6 Duration (com.google.protobuf.Duration)5 NoopClientCall (io.grpc.internal.NoopClientCall)5 ForwardingClientCall (io.grpc.ForwardingClientCall)4 InetSocketAddress (java.net.InetSocketAddress)4 SocketAddress (java.net.SocketAddress)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)3 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3