Search in sources :

Example 31 with ServerCall

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

the class BinlogHelperTest method serverDeadlineLogged.

@Test
public void serverDeadlineLogged() {
    final MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
    final ServerCall<byte[], byte[]> noopServerCall = new NoopServerCall<byte[], byte[]>() {

        @Override
        public MethodDescriptor<byte[], byte[]> getMethodDescriptor() {
            return method;
        }
    };
    final ServerCallHandler<byte[], byte[]> noopHandler = new ServerCallHandler<byte[], byte[]>() {

        @Override
        public ServerCall.Listener<byte[]> startCall(ServerCall<byte[], byte[]> call, Metadata headers) {
            return new ServerCall.Listener<byte[]>() {
            };
        }
    };
    // Warm-up JVM
    new BinlogHelper(mock(SinkWriter.class)).getServerInterceptor(1234).interceptCall(noopServerCall, new Metadata(), noopHandler);
    // We expect the contents of the "grpc-timeout" header to be installed the context
    Context.current().withDeadlineAfter(1, TimeUnit.SECONDS, Executors.newSingleThreadScheduledExecutor()).run(new Runnable() {

        @Override
        public void run() {
            ServerCall.Listener<byte[]> unused = new BinlogHelper(mockSinkWriter).getServerInterceptor(CALL_ID).interceptCall(noopServerCall, new Metadata(), noopHandler);
        }
    });
    ArgumentCaptor<Duration> timeoutCaptor = ArgumentCaptor.forClass(Duration.class);
    verify(mockSinkWriter).logClientHeader(/*seq=*/
    eq(1L), eq("service/method"), ArgumentMatchers.<String>isNull(), timeoutCaptor.capture(), any(Metadata.class), eq(Logger.LOGGER_SERVER), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
    verifyNoMoreInteractions(mockSinkWriter);
    Duration timeout = timeoutCaptor.getValue();
    assertThat(TimeUnit.SECONDS.toNanos(1) - Durations.toNanos(timeout)).isAtMost(TimeUnit.MILLISECONDS.toNanos(250));
}
Also used : ServerCallHandler(io.grpc.ServerCallHandler) Metadata(io.grpc.Metadata) Duration(com.google.protobuf.Duration) SinkWriter(io.grpc.protobuf.services.BinlogHelper.SinkWriter) NoopServerCall(io.grpc.internal.NoopServerCall) NoopServerCall(io.grpc.internal.NoopServerCall) ServerCall(io.grpc.ServerCall) Test(org.junit.Test)

Example 32 with ServerCall

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

the class BinlogHelper method getServerInterceptor.

public ServerInterceptor getServerInterceptor(final long callId) {
    return new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            final AtomicLong seq = new AtomicLong(1);
            SocketAddress peer = getPeerSocket(call.getAttributes());
            String methodName = call.getMethodDescriptor().getFullMethodName();
            String authority = call.getAuthority();
            Deadline deadline = Context.current().getDeadline();
            final Duration timeout = deadline == null ? null : Durations.fromNanos(deadline.timeRemaining(TimeUnit.NANOSECONDS));
            writer.logClientHeader(seq.getAndIncrement(), methodName, authority, timeout, headers, GrpcLogEntry.Logger.LOGGER_SERVER, callId, peer);
            ServerCall<ReqT, RespT> wCall = new SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendMessage(RespT message) {
                    writer.logRpcMessage(seq.getAndIncrement(), EventType.EVENT_TYPE_SERVER_MESSAGE, call.getMethodDescriptor().getResponseMarshaller(), message, GrpcLogEntry.Logger.LOGGER_SERVER, callId);
                    super.sendMessage(message);
                }

                @Override
                public void sendHeaders(Metadata headers) {
                    writer.logServerHeader(seq.getAndIncrement(), headers, GrpcLogEntry.Logger.LOGGER_SERVER, callId, /*peerAddress=*/
                    null);
                    super.sendHeaders(headers);
                }

                @Override
                public void close(Status status, Metadata trailers) {
                    writer.logTrailer(seq.getAndIncrement(), status, trailers, GrpcLogEntry.Logger.LOGGER_SERVER, callId, /*peerAddress=*/
                    null);
                    super.close(status, trailers);
                }
            };
            return new SimpleForwardingServerCallListener<ReqT>(next.startCall(wCall, headers)) {

                @Override
                public void onMessage(ReqT message) {
                    writer.logRpcMessage(seq.getAndIncrement(), EventType.EVENT_TYPE_CLIENT_MESSAGE, call.getMethodDescriptor().getRequestMarshaller(), message, GrpcLogEntry.Logger.LOGGER_SERVER, callId);
                    super.onMessage(message);
                }

                @Override
                public void onHalfClose() {
                    writer.logHalfClose(seq.getAndIncrement(), GrpcLogEntry.Logger.LOGGER_SERVER, callId);
                    super.onHalfClose();
                }

                @Override
                public void onCancel() {
                    writer.logCancel(seq.getAndIncrement(), GrpcLogEntry.Logger.LOGGER_SERVER, callId);
                    super.onCancel();
                }
            };
        }
    };
}
Also used : Status(io.grpc.Status) ServerCallHandler(io.grpc.ServerCallHandler) Deadline(io.grpc.Deadline) Metadata(io.grpc.Metadata) InternalMetadata(io.grpc.InternalMetadata) Duration(com.google.protobuf.Duration) ByteString(com.google.protobuf.ByteString) SimpleForwardingServerCall(io.grpc.ForwardingServerCall.SimpleForwardingServerCall) SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) AtomicLong(java.util.concurrent.atomic.AtomicLong) SimpleForwardingServerCall(io.grpc.ForwardingServerCall.SimpleForwardingServerCall) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 33 with ServerCall

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

the class ServerImplTest method testStreamClose_setup.

private ServerStreamListener testStreamClose_setup(final AtomicReference<ServerCall<String, Integer>> callReference, final AtomicReference<Context> context, final AtomicBoolean contextCancelled, @Nullable Long timeoutNanos) throws Exception {
    createAndStartServer();
    callListener = new ServerCall.Listener<String>() {

        @Override
        public void onReady() {
            context.set(Context.current());
            Context.current().addListener(new Context.CancellationListener() {

                @Override
                public void cancelled(Context context) {
                    contextCancelled.set(true);
                }
            }, MoreExecutors.directExecutor());
        }
    };
    mutableFallbackRegistry.addService(ServerServiceDefinition.builder(new ServiceDescriptor("Waiter", METHOD)).addMethod(METHOD, new ServerCallHandler<String, Integer>() {

        @Override
        public ServerCall.Listener<String> startCall(ServerCall<String, Integer> call, Metadata headers) {
            callReference.set(call);
            return callListener;
        }
    }).build());
    ServerTransportListener transportListener = transportServer.registerNewServerTransport(new SimpleServerTransport());
    transportListener.transportReady(Attributes.EMPTY);
    Metadata requestHeaders = new Metadata();
    if (timeoutNanos != null) {
        requestHeaders.put(TIMEOUT_KEY, timeoutNanos);
    }
    StatsTraceContext statsTraceCtx = StatsTraceContext.newServerContext(streamTracerFactories, "Waitier/serve", requestHeaders);
    when(stream.statsTraceContext()).thenReturn(statsTraceCtx);
    transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
    verify(stream).setListener(streamListenerCaptor.capture());
    ServerStreamListener streamListener = streamListenerCaptor.getValue();
    assertNotNull(streamListener);
    streamListener.onReady();
    assertEquals(1, executor.runDueTasks());
    return streamListener;
}
Also used : Context(io.grpc.Context) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Listener(io.grpc.ServerCall.Listener) Metadata(io.grpc.Metadata) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerCall(io.grpc.ServerCall) ServiceDescriptor(io.grpc.ServiceDescriptor) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener)

Example 34 with ServerCall

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

the class ServerImplTest method testCallContextIsBoundInListenerCallbacks.

@Test
public void testCallContextIsBoundInListenerCallbacks() throws Exception {
    createAndStartServer();
    final AtomicBoolean onReadyCalled = new AtomicBoolean(false);
    final AtomicBoolean onMessageCalled = new AtomicBoolean(false);
    final AtomicBoolean onHalfCloseCalled = new AtomicBoolean(false);
    final AtomicBoolean onCancelCalled = new AtomicBoolean(false);
    mutableFallbackRegistry.addService(ServerServiceDefinition.builder(new ServiceDescriptor("Waiter", METHOD)).addMethod(METHOD, new ServerCallHandler<String, Integer>() {

        @Override
        public ServerCall.Listener<String> startCall(ServerCall<String, Integer> call, Metadata headers) {
            // Check that the current context is a descendant of SERVER_CONTEXT
            final Context initial = Context.current();
            assertEquals("yes", SERVER_ONLY.get(initial));
            assertNotSame(SERVER_CONTEXT, initial);
            assertFalse(initial.isCancelled());
            return new ServerCall.Listener<String>() {

                @Override
                public void onReady() {
                    checkContext();
                    onReadyCalled.set(true);
                }

                @Override
                public void onMessage(String message) {
                    checkContext();
                    onMessageCalled.set(true);
                }

                @Override
                public void onHalfClose() {
                    checkContext();
                    onHalfCloseCalled.set(true);
                }

                @Override
                public void onCancel() {
                    checkContext();
                    onCancelCalled.set(true);
                }

                @Override
                public void onComplete() {
                    checkContext();
                }

                private void checkContext() {
                    // Check that the bound context is the same as the initial one.
                    assertSame(initial, Context.current());
                }
            };
        }
    }).build());
    ServerTransportListener transportListener = transportServer.registerNewServerTransport(new SimpleServerTransport());
    transportListener.transportReady(Attributes.EMPTY);
    Metadata requestHeaders = new Metadata();
    StatsTraceContext statsTraceCtx = StatsTraceContext.newServerContext(streamTracerFactories, "Waitier/serve", requestHeaders);
    when(stream.statsTraceContext()).thenReturn(statsTraceCtx);
    transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
    verify(stream).setListener(streamListenerCaptor.capture());
    ServerStreamListener streamListener = streamListenerCaptor.getValue();
    assertNotNull(streamListener);
    streamListener.onReady();
    assertEquals(1, executor.runDueTasks());
    assertTrue(onReadyCalled.get());
    streamListener.messagesAvailable(new SingleMessageProducer(new ByteArrayInputStream(new byte[0])));
    assertEquals(1, executor.runDueTasks());
    assertTrue(onMessageCalled.get());
    streamListener.halfClosed();
    assertEquals(1, executor.runDueTasks());
    assertTrue(onHalfCloseCalled.get());
    streamListener.closed(Status.CANCELLED);
    assertEquals(1, executor.numPendingTasks(CONTEXT_CLOSER_TASK_FITLER));
    assertEquals(2, executor.runDueTasks());
    assertTrue(onCancelCalled.get());
    // Close should never be called if asserts in listener pass.
    verify(stream, times(0)).close(isA(Status.class), ArgumentMatchers.<Metadata>isNotNull());
}
Also used : Context(io.grpc.Context) Status(io.grpc.Status) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Listener(io.grpc.ServerCall.Listener) Metadata(io.grpc.Metadata) SingleMessageProducer(io.grpc.internal.testing.SingleMessageProducer) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerCall(io.grpc.ServerCall) ByteArrayInputStream(java.io.ByteArrayInputStream) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Test(org.junit.Test)

Example 35 with ServerCall

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

the class ServerImplTest method binaryLogInstalled.

@Test
public void binaryLogInstalled() throws Exception {
    final SettableFuture<Boolean> intercepted = SettableFuture.create();
    final ServerInterceptor interceptor = new ServerInterceptor() {

        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            intercepted.set(true);
            return next.startCall(call, headers);
        }
    };
    builder.binlog = new BinaryLog() {

        @Override
        public void close() throws IOException {
        // noop
        }

        @Override
        public <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition(ServerMethodDefinition<ReqT, RespT> oMethodDef) {
            return ServerMethodDefinition.create(oMethodDef.getMethodDescriptor(), InternalServerInterceptors.interceptCallHandlerCreate(interceptor, oMethodDef.getServerCallHandler()));
        }

        @Override
        public Channel wrapChannel(Channel channel) {
            return channel;
        }
    };
    createAndStartServer();
    basicExchangeHelper(METHOD, "Lots of pizza, please", 314, 50);
    assertTrue(intercepted.get());
}
Also used : ServerCallHandler(io.grpc.ServerCallHandler) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) IOException(java.io.IOException) BinaryLog(io.grpc.BinaryLog) ServerMethodDefinition(io.grpc.ServerMethodDefinition) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Aggregations

ServerCall (io.grpc.ServerCall)52 Metadata (io.grpc.Metadata)48 Test (org.junit.Test)42 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)19 ServerCallHandler (io.grpc.ServerCallHandler)14 Status (io.grpc.Status)14 Context (io.grpc.Context)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 JumpToApplicationThreadServerStreamListener (io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener)10 Server (io.grpc.Server)9 ServerInterceptor (io.grpc.ServerInterceptor)9 ServiceDescriptor (io.grpc.ServiceDescriptor)9 IOException (java.io.IOException)8 ExecutionException (java.util.concurrent.ExecutionException)8 StatusException (io.grpc.StatusException)7 TimeoutException (java.util.concurrent.TimeoutException)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)7 Listener (io.grpc.ServerCall.Listener)6 StatusRuntimeException (io.grpc.StatusRuntimeException)5