Search in sources :

Example 31 with MethodDescriptor

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

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

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

the class BinaryLogProviderTest method wrapChannel_handler.

@Test
public void wrapChannel_handler() throws Exception {
    final List<byte[]> serializedReq = new ArrayList<>();
    final AtomicReference<ClientCall.Listener<?>> listener = new AtomicReference<>();
    Channel channel = new Channel() {

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

                @Override
                public void start(ClientCall.Listener<ResponseT> responseListener, Metadata headers) {
                    listener.set(responseListener);
                }

                @Override
                public void sendMessage(RequestT message) {
                    serializedReq.add((byte[]) message);
                }
            };
        }

        @Override
        public String authority() {
            throw new UnsupportedOperationException();
        }
    };
    Channel wChannel = binlogProvider.wrapChannel(channel);
    ClientCall<String, Integer> clientCall = wChannel.newCall(method, CallOptions.DEFAULT);
    final List<Integer> observedResponse = new ArrayList<>();
    clientCall.start(new NoopClientCall.NoopClientCallListener<Integer>() {

        @Override
        public void onMessage(Integer message) {
            observedResponse.add(message);
        }
    }, new Metadata());
    String expectedRequest = "hello world";
    assertThat(binlogReq).isEmpty();
    assertThat(serializedReq).isEmpty();
    assertEquals(0, reqMarshaller.streamInvocations);
    clientCall.sendMessage(expectedRequest);
    // it is unacceptably expensive for the binlog to double parse every logged message
    assertEquals(1, reqMarshaller.streamInvocations);
    assertEquals(0, reqMarshaller.parseInvocations);
    assertThat(binlogReq).hasSize(1);
    assertThat(serializedReq).hasSize(1);
    assertEquals(expectedRequest, StringMarshaller.INSTANCE.parse(new ByteArrayInputStream(binlogReq.get(0))));
    assertEquals(expectedRequest, StringMarshaller.INSTANCE.parse(new ByteArrayInputStream(serializedReq.get(0))));
    int expectedResponse = 12345;
    assertThat(binlogResp).isEmpty();
    assertThat(observedResponse).isEmpty();
    assertEquals(0, respMarshaller.parseInvocations);
    onClientMessageHelper(listener.get(), IntegerMarshaller.INSTANCE.stream(expectedResponse));
    // it is unacceptably expensive for the binlog to double parse every logged message
    assertEquals(1, respMarshaller.parseInvocations);
    assertEquals(0, respMarshaller.streamInvocations);
    assertThat(binlogResp).hasSize(1);
    assertThat(observedResponse).hasSize(1);
    assertEquals(expectedResponse, (int) IntegerMarshaller.INSTANCE.parse(new ByteArrayInputStream(binlogResp.get(0))));
    assertEquals(expectedResponse, (int) observedResponse.get(0));
}
Also used : SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Channel(io.grpc.Channel) ArrayList(java.util.ArrayList) Metadata(io.grpc.Metadata) AtomicReference(java.util.concurrent.atomic.AtomicReference) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) NoopClientCall(io.grpc.internal.NoopClientCall) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.junit.Test)

Example 34 with MethodDescriptor

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

the class BinaryLogProviderTest method wrapChannel_methodDescriptor.

@Test
public void wrapChannel_methodDescriptor() throws Exception {
    final AtomicReference<MethodDescriptor<?, ?>> methodRef = new AtomicReference<>();
    Channel channel = new Channel() {

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

        @Override
        public String authority() {
            throw new UnsupportedOperationException();
        }
    };
    Channel wChannel = binlogProvider.wrapChannel(channel);
    ClientCall<String, Integer> unusedClientCall = wChannel.newCall(method, CallOptions.DEFAULT);
    validateWrappedMethod(methodRef.get());
}
Also used : NoopClientCall(io.grpc.internal.NoopClientCall) Channel(io.grpc.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) Test(org.junit.Test)

Example 35 with MethodDescriptor

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

the class RetryPolicyTest method getRetryPolicies.

@Test
public void getRetryPolicies() throws Exception {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(RetryPolicyTest.class.getResourceAsStream("/io/grpc/internal/test_retry_service_config.json"), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
        Object serviceConfigObj = JsonParser.parse(sb.toString());
        assertTrue(serviceConfigObj instanceof Map);
        @SuppressWarnings("unchecked") Map<String, ?> serviceConfig = (Map<String, ?>) serviceConfigObj;
        ManagedChannelServiceConfig channelServiceConfig = ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, /* retryEnabled= */
        true, /* maxRetryAttemptsLimit= */
        4, /* maxHedgedAttemptsLimit= */
        3, /* loadBalancingConfig= */
        null);
        MethodDescriptor.Builder<Void, Void> builder = TestMethodDescriptors.voidMethod().toBuilder();
        MethodDescriptor<Void, Void> method = builder.setFullMethodName("not/exist").build();
        assertThat(channelServiceConfig.getMethodConfig(method)).isNull();
        method = builder.setFullMethodName("not_exist/Foo1").build();
        assertThat(channelServiceConfig.getMethodConfig(method)).isNull();
        method = builder.setFullMethodName("SimpleService1/not_exist").build();
        assertThat(channelServiceConfig.getMethodConfig(method).retryPolicy).isEqualTo(new RetryPolicy(3, TimeUnit.MILLISECONDS.toNanos(2100), TimeUnit.MILLISECONDS.toNanos(2200), parseDouble("3"), null, ImmutableSet.of(Code.UNAVAILABLE, Code.RESOURCE_EXHAUSTED)));
        method = builder.setFullMethodName("SimpleService1/Foo1").build();
        assertThat(channelServiceConfig.getMethodConfig(method).retryPolicy).isEqualTo(new RetryPolicy(4, TimeUnit.MILLISECONDS.toNanos(100), TimeUnit.MILLISECONDS.toNanos(1000), parseDouble("2"), null, ImmutableSet.of(Code.UNAVAILABLE)));
        method = builder.setFullMethodName("SimpleService2/not_exist").build();
        assertThat(channelServiceConfig.getMethodConfig(method).retryPolicy).isNull();
        method = builder.setFullMethodName("SimpleService2/Foo2").build();
        assertThat(channelServiceConfig.getMethodConfig(method).retryPolicy).isEqualTo(new RetryPolicy(4, TimeUnit.MILLISECONDS.toNanos(100), TimeUnit.MILLISECONDS.toNanos(1000), parseDouble("2"), null, ImmutableSet.of(Code.UNAVAILABLE)));
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) MethodDescriptor(io.grpc.MethodDescriptor) BufferedReader(java.io.BufferedReader) Map(java.util.Map) Test(org.junit.Test)

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