Search in sources :

Example 6 with ServiceDescriptor

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

the class HandlerRegistryBenchmark method setup.

/**
   * Set up the registry.
   */
@Setup(Level.Trial)
public void setup() throws Exception {
    registry = new MutableHandlerRegistry();
    fullMethodNames = new ArrayList<String>(serviceCount * methodCountPerService);
    for (int serviceIndex = 0; serviceIndex < serviceCount; ++serviceIndex) {
        String serviceName = randomString();
        ServerServiceDefinition.Builder serviceBuilder = ServerServiceDefinition.builder(new ServiceDescriptor(serviceName));
        for (int methodIndex = 0; methodIndex < methodCountPerService; ++methodIndex) {
            String methodName = randomString();
            MethodDescriptor<Void, Void> methodDescriptor = MethodDescriptor.<Void, Void>newBuilder().setType(MethodDescriptor.MethodType.UNKNOWN).setFullMethodName(MethodDescriptor.generateFullMethodName(serviceName, methodName)).setRequestMarshaller(TestMethodDescriptors.voidMarshaller()).setResponseMarshaller(TestMethodDescriptors.voidMarshaller()).build();
            serviceBuilder.addMethod(methodDescriptor, new ServerCallHandler<Void, Void>() {

                @Override
                public Listener<Void> startCall(ServerCall<Void, Void> call, Metadata headers) {
                    return null;
                }
            });
            fullMethodNames.add(methodDescriptor.getFullMethodName());
        }
        registry.addService(serviceBuilder.build());
    }
}
Also used : Listener(io.grpc.ServerCall.Listener) MutableHandlerRegistry(io.grpc.util.MutableHandlerRegistry) Metadata(io.grpc.Metadata) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerServiceDefinition(io.grpc.ServerServiceDefinition) Setup(org.openjdk.jmh.annotations.Setup)

Example 7 with ServiceDescriptor

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

the class ServerImplTest method testCallContextIsBoundInListenerCallbacks.

@Test
public void testCallContextIsBoundInListenerCallbacks() throws Exception {
    createAndStartServer(NO_FILTERS);
    MethodDescriptor<String, Integer> method = MethodDescriptor.<String, Integer>newBuilder().setType(MethodDescriptor.MethodType.UNKNOWN).setFullMethodName("Waiter/serve").setRequestMarshaller(STRING_MARSHALLER).setResponseMarshaller(INTEGER_MARSHALLER).build();
    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());
    Metadata requestHeaders = new Metadata();
    StatsTraceContext statsTraceCtx = transportListener.methodDetermined("Waiter/serve", requestHeaders);
    assertNotNull(statsTraceCtx);
    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.messageRead(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.runDueTasks());
    assertTrue(onCancelCalled.get());
    // Close should never be called if asserts in listener pass.
    verify(stream, times(0)).close(isA(Status.class), isNotNull(Metadata.class));
}
Also used : Context(io.grpc.Context) StatsContext(com.google.instrumentation.stats.StatsContext) Status(io.grpc.Status) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Metadata(io.grpc.Metadata) 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 8 with ServiceDescriptor

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

the class MutableHandlerRegistryTest method replaceAndLookup.

@Test
public void replaceAndLookup() {
    assertNull(registry.addService(basicServiceDefinition));
    assertNotNull(registry.lookupMethod("basic/flow"));
    MethodDescriptor<String, Integer> anotherMethod = MethodDescriptor.<String, Integer>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("basic/another").setRequestMarshaller(requestMarshaller).setResponseMarshaller(responseMarshaller).build();
    ServerServiceDefinition replaceServiceDefinition = ServerServiceDefinition.builder(new ServiceDescriptor("basic", anotherMethod)).addMethod(anotherMethod, flowHandler).build();
    ServerMethodDefinition<?, ?> anotherMethodDefinition = replaceServiceDefinition.getMethod("basic/another");
    assertSame(basicServiceDefinition, registry.addService(replaceServiceDefinition));
    assertNull(registry.lookupMethod("basic/flow"));
    ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/another");
    assertSame(anotherMethodDefinition, method);
}
Also used : ServiceDescriptor(io.grpc.ServiceDescriptor) ServerServiceDefinition(io.grpc.ServerServiceDefinition) Test(org.junit.Test)

Example 9 with ServiceDescriptor

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

the class MutableHandlerRegistryTest method setUp.

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    MethodDescriptor<String, Integer> flowMethod = MethodDescriptor.<String, Integer>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("basic/flow").setRequestMarshaller(requestMarshaller).setResponseMarshaller(responseMarshaller).build();
    basicServiceDefinition = ServerServiceDefinition.builder(new ServiceDescriptor("basic", flowMethod)).addMethod(flowMethod, flowHandler).build();
    MethodDescriptor<String, Integer> coupleMethod = flowMethod.toBuilder().setFullMethodName("multi/couple").build();
    MethodDescriptor<String, Integer> fewMethod = flowMethod.toBuilder().setFullMethodName("multi/few").build();
    multiServiceDefinition = ServerServiceDefinition.builder(new ServiceDescriptor("multi", coupleMethod, fewMethod)).addMethod(coupleMethod, coupleHandler).addMethod(fewMethod, fewHandler).build();
    flowMethodDefinition = getOnlyElement(basicServiceDefinition.getMethods());
}
Also used : ServiceDescriptor(io.grpc.ServiceDescriptor) Before(org.junit.Before)

Example 10 with ServiceDescriptor

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

the class ServerImplTest method basicExchangeSuccessful.

@Test
public void basicExchangeSuccessful() throws Exception {
    createAndStartServer(NO_FILTERS);
    final Metadata.Key<String> metadataKey = Metadata.Key.of("inception", Metadata.ASCII_STRING_MARSHALLER);
    final Metadata.Key<StatsContext> statsHeaderKey = StatsTraceContext.createStatsHeader(statsCtxFactory);
    final AtomicReference<ServerCall<String, Integer>> callReference = new AtomicReference<ServerCall<String, Integer>>();
    MethodDescriptor<String, Integer> method = MethodDescriptor.<String, Integer>newBuilder().setType(MethodDescriptor.MethodType.UNKNOWN).setFullMethodName("Waiter/serve").setRequestMarshaller(STRING_MARSHALLER).setResponseMarshaller(INTEGER_MARSHALLER).build();
    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) {
            assertEquals("Waiter/serve", call.getMethodDescriptor().getFullMethodName());
            assertNotNull(call);
            assertNotNull(headers);
            assertEquals("value", headers.get(metadataKey));
            callReference.set(call);
            return callListener;
        }
    }).build());
    ServerTransportListener transportListener = transportServer.registerNewServerTransport(new SimpleServerTransport());
    Metadata requestHeaders = new Metadata();
    requestHeaders.put(metadataKey, "value");
    StatsContext statsContextOnClient = statsCtxFactory.getDefault().with(StatsTestUtils.EXTRA_TAG, TagValue.create("extraTagValue"));
    requestHeaders.put(statsHeaderKey, statsContextOnClient);
    StatsTraceContext statsTraceCtx = transportListener.methodDetermined("Waiter/serve", requestHeaders);
    assertNotNull(statsTraceCtx);
    when(stream.statsTraceContext()).thenReturn(statsTraceCtx);
    transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
    verify(stream).setListener(streamListenerCaptor.capture());
    ServerStreamListener streamListener = streamListenerCaptor.getValue();
    assertNotNull(streamListener);
    verify(stream, atLeast(1)).statsTraceContext();
    assertEquals(1, executor.runDueTasks());
    ServerCall<String, Integer> call = callReference.get();
    assertNotNull(call);
    verify(stream).getAuthority();
    String order = "Lots of pizza, please";
    streamListener.messageRead(STRING_MARSHALLER.stream(order));
    assertEquals(1, executor.runDueTasks());
    verify(callListener).onMessage(order);
    Metadata responseHeaders = new Metadata();
    responseHeaders.put(metadataKey, "response value");
    call.sendHeaders(responseHeaders);
    verify(stream).writeHeaders(responseHeaders);
    verify(stream).setCompressor(isA(Compressor.class));
    call.sendMessage(314);
    ArgumentCaptor<InputStream> inputCaptor = ArgumentCaptor.forClass(InputStream.class);
    verify(stream).writeMessage(inputCaptor.capture());
    verify(stream).flush();
    assertEquals(314, INTEGER_MARSHALLER.parse(inputCaptor.getValue()).intValue());
    // All full; no dessert.
    streamListener.halfClosed();
    assertEquals(1, executor.runDueTasks());
    verify(callListener).onHalfClose();
    call.sendMessage(50);
    verify(stream, times(2)).writeMessage(inputCaptor.capture());
    verify(stream, times(2)).flush();
    assertEquals(50, INTEGER_MARSHALLER.parse(inputCaptor.getValue()).intValue());
    Metadata trailers = new Metadata();
    trailers.put(metadataKey, "another value");
    Status status = Status.OK.withDescription("A okay");
    call.close(status, trailers);
    verify(stream).close(status, trailers);
    streamListener.closed(Status.OK);
    assertEquals(1, executor.runDueTasks());
    verify(callListener).onComplete();
    verify(stream, atLeast(1)).statsTraceContext();
    verifyNoMoreInteractions(stream);
    verifyNoMoreInteractions(callListener);
    // Check stats
    StatsTestUtils.MetricsRecord record = statsCtxFactory.pollRecord();
    assertNotNull(record);
    TagValue methodTag = record.tags.get(RpcConstants.RPC_SERVER_METHOD);
    assertNotNull(methodTag);
    assertEquals("Waiter/serve", methodTag.toString());
    TagValue statusTag = record.tags.get(RpcConstants.RPC_STATUS);
    assertNotNull(statusTag);
    assertEquals(Status.Code.OK.toString(), statusTag.toString());
    TagValue extraTag = record.tags.get(StatsTestUtils.EXTRA_TAG);
    assertNotNull(extraTag);
    assertEquals("extraTagValue", extraTag.toString());
    assertNull(record.getMetric(RpcConstants.RPC_CLIENT_REQUEST_BYTES));
    assertNull(record.getMetric(RpcConstants.RPC_CLIENT_RESPONSE_BYTES));
    assertNull(record.getMetric(RpcConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
    assertNull(record.getMetric(RpcConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
    // The test doesn't invoke MessageFramer and MessageDeframer which keep the sizes.
    // Thus the sizes reported to stats would be zero.
    assertEquals(0, record.getMetricAsLongOrFail(RpcConstants.RPC_SERVER_REQUEST_BYTES));
    assertEquals(0, record.getMetricAsLongOrFail(RpcConstants.RPC_SERVER_RESPONSE_BYTES));
    assertEquals(0, record.getMetricAsLongOrFail(RpcConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
    assertEquals(0, record.getMetricAsLongOrFail(RpcConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
}
Also used : JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) StatsTestUtils(io.grpc.internal.testing.StatsTestUtils) Metadata(io.grpc.Metadata) ServerCall(io.grpc.ServerCall) ServiceDescriptor(io.grpc.ServiceDescriptor) StatsContext(com.google.instrumentation.stats.StatsContext) TagValue(com.google.instrumentation.stats.TagValue) Status(io.grpc.Status) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Compressor(io.grpc.Compressor) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Test(org.junit.Test)

Aggregations

ServiceDescriptor (io.grpc.ServiceDescriptor)12 Test (org.junit.Test)9 Metadata (io.grpc.Metadata)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 ServerServiceDefinition (io.grpc.ServerServiceDefinition)5 ServerCall (io.grpc.ServerCall)4 Status (io.grpc.Status)4 JumpToApplicationThreadServerStreamListener (io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener)4 StatsContext (com.google.instrumentation.stats.StatsContext)3 Semaphore (java.util.concurrent.Semaphore)3 Context (io.grpc.Context)2 NoopStreamObserver (io.grpc.stub.ServerCalls.NoopStreamObserver)2 MutableHandlerRegistry (io.grpc.util.MutableHandlerRegistry)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ArrayList (java.util.ArrayList)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 TagValue (com.google.instrumentation.stats.TagValue)1 ClientCall (io.grpc.ClientCall)1