Search in sources :

Example 16 with ClientCall

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

the class AbstractInteropTest method serverStreamingShouldBeFlowControlled.

@Test
public void serverStreamingShouldBeFlowControlled() throws Exception {
    final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder().addResponseParameters(ResponseParameters.newBuilder().setSize(100000)).addResponseParameters(ResponseParameters.newBuilder().setSize(100001)).build();
    final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(StreamingOutputCallResponse.newBuilder().setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[100000]))).build(), StreamingOutputCallResponse.newBuilder().setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[100001]))).build());
    long start = System.nanoTime();
    final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
    ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call = channel.newCall(TestServiceGrpc.getStreamingOutputCallMethod(), 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(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);
    Object response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
    assertTrue(response instanceof StreamingOutputCallResponse);
    assertResponse(goldenResponses.get(0), (StreamingOutputCallResponse) response);
    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);
    response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
    assertTrue(response instanceof StreamingOutputCallResponse);
    assertResponse(goldenResponses.get(1), (StreamingOutputCallResponse) response);
    assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
}
Also used : Status(io.grpc.Status) EchoStatus(io.grpc.testing.integration.Messages.EchoStatus) Metadata(io.grpc.Metadata) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ClientCall(io.grpc.ClientCall) StreamingOutputCallRequest(io.grpc.testing.integration.Messages.StreamingOutputCallRequest) StreamingOutputCallResponse(io.grpc.testing.integration.Messages.StreamingOutputCallResponse) Test(org.junit.Test)

Example 17 with ClientCall

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

the class BinlogHelperTest method clientDeadlineLogged_deadlineSetViaContext.

@Test
public void clientDeadlineLogged_deadlineSetViaContext() throws Exception {
    // important: deadline is read from the ctx where call was created
    final SettableFuture<ClientCall<byte[], byte[]>> callFuture = SettableFuture.create();
    Context.current().withDeadline(Deadline.after(1, TimeUnit.SECONDS), Executors.newSingleThreadScheduledExecutor()).run(new Runnable() {

        @Override
        public void run() {
            MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
            callFuture.set(new BinlogHelper(mockSinkWriter).getClientInterceptor(CALL_ID).interceptCall(method, CallOptions.DEFAULT.withDeadlineAfter(1, TimeUnit.SECONDS), new Channel() {

                @Override
                public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
                    return new NoopClientCall<>();
                }

                @Override
                public String authority() {
                    return null;
                }
            }));
        }
    });
    @SuppressWarnings("unchecked") ClientCall.Listener<byte[]> mockListener = mock(ClientCall.Listener.class);
    callFuture.get().start(mockListener, new Metadata());
    ArgumentCaptor<Duration> callOptTimeoutCaptor = ArgumentCaptor.forClass(Duration.class);
    verify(mockSinkWriter).logClientHeader(anyLong(), anyString(), ArgumentMatchers.<String>any(), callOptTimeoutCaptor.capture(), any(Metadata.class), any(GrpcLogEntry.Logger.class), anyLong(), AdditionalMatchers.or(ArgumentMatchers.<SocketAddress>isNull(), ArgumentMatchers.<SocketAddress>any()));
    Duration timeout = callOptTimeoutCaptor.getValue();
    assertThat(TimeUnit.SECONDS.toNanos(1) - Durations.toNanos(timeout)).isAtMost(TimeUnit.MILLISECONDS.toNanos(250));
}
Also used : Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) Duration(com.google.protobuf.Duration) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Logger(io.grpc.binarylog.v1.GrpcLogEntry.Logger) MethodDescriptor(io.grpc.MethodDescriptor) ClientCall(io.grpc.ClientCall) NoopClientCall(io.grpc.internal.NoopClientCall) SocketAddress(java.net.SocketAddress) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.Test)

Example 18 with ClientCall

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

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

the class ErrorHandlingClient method advancedAsyncCall.

/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
    ClientCall<HelloRequest, HelloReply> call = channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);
    final CountDownLatch latch = new CountDownLatch(1);
    call.start(new ClientCall.Listener<HelloReply>() {

        @Override
        public void onClose(Status status, Metadata trailers) {
            Verify.verify(status.getCode() == Status.Code.INTERNAL);
            Verify.verify(status.getDescription().contains("Narwhal"));
            // Cause is not transmitted over the wire.
            latch.countDown();
        }
    }, new Metadata());
    call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
    call.halfClose();
    if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
        throw new RuntimeException("timeout!");
    }
}
Also used : Status(io.grpc.Status) ClientCall(io.grpc.ClientCall) HelloRequest(io.grpc.examples.helloworld.HelloRequest) Metadata(io.grpc.Metadata) HelloReply(io.grpc.examples.helloworld.HelloReply) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 20 with ClientCall

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

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