Search in sources :

Example 11 with StreamObserver

use of io.grpc.stub.StreamObserver in project grpc-java by grpc.

the class MoreInProcessTest method asyncClientStreaming_serverResponsePriorToRequest.

@Test
public void asyncClientStreaming_serverResponsePriorToRequest() throws Exception {
    // implement a service
    final StreamingInputCallResponse fakeResponse = StreamingInputCallResponse.newBuilder().setAggregatedPayloadSize(100).build();
    TestServiceImplBase clientStreamingImpl = new TestServiceImplBase() {

        @Override
        public StreamObserver<StreamingInputCallRequest> streamingInputCall(StreamObserver<StreamingInputCallResponse> responseObserver) {
            // send response directly
            responseObserver.onNext(fakeResponse);
            responseObserver.onCompleted();
            return new StreamObserver<StreamingInputCallRequest>() {

                @Override
                public void onNext(StreamingInputCallRequest value) {
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onCompleted() {
                }
            };
        }
    };
    serviceRegistry.addService(clientStreamingImpl);
    // implement a client
    final CountDownLatch finishLatch = new CountDownLatch(1);
    final AtomicReference<StreamingInputCallResponse> responseRef = new AtomicReference<StreamingInputCallResponse>();
    final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
    StreamObserver<StreamingInputCallResponse> responseObserver = new StreamObserver<StreamingInputCallResponse>() {

        @Override
        public void onNext(StreamingInputCallResponse response) {
            responseRef.set(response);
        }

        @Override
        public void onError(Throwable t) {
            throwableRef.set(t);
            finishLatch.countDown();
        }

        @Override
        public void onCompleted() {
            finishLatch.countDown();
        }
    };
    // make a gRPC call
    TestServiceGrpc.newStub(inProcessChannel).streamingInputCall(responseObserver);
    assertTrue(finishLatch.await(900, TimeUnit.MILLISECONDS));
    assertEquals(fakeResponse, responseRef.get());
    assertNull(throwableRef.get());
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) StreamingInputCallRequest(io.grpc.testing.integration.Messages.StreamingInputCallRequest) TestServiceImplBase(io.grpc.testing.integration.TestServiceGrpc.TestServiceImplBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingInputCallResponse(io.grpc.testing.integration.Messages.StreamingInputCallResponse) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 12 with StreamObserver

use of io.grpc.stub.StreamObserver in project core-java by SpineEventEngine.

the class CommandRouterOnErrorShould method createRouter.

/**
     * Creates a router with mocked {@code CommandBus} which always calls
     * {@link StreamObserver#onError(Throwable) StreamObserver.onError()} when
     * {@link CommandBus#post(Command, StreamObserver) CommandBus.post()} is invoked.
     */
@Override
CommandRouter createRouter(CommandBus ignored, Message sourceMessage, CommandContext commandContext) {
    final CommandBus mockBus = mock(CommandBus.class);
    doAnswer(new Answer() {

        // is OK for Answer
        @SuppressWarnings("ReturnOfNull")
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final StreamObserver<Response> observer = invocation.getArgument(1);
            observer.onError(new RuntimeException("simulate error"));
            return null;
        }
    }).when(mockBus).post(any(Command.class), ArgumentMatchers.<StreamObserver<Response>>any());
    return new CommandRouter(mockBus, sourceMessage, commandContext);
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) Response(io.spine.base.Response) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) CommandRouter(io.spine.server.procman.CommandRouter) Command(io.spine.base.Command) InvocationOnMock(org.mockito.invocation.InvocationOnMock) CommandBus(io.spine.server.commandbus.CommandBus)

Example 13 with StreamObserver

use of io.grpc.stub.StreamObserver in project beam by apache.

the class BeamFnLoggingClientTest method testLogging.

@Test
public void testLogging() throws Exception {
    AtomicBoolean clientClosedStream = new AtomicBoolean();
    Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
    AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver = new AtomicReference<>();
    CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver = TestStreams.withOnNext((BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList())).withOnCompleted(new Runnable() {

        @Override
        public void run() {
            // Remember that the client told us that this stream completed
            clientClosedStream.set(true);
            outboundServerObserver.get().onCompleted();
        }
    }).build();
    BeamFnApi.ApiServiceDescriptor apiServiceDescriptor = BeamFnApi.ApiServiceDescriptor.newBuilder().setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString()).build();
    Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl()).addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {

        @Override
        public StreamObserver<BeamFnApi.LogEntry.List> logging(StreamObserver<BeamFnApi.LogControl> outboundObserver) {
            outboundServerObserver.set(outboundObserver);
            return inboundServerObserver;
        }
    }).build();
    server.start();
    try {
        ManagedChannel channel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
        BeamFnLoggingClient client = new BeamFnLoggingClient(PipelineOptionsFactory.fromArgs(new String[] { "--defaultWorkerLogLevel=OFF", "--workerLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}" }).create(), apiServiceDescriptor, (BeamFnApi.ApiServiceDescriptor descriptor) -> channel, this::createStreamForTest);
        // Ensure that log levels were correctly set.
        assertEquals(Level.OFF, LogManager.getLogManager().getLogger("").getLevel());
        assertEquals(Level.FINE, LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());
        // Should be filtered because the default log level override is OFF
        LogManager.getLogManager().getLogger("").log(FILTERED_RECORD);
        // Should not be filtered because the default log level override for ConfiguredLogger is DEBUG
        LogManager.getLogManager().getLogger("ConfiguredLogger").log(TEST_RECORD);
        LogManager.getLogManager().getLogger("ConfiguredLogger").log(TEST_RECORD_WITH_EXCEPTION);
        client.close();
        // Verify that after close, log levels are reset.
        assertEquals(Level.INFO, LogManager.getLogManager().getLogger("").getLevel());
        assertNull(LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());
        assertTrue(clientClosedStream.get());
        assertTrue(channel.isShutdown());
        assertThat(values, contains(TEST_ENTRY, TEST_ENTRY_WITH_EXCEPTION));
    } finally {
        server.shutdownNow();
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) CallStreamObserver(io.grpc.stub.CallStreamObserver) Server(io.grpc.Server) BeamFnApi(org.apache.beam.fn.v1.BeamFnApi) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedChannel(io.grpc.ManagedChannel) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Test(org.junit.Test)

Example 14 with StreamObserver

use of io.grpc.stub.StreamObserver in project beam by apache.

the class BeamFnDataGrpcClientTest method testForInboundConsumer.

@Test
public void testForInboundConsumer() throws Exception {
    CountDownLatch waitForClientToConnect = new CountDownLatch(1);
    Collection<WindowedValue<String>> inboundValuesA = new ConcurrentLinkedQueue<>();
    Collection<WindowedValue<String>> inboundValuesB = new ConcurrentLinkedQueue<>();
    Collection<BeamFnApi.Elements> inboundServerValues = new ConcurrentLinkedQueue<>();
    AtomicReference<StreamObserver<BeamFnApi.Elements>> outboundServerObserver = new AtomicReference<>();
    CallStreamObserver<BeamFnApi.Elements> inboundServerObserver = TestStreams.withOnNext(inboundServerValues::add).build();
    BeamFnApi.ApiServiceDescriptor apiServiceDescriptor = BeamFnApi.ApiServiceDescriptor.newBuilder().setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString()).build();
    Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl()).addService(new BeamFnDataGrpc.BeamFnDataImplBase() {

        @Override
        public StreamObserver<BeamFnApi.Elements> data(StreamObserver<BeamFnApi.Elements> outboundObserver) {
            outboundServerObserver.set(outboundObserver);
            waitForClientToConnect.countDown();
            return inboundServerObserver;
        }
    }).build();
    server.start();
    try {
        ManagedChannel channel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
        BeamFnDataGrpcClient clientFactory = new BeamFnDataGrpcClient(PipelineOptionsFactory.create(), (BeamFnApi.ApiServiceDescriptor descriptor) -> channel, this::createStreamForTest);
        CompletableFuture<Void> readFutureA = clientFactory.forInboundConsumer(apiServiceDescriptor, KEY_A, CODER, inboundValuesA::add);
        waitForClientToConnect.await();
        outboundServerObserver.get().onNext(ELEMENTS_A_1);
        // Purposefully transmit some data before the consumer for B is bound showing that
        // data is not lost
        outboundServerObserver.get().onNext(ELEMENTS_B_1);
        Thread.sleep(100);
        CompletableFuture<Void> readFutureB = clientFactory.forInboundConsumer(apiServiceDescriptor, KEY_B, CODER, inboundValuesB::add);
        // Show that out of order stream completion can occur.
        readFutureB.get();
        assertThat(inboundValuesB, contains(valueInGlobalWindow("JKL"), valueInGlobalWindow("MNO")));
        outboundServerObserver.get().onNext(ELEMENTS_A_2);
        readFutureA.get();
        assertThat(inboundValuesA, contains(valueInGlobalWindow("ABC"), valueInGlobalWindow("DEF"), valueInGlobalWindow("GHI")));
    } finally {
        server.shutdownNow();
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) CallStreamObserver(io.grpc.stub.CallStreamObserver) Server(io.grpc.Server) BeamFnApi(org.apache.beam.fn.v1.BeamFnApi) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) WindowedValue(org.apache.beam.sdk.util.WindowedValue) ManagedChannel(io.grpc.ManagedChannel) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Test(org.junit.Test)

Example 15 with StreamObserver

use of io.grpc.stub.StreamObserver in project beam by apache.

the class PubsubGrpcClientTest method pullOneMessage.

@Test
public void pullOneMessage() throws IOException {
    String expectedSubscription = SUBSCRIPTION.getPath();
    final PullRequest expectedRequest = PullRequest.newBuilder().setSubscription(expectedSubscription).setReturnImmediately(true).setMaxMessages(10).build();
    Timestamp timestamp = Timestamp.newBuilder().setSeconds(PUB_TIME / 1000).setNanos((int) (PUB_TIME % 1000) * 1000).build();
    PubsubMessage expectedPubsubMessage = PubsubMessage.newBuilder().setMessageId(MESSAGE_ID).setData(ByteString.copyFrom(DATA.getBytes())).setPublishTime(timestamp).putAllAttributes(ATTRIBUTES).putAllAttributes(ImmutableMap.of(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME), ID_ATTRIBUTE, RECORD_ID)).build();
    ReceivedMessage expectedReceivedMessage = ReceivedMessage.newBuilder().setMessage(expectedPubsubMessage).setAckId(ACK_ID).build();
    final PullResponse response = PullResponse.newBuilder().addAllReceivedMessages(ImmutableList.of(expectedReceivedMessage)).build();
    final List<PullRequest> requestsReceived = new ArrayList<>();
    SubscriberImplBase subscriberImplBase = new SubscriberImplBase() {

        @Override
        public void pull(PullRequest request, StreamObserver<PullResponse> responseObserver) {
            requestsReceived.add(request);
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    };
    Server server = InProcessServerBuilder.forName(channelName).addService(subscriberImplBase).build().start();
    try {
        List<IncomingMessage> acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true);
        assertEquals(1, acutalMessages.size());
        IncomingMessage actualMessage = acutalMessages.get(0);
        assertEquals(ACK_ID, actualMessage.ackId);
        assertEquals(DATA, new String(actualMessage.elementBytes));
        assertEquals(RECORD_ID, actualMessage.recordId);
        assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch);
        assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch);
        assertEquals(expectedRequest, Iterables.getOnlyElement(requestsReceived));
    } finally {
        server.shutdownNow();
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) SubscriberImplBase(com.google.pubsub.v1.SubscriberGrpc.SubscriberImplBase) Server(io.grpc.Server) PullRequest(com.google.pubsub.v1.PullRequest) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) ReceivedMessage(com.google.pubsub.v1.ReceivedMessage) Timestamp(com.google.protobuf.Timestamp) PubsubMessage(com.google.pubsub.v1.PubsubMessage) PullResponse(com.google.pubsub.v1.PullResponse) IncomingMessage(org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.IncomingMessage) Test(org.junit.Test)

Aggregations

StreamObserver (io.grpc.stub.StreamObserver)34 Test (org.junit.Test)24 CountDownLatch (java.util.concurrent.CountDownLatch)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 RouteGuideImplBase (io.grpc.examples.routeguide.RouteGuideGrpc.RouteGuideImplBase)10 StatusRuntimeException (io.grpc.StatusRuntimeException)9 ManagedChannel (io.grpc.ManagedChannel)8 Server (io.grpc.Server)8 ArrayList (java.util.ArrayList)8 BeamFnApi (org.apache.beam.fn.v1.BeamFnApi)7 CallStreamObserver (io.grpc.stub.CallStreamObserver)5 Status (io.grpc.Status)4 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 ByteString (com.google.protobuf.ByteString)3 HelloRequest (io.grpc.examples.helloworld.HelloRequest)3 ServerCallStreamObserver (io.grpc.stub.ServerCallStreamObserver)3 SimpleRequest (io.grpc.testing.integration.Messages.SimpleRequest)3 StreamingInputCallRequest (io.grpc.testing.integration.Messages.StreamingInputCallRequest)3