Search in sources :

Example 31 with CallOptions

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

the class BinlogHelperTest method clientInterceptor.

@Test
public void clientInterceptor() throws Exception {
    final AtomicReference<ClientCall.Listener<byte[]>> interceptedListener = new AtomicReference<>();
    // capture these manually because ClientCall can not be mocked
    final AtomicReference<Metadata> actualClientInitial = new AtomicReference<>();
    final AtomicReference<Object> actualRequest = new AtomicReference<>();
    final SettableFuture<Void> halfCloseCalled = SettableFuture.create();
    final SettableFuture<Void> cancelCalled = SettableFuture.create();
    Channel channel = new Channel() {

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

                @Override
                @SuppressWarnings("unchecked")
                public void start(Listener<ResponseT> responseListener, Metadata headers) {
                    interceptedListener.set((Listener<byte[]>) responseListener);
                    actualClientInitial.set(headers);
                }

                @Override
                public void sendMessage(RequestT message) {
                    actualRequest.set(message);
                }

                @Override
                public void cancel(String message, Throwable cause) {
                    cancelCalled.set(null);
                }

                @Override
                public void halfClose() {
                    halfCloseCalled.set(null);
                }

                @Override
                public Attributes getAttributes() {
                    return Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, peer).build();
                }
            };
        }

        @Override
        public String authority() {
            return "the-authority";
        }
    };
    @SuppressWarnings("unchecked") ClientCall.Listener<byte[]> mockListener = mock(ClientCall.Listener.class);
    MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
    ClientCall<byte[], byte[]> interceptedCall = new BinlogHelper(mockSinkWriter).getClientInterceptor(CALL_ID).interceptCall(method, CallOptions.DEFAULT, channel);
    // send client header
    {
        Metadata clientInitial = new Metadata();
        interceptedCall.start(mockListener, clientInitial);
        verify(mockSinkWriter).logClientHeader(/*seq=*/
        eq(1L), eq("service/method"), eq("the-authority"), ArgumentMatchers.<Duration>isNull(), same(clientInitial), eq(Logger.LOGGER_CLIENT), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
        verifyNoMoreInteractions(mockSinkWriter);
        assertSame(clientInitial, actualClientInitial.get());
    }
    // receive server header
    {
        Metadata serverInitial = new Metadata();
        interceptedListener.get().onHeaders(serverInitial);
        verify(mockSinkWriter).logServerHeader(/*seq=*/
        eq(2L), same(serverInitial), eq(Logger.LOGGER_CLIENT), eq(CALL_ID), same(peer));
        verifyNoMoreInteractions(mockSinkWriter);
        verify(mockListener).onHeaders(same(serverInitial));
    }
    // send client msg
    {
        byte[] request = "this is a request".getBytes(US_ASCII);
        interceptedCall.sendMessage(request);
        verify(mockSinkWriter).logRpcMessage(/*seq=*/
        eq(3L), eq(EventType.EVENT_TYPE_CLIENT_MESSAGE), same(BYTEARRAY_MARSHALLER), same(request), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
        verifyNoMoreInteractions(mockSinkWriter);
        assertSame(request, actualRequest.get());
    }
    // client half close
    {
        interceptedCall.halfClose();
        verify(mockSinkWriter).logHalfClose(/*seq=*/
        eq(4L), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
        halfCloseCalled.get(1, TimeUnit.SECONDS);
        verifyNoMoreInteractions(mockSinkWriter);
    }
    // receive server msg
    {
        byte[] response = "this is a response".getBytes(US_ASCII);
        interceptedListener.get().onMessage(response);
        verify(mockSinkWriter).logRpcMessage(/*seq=*/
        eq(5L), eq(EventType.EVENT_TYPE_SERVER_MESSAGE), same(BYTEARRAY_MARSHALLER), same(response), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
        verifyNoMoreInteractions(mockSinkWriter);
        verify(mockListener).onMessage(same(response));
    }
    // receive trailer
    {
        Status status = Status.INTERNAL.withDescription("some description");
        Metadata trailers = new Metadata();
        interceptedListener.get().onClose(status, trailers);
        verify(mockSinkWriter).logTrailer(/*seq=*/
        eq(6L), same(status), same(trailers), eq(Logger.LOGGER_CLIENT), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
        verifyNoMoreInteractions(mockSinkWriter);
        verify(mockListener).onClose(same(status), same(trailers));
    }
    // cancel
    {
        interceptedCall.cancel(null, null);
        verify(mockSinkWriter).logCancel(/*seq=*/
        eq(7L), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
        cancelCalled.get(1, TimeUnit.SECONDS);
    }
}
Also used : Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) NoopClientCall(io.grpc.internal.NoopClientCall) ClientCall(io.grpc.ClientCall) NoopClientCall(io.grpc.internal.NoopClientCall) SocketAddress(java.net.SocketAddress) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) InetSocketAddress(java.net.InetSocketAddress) Status(io.grpc.Status) Channel(io.grpc.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(com.google.protobuf.Duration) MethodDescriptor(io.grpc.MethodDescriptor) Test(org.junit.Test)

Example 32 with CallOptions

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

the class BinlogHelperTest method clientDeadlineLogged_deadlineSetViaCallOption.

@Test
public void clientDeadlineLogged_deadlineSetViaCallOption() {
    MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
    @SuppressWarnings("unchecked") ClientCall.Listener<byte[]> mockListener = mock(ClientCall.Listener.class);
    ClientCall<byte[], byte[]> call = 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;
        }
    });
    call.start(mockListener, new Metadata());
    ArgumentCaptor<Duration> callOptTimeoutCaptor = ArgumentCaptor.forClass(Duration.class);
    verify(mockSinkWriter).logClientHeader(anyLong(), AdditionalMatchers.or(ArgumentMatchers.<String>isNull(), anyString()), AdditionalMatchers.or(ArgumentMatchers.<String>isNull(), anyString()), 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) 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 33 with CallOptions

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

the class ManagedChannelImplTest method subtestFailRpcFromBalancer.

private void subtestFailRpcFromBalancer(boolean waitForReady, boolean drop, boolean shouldFail) {
    createChannel();
    // This call will be buffered by the channel, thus involve delayed transport
    CallOptions callOptions = CallOptions.DEFAULT;
    if (waitForReady) {
        callOptions = callOptions.withWaitForReady();
    } else {
        callOptions = callOptions.withoutWaitForReady();
    }
    ClientCall<String, Integer> call1 = channel.newCall(method, callOptions);
    call1.start(mockCallListener, new Metadata());
    SubchannelPicker picker = mock(SubchannelPicker.class);
    Status status = Status.UNAVAILABLE.withDescription("for test");
    when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(drop ? PickResult.withDrop(status) : PickResult.withError(status));
    updateBalancingStateSafely(helper, READY, picker);
    executor.runDueTasks();
    if (shouldFail) {
        verify(mockCallListener).onClose(same(status), any(Metadata.class));
    } else {
        verifyNoInteractions(mockCallListener);
    }
    // This call doesn't involve delayed transport
    ClientCall<String, Integer> call2 = channel.newCall(method, callOptions);
    call2.start(mockCallListener2, new Metadata());
    executor.runDueTasks();
    if (shouldFail) {
        verify(mockCallListener2).onClose(same(status), any(Metadata.class));
    } else {
        verifyNoInteractions(mockCallListener2);
    }
}
Also used : Status(io.grpc.Status) SubchannelPicker(io.grpc.LoadBalancer.SubchannelPicker) Metadata(io.grpc.Metadata) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) CallOptions(io.grpc.CallOptions)

Example 34 with CallOptions

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

the class ManagedChannelImplTest method newCallWithConfigSelector.

@Test
public void newCallWithConfigSelector() {
    FakeNameResolverFactory nameResolverFactory = new FakeNameResolverFactory.Builder(expectedUri).setServers(ImmutableList.of(addressGroup)).build();
    channelBuilder.nameResolverFactory(nameResolverFactory);
    channel = new ManagedChannelImpl(channelBuilder, mockTransportFactory, new FakeBackoffPolicyProvider(), balancerRpcExecutorPool, timer.getStopwatchSupplier(), Collections.<ClientInterceptor>emptyList(), timer.getTimeProvider());
    nameResolverFactory.nextConfigOrError.set(ConfigOrError.fromConfig(ManagedChannelServiceConfig.empty()));
    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) {
            return Result.newBuilder().setConfig(ManagedChannelServiceConfig.empty()).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();
        }
    };
    nameResolverFactory.nextAttributes.set(Attributes.newBuilder().set(InternalConfigSelector.KEY, configSelector).build());
    channel.getState(true);
    Metadata headers = new Metadata();
    headers.put(metadataKey, "fooValue");
    ClientStream mockStream = mock(ClientStream.class);
    ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
    call.start(mockCallListener, headers);
    ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
    verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture());
    helper = helperCaptor.getValue();
    // Make the transport available
    Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
    requestConnectionSafely(helper, subchannel);
    verify(mockTransportFactory).newClientTransport(any(SocketAddress.class), any(ClientTransportOptions.class), any(ChannelLogger.class));
    MockClientTransportInfo transportInfo = transports.poll();
    ConnectionClientTransport mockTransport = transportInfo.transport;
    ManagedClientTransport.Listener transportListener = transportInfo.listener;
    when(mockTransport.newStream(same(method), same(headers), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any())).thenReturn(mockStream);
    transportListener.transportReady();
    when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
    updateBalancingStateSafely(helper, READY, mockPicker);
    executor.runDueTasks();
    ArgumentCaptor<CallOptions> callOptionsCaptor = ArgumentCaptor.forClass(null);
    verify(mockTransport).newStream(same(method), same(headers), callOptionsCaptor.capture(), ArgumentMatchers.<ClientStreamTracer[]>any());
    assertThat(callOptionsCaptor.getValue().getOption(callOptionsKey)).isEqualTo("fooValue");
    verify(mockStream).start(streamListenerCaptor.capture());
    // Clean up as much as possible to allow the channel to terminate.
    shutdownSafely(helper, subchannel);
    timer.forwardNanos(TimeUnit.SECONDS.toNanos(ManagedChannelImpl.SUBCHANNEL_SHUTDOWN_DELAY_SECONDS));
}
Also used : ClientStreamTracer(io.grpc.ClientStreamTracer) UnsupportedClientTransportFactoryBuilder(io.grpc.internal.ManagedChannelImplBuilder.UnsupportedClientTransportFactoryBuilder) ClientTransportFactoryBuilder(io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Helper(io.grpc.LoadBalancer.Helper) ClientInterceptor(io.grpc.ClientInterceptor) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) ChannelLogger(io.grpc.ChannelLogger) ProxiedSocketAddress(io.grpc.ProxiedSocketAddress) SocketAddress(java.net.SocketAddress) ClientTransportOptions(io.grpc.internal.ClientTransportFactory.ClientTransportOptions) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) MethodDescriptor(io.grpc.MethodDescriptor) InternalConfigSelector(io.grpc.InternalConfigSelector) ForwardingSubchannel(io.grpc.util.ForwardingSubchannel) Subchannel(io.grpc.LoadBalancer.Subchannel) Test(org.junit.Test)

Example 35 with CallOptions

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

the class ManagedChannelImplTest method pickerReturnsStreamTracer_delayed.

@Test
public void pickerReturnsStreamTracer_delayed() {
    ClientStream mockStream = mock(ClientStream.class);
    final ClientStreamTracer tracer1 = new ClientStreamTracer() {
    };
    final ClientStreamTracer tracer2 = new ClientStreamTracer() {
    };
    ClientStreamTracer.Factory factory1 = new ClientStreamTracer.Factory() {

        @Override
        public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
            return tracer1;
        }
    };
    ClientStreamTracer.Factory factory2 = new ClientStreamTracer.Factory() {

        @Override
        public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
            return tracer2;
        }
    };
    createChannel();
    CallOptions callOptions = CallOptions.DEFAULT.withStreamTracerFactory(factory1);
    ClientCall<String, Integer> call = channel.newCall(method, callOptions);
    call.start(mockCallListener, new Metadata());
    Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
    requestConnectionSafely(helper, subchannel);
    MockClientTransportInfo transportInfo = transports.poll();
    transportInfo.listener.transportReady();
    ClientTransport mockTransport = transportInfo.transport;
    when(mockTransport.newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any())).thenReturn(mockStream);
    when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel, factory2));
    updateBalancingStateSafely(helper, READY, mockPicker);
    assertEquals(1, executor.runDueTasks());
    verify(mockPicker).pickSubchannel(any(PickSubchannelArgs.class));
    verify(mockTransport).newStream(same(method), any(Metadata.class), callOptionsCaptor.capture(), tracersCaptor.capture());
    assertThat(tracersCaptor.getValue()).isEqualTo(new ClientStreamTracer[] { tracer1, tracer2 });
}
Also used : ClientStreamTracer(io.grpc.ClientStreamTracer) Metadata(io.grpc.Metadata) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) ForwardingSubchannel(io.grpc.util.ForwardingSubchannel) Subchannel(io.grpc.LoadBalancer.Subchannel) StreamInfo(io.grpc.ClientStreamTracer.StreamInfo) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) Test(org.junit.Test)

Aggregations

CallOptions (io.grpc.CallOptions)81 Test (org.junit.Test)61 Metadata (io.grpc.Metadata)50 Channel (io.grpc.Channel)36 MethodDescriptor (io.grpc.MethodDescriptor)28 ClientInterceptor (io.grpc.ClientInterceptor)23 ManagedChannel (io.grpc.ManagedChannel)18 ClientStreamTracer (io.grpc.ClientStreamTracer)17 ClientCall (io.grpc.ClientCall)15 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)11 Status (io.grpc.Status)11 Context (io.grpc.Context)10 Subchannel (io.grpc.LoadBalancer.Subchannel)10 MockClientTransportInfo (io.grpc.internal.TestUtils.MockClientTransportInfo)10 ForwardingSubchannel (io.grpc.util.ForwardingSubchannel)9 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)8 NoopClientCall (io.grpc.internal.NoopClientCall)8 SocketAddress (java.net.SocketAddress)8 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)7 ByteString (com.google.protobuf.ByteString)6