Search in sources :

Example 1 with MethodDescriptor

use of io.grpc.MethodDescriptor in project grpc-java by grpc.

the class ManagedChannelImplTest method informationPropagatedToNewStreamAndCallCredentials.

/**
   * Test that information such as the Call's context, MethodDescriptor, authority, executor are
   * propagated to newStream() and applyRequestMetadata().
   */
@Test
public void informationPropagatedToNewStreamAndCallCredentials() {
    ResolvedServerInfoGroup serverInfoGroup = ResolvedServerInfoGroup.builder().add(server).build();
    createChannel(new FakeNameResolverFactory(true), NO_INTERCEPTOR);
    CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(creds);
    final Context.Key<String> testKey = Context.key("testing");
    Context ctx = Context.current().withValue(testKey, "testValue");
    final LinkedList<Context> credsApplyContexts = new LinkedList<Context>();
    final LinkedList<Context> newStreamContexts = new LinkedList<Context>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock in) throws Throwable {
            credsApplyContexts.add(Context.current());
            return null;
        }
    }).when(creds).applyRequestMetadata(any(MethodDescriptor.class), any(Attributes.class), any(Executor.class), any(MetadataApplier.class));
    // First call will be on delayed transport.  Only newCall() is run within the expected context,
    // so that we can verify that the context is explicitly attached before calling newStream() and
    // applyRequestMetadata(), which happens after we detach the context from the thread.
    Context origCtx = ctx.attach();
    assertEquals("testValue", testKey.get());
    ClientCall<String, Integer> call = channel.newCall(method, callOptions);
    ctx.detach(origCtx);
    assertNull(testKey.get());
    call.start(mockCallListener, new Metadata());
    // Simulate name resolution results
    Subchannel subchannel = helper.createSubchannel(serverInfoGroup.toEquivalentAddressGroup(), Attributes.EMPTY);
    subchannel.requestConnection();
    verify(mockTransportFactory).newClientTransport(same(socketAddress), eq(authority), eq(userAgent));
    MockClientTransportInfo transportInfo = transports.poll();
    final ConnectionClientTransport transport = transportInfo.transport;
    when(transport.getAttributes()).thenReturn(Attributes.EMPTY);
    doAnswer(new Answer<ClientStream>() {

        @Override
        public ClientStream answer(InvocationOnMock in) throws Throwable {
            newStreamContexts.add(Context.current());
            return mock(ClientStream.class);
        }
    }).when(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    verify(creds, never()).applyRequestMetadata(any(MethodDescriptor.class), any(Attributes.class), any(Executor.class), any(MetadataApplier.class));
    // applyRequestMetadata() is called after the transport becomes ready.
    transportInfo.listener.transportReady();
    when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
    helper.updatePicker(mockPicker);
    executor.runDueTasks();
    ArgumentCaptor<Attributes> attrsCaptor = ArgumentCaptor.forClass(Attributes.class);
    ArgumentCaptor<MetadataApplier> applierCaptor = ArgumentCaptor.forClass(MetadataApplier.class);
    verify(creds).applyRequestMetadata(same(method), attrsCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
    assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
    assertEquals(authority, attrsCaptor.getValue().get(CallCredentials.ATTR_AUTHORITY));
    assertEquals(SecurityLevel.NONE, attrsCaptor.getValue().get(CallCredentials.ATTR_SECURITY_LEVEL));
    verify(transport, never()).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    // newStream() is called after apply() is called
    applierCaptor.getValue().apply(new Metadata());
    verify(transport).newStream(same(method), any(Metadata.class), same(callOptions), any(StatsTraceContext.class));
    assertEquals("testValue", testKey.get(newStreamContexts.poll()));
    // The context should not live beyond the scope of newStream() and applyRequestMetadata()
    assertNull(testKey.get());
    // Second call will not be on delayed transport
    origCtx = ctx.attach();
    call = channel.newCall(method, callOptions);
    ctx.detach(origCtx);
    call.start(mockCallListener, new Metadata());
    verify(creds, times(2)).applyRequestMetadata(same(method), attrsCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
    assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
    assertEquals(authority, attrsCaptor.getValue().get(CallCredentials.ATTR_AUTHORITY));
    assertEquals(SecurityLevel.NONE, attrsCaptor.getValue().get(CallCredentials.ATTR_SECURITY_LEVEL));
    // This is from the first call
    verify(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    // Still, newStream() is called after apply() is called
    applierCaptor.getValue().apply(new Metadata());
    verify(transport, times(2)).newStream(same(method), any(Metadata.class), same(callOptions), any(StatsTraceContext.class));
    assertEquals("testValue", testKey.get(newStreamContexts.poll()));
    assertNull(testKey.get());
}
Also used : Attributes(io.grpc.Attributes) Metadata(io.grpc.Metadata) ResolvedServerInfoGroup(io.grpc.ResolvedServerInfoGroup) CallOptions(io.grpc.CallOptions) Matchers.anyString(org.mockito.Matchers.anyString) Executor(java.util.concurrent.Executor) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) Context(io.grpc.Context) MetadataApplier(io.grpc.CallCredentials.MetadataApplier) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) MethodDescriptor(io.grpc.MethodDescriptor) LinkedList(java.util.LinkedList) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Subchannel(io.grpc.LoadBalancer.Subchannel) Test(org.junit.Test)

Example 2 with MethodDescriptor

use of io.grpc.MethodDescriptor in project grpc-java by grpc.

the class TransportCompressionTest method createChannel.

@Override
protected ManagedChannel createChannel() {
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress("localhost", getPort()).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(true);
    io.grpc.internal.TestingAccessor.setStatsContextFactory(builder, getClientStatsFactory());
    return builder.build();
}
Also used : ForwardingClientCallListener(io.grpc.ForwardingClientCallListener) Listener(io.grpc.ServerCall.Listener) ManagedChannel(io.grpc.ManagedChannel) 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) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) ForwardingClientCallListener(io.grpc.ForwardingClientCallListener)

Example 3 with MethodDescriptor

use of io.grpc.MethodDescriptor in project google-cloud-java by GoogleCloudPlatform.

the class WatchdogInterceptor method newDefaultWatchdogInterceptor.

/**
   * Creates a default instance based on the system property {@code
   * com.google.cloud.spanner.watchdogTimeoutSeconds}, or a no-op interceptor if none configured.
   */
@Nullable
static ClientInterceptor newDefaultWatchdogInterceptor() {
    int timeoutSeconds = systemProperty(PROPERTY_TIMEOUT_SECONDS, DEFAULT_TIMEOUT_SECONDS);
    if (timeoutSeconds <= 0) {
        return new ClientInterceptor() {

            @Override
            public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions, Channel channel) {
                return channel.newCall(methodDescriptor, callOptions);
            }
        };
    }
    int periodSeconds = systemProperty(PROPERTY_PERIOD_SECONDS, DEFAULT_PERIOD_SECONDS);
    final WatchdogInterceptor interceptor = new WatchdogInterceptor(timeoutSeconds, TimeUnit.SECONDS);
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Cloud-Spanner-WatchdogInterceptor-%d").build());
    executor.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            interceptor.tick();
        }
    }, periodSeconds, periodSeconds, TimeUnit.SECONDS);
    logger.log(Level.FINE, "Created watchdog interceptor with activity timeout of {0}s and period {1}s", new Object[] { timeoutSeconds, periodSeconds });
    return interceptor;
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Channel(io.grpc.Channel) ClientInterceptor(io.grpc.ClientInterceptor) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) Nullable(javax.annotation.Nullable)

Example 4 with MethodDescriptor

use of io.grpc.MethodDescriptor 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 = spy(responseListener);
                    super.start(responseListener, headers);
                }
            };
        }
    }
    SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
    GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(inProcessChannel).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) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) ClientInterceptor(io.grpc.ClientInterceptor) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) Test(org.junit.Test)

Example 5 with MethodDescriptor

use of 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(new FakeNameResolverFactory(true), Arrays.asList(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)

Aggregations

CallOptions (io.grpc.CallOptions)5 MethodDescriptor (io.grpc.MethodDescriptor)5 Channel (io.grpc.Channel)4 ClientInterceptor (io.grpc.ClientInterceptor)4 ManagedChannel (io.grpc.ManagedChannel)3 Metadata (io.grpc.Metadata)3 Test (org.junit.Test)3 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 ByteString (com.google.protobuf.ByteString)1 Attributes (io.grpc.Attributes)1 MetadataApplier (io.grpc.CallCredentials.MetadataApplier)1 ClientCall (io.grpc.ClientCall)1 Context (io.grpc.Context)1 ForwardingClientCall (io.grpc.ForwardingClientCall)1 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)1 ForwardingClientCallListener (io.grpc.ForwardingClientCallListener)1 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)1 Subchannel (io.grpc.LoadBalancer.Subchannel)1 ResolvedServerInfoGroup (io.grpc.ResolvedServerInfoGroup)1 Listener (io.grpc.ServerCall.Listener)1