Search in sources :

Example 1 with StreamObserver

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

the class AbstractBenchmark method startUnaryCalls.

/**
   * Start a continuously executing set of unary calls that will terminate when
   * {@code done.get()} is true. Each completed call will increment the counter by the specified
   * delta which benchmarks can use to measure QPS or bandwidth.
   */
protected void startUnaryCalls(int callsPerChannel, final AtomicLong counter, final AtomicBoolean done, final long counterDelta) {
    for (final ManagedChannel channel : channels) {
        for (int i = 0; i < callsPerChannel; i++) {
            StreamObserver<ByteBuf> observer = new StreamObserver<ByteBuf>() {

                @Override
                public void onNext(ByteBuf value) {
                    counter.addAndGet(counterDelta);
                }

                @Override
                public void onError(Throwable t) {
                    done.set(true);
                }

                @Override
                public void onCompleted() {
                    if (!done.get()) {
                        ByteBuf slice = request.slice();
                        ClientCalls.asyncUnaryCall(channel.newCall(unaryMethod, CALL_OPTIONS), slice, this);
                    }
                }
            };
            observer.onCompleted();
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ManagedChannel(io.grpc.ManagedChannel) ByteBuf(io.netty.buffer.ByteBuf)

Example 2 with StreamObserver

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

the class AbstractBenchmark method startFlowControlledStreamingCalls.

/**
   * Start a continuously executing set of duplex streaming ping-pong calls that will terminate when
   * {@code done.get()} is true. Each completed call will increment the counter by the specified
   * delta which benchmarks can use to measure messages per second or bandwidth.
   */
protected CountDownLatch startFlowControlledStreamingCalls(int callsPerChannel, final AtomicLong counter, final AtomicBoolean record, final AtomicBoolean done, final long counterDelta) {
    final CountDownLatch latch = new CountDownLatch(callsPerChannel * channels.length);
    for (final ManagedChannel channel : channels) {
        for (int i = 0; i < callsPerChannel; i++) {
            final ClientCall<ByteBuf, ByteBuf> streamingCall = channel.newCall(flowControlledStreaming, CALL_OPTIONS);
            final AtomicReference<StreamObserver<ByteBuf>> requestObserverRef = new AtomicReference<StreamObserver<ByteBuf>>();
            final AtomicBoolean ignoreMessages = new AtomicBoolean();
            StreamObserver<ByteBuf> requestObserver = ClientCalls.asyncBidiStreamingCall(streamingCall, new StreamObserver<ByteBuf>() {

                @Override
                public void onNext(ByteBuf value) {
                    StreamObserver<ByteBuf> obs = requestObserverRef.get();
                    if (done.get()) {
                        if (!ignoreMessages.getAndSet(true)) {
                            obs.onCompleted();
                        }
                        return;
                    }
                    if (record.get()) {
                        counter.addAndGet(counterDelta);
                    }
                // request is called automatically because the observer implicitly has auto
                // inbound flow control
                }

                @Override
                public void onError(Throwable t) {
                    logger.log(Level.WARNING, "call error", t);
                    latch.countDown();
                }

                @Override
                public void onCompleted() {
                    latch.countDown();
                }
            });
            requestObserverRef.set(requestObserver);
            // Add some outstanding requests to ensure the server is filling the connection
            streamingCall.request(5);
            requestObserver.onNext(request.slice());
        }
    }
    return latch;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedChannel(io.grpc.ManagedChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf)

Example 3 with StreamObserver

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

the class RouteGuideClient method recordRoute.

/**
   * Async client-streaming example. Sends {@code numPoints} randomly chosen points from {@code
   * features} with a variable delay in between. Prints the statistics when they are sent from the
   * server.
   */
public void recordRoute(List<Feature> features, int numPoints) throws InterruptedException {
    info("*** RecordRoute");
    final CountDownLatch finishLatch = new CountDownLatch(1);
    StreamObserver<RouteSummary> responseObserver = new StreamObserver<RouteSummary>() {

        @Override
        public void onNext(RouteSummary summary) {
            info("Finished trip with {0} points. Passed {1} features. " + "Travelled {2} meters. It took {3} seconds.", summary.getPointCount(), summary.getFeatureCount(), summary.getDistance(), summary.getElapsedTime());
            if (testHelper != null) {
                testHelper.onMessage(summary);
            }
        }

        @Override
        public void onError(Throwable t) {
            warning("RecordRoute Failed: {0}", Status.fromThrowable(t));
            if (testHelper != null) {
                testHelper.onRpcError(t);
            }
            finishLatch.countDown();
        }

        @Override
        public void onCompleted() {
            info("Finished RecordRoute");
            finishLatch.countDown();
        }
    };
    StreamObserver<Point> requestObserver = asyncStub.recordRoute(responseObserver);
    try {
        // Send numPoints points randomly selected from the features list.
        for (int i = 0; i < numPoints; ++i) {
            int index = random.nextInt(features.size());
            Point point = features.get(index).getLocation();
            info("Visiting point {0}, {1}", RouteGuideUtil.getLatitude(point), RouteGuideUtil.getLongitude(point));
            requestObserver.onNext(point);
            // Sleep for a bit before sending the next one.
            Thread.sleep(random.nextInt(1000) + 500);
            if (finishLatch.getCount() == 0) {
                // Sending further requests won't error, but they will just be thrown away.
                return;
            }
        }
    } catch (RuntimeException e) {
        // Cancel RPC
        requestObserver.onError(e);
        throw e;
    }
    // Mark the end of requests
    requestObserver.onCompleted();
    // Receiving happens asynchronously
    if (!finishLatch.await(1, TimeUnit.MINUTES)) {
        warning("recordRoute can not finish within 1 minutes");
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) StatusRuntimeException(io.grpc.StatusRuntimeException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with StreamObserver

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

the class RouteGuideClientTest method listFeatures.

/**
   * Example for testing blocking server-streaming.
   */
@Test
public void listFeatures() {
    final Feature responseFeature1 = Feature.newBuilder().setName("feature 1").build();
    final Feature responseFeature2 = Feature.newBuilder().setName("feature 2").build();
    final AtomicReference<Rectangle> rectangleDelivered = new AtomicReference<Rectangle>();
    // implement the fake service
    RouteGuideImplBase listFeaturesImpl = new RouteGuideImplBase() {

        @Override
        public void listFeatures(Rectangle rectangle, StreamObserver<Feature> responseObserver) {
            rectangleDelivered.set(rectangle);
            // send two response messages
            responseObserver.onNext(responseFeature1);
            responseObserver.onNext(responseFeature2);
            // complete the response
            responseObserver.onCompleted();
        }
    };
    serviceRegistry.addService(listFeaturesImpl);
    client.listFeatures(1, 2, 3, 4);
    assertEquals(Rectangle.newBuilder().setLo(Point.newBuilder().setLatitude(1).setLongitude(2).build()).setHi(Point.newBuilder().setLatitude(3).setLongitude(4).build()).build(), rectangleDelivered.get());
    verify(testHelper).onMessage(responseFeature1);
    verify(testHelper).onMessage(responseFeature2);
    verify(testHelper, never()).onRpcError(any(Throwable.class));
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) AtomicReference(java.util.concurrent.atomic.AtomicReference) RouteGuideImplBase(io.grpc.examples.routeguide.RouteGuideGrpc.RouteGuideImplBase) Test(org.junit.Test)

Example 5 with StreamObserver

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

the class RouteGuideClientTest method routeChat_echoResponse.

/**
   * Example for testing bi-directional call.
   */
@Test
public void routeChat_echoResponse() throws Exception {
    final List<RouteNote> notesDelivered = new ArrayList<RouteNote>();
    // implement the fake service
    RouteGuideImplBase routeChatImpl = new RouteGuideImplBase() {

        @Override
        public StreamObserver<RouteNote> routeChat(final StreamObserver<RouteNote> responseObserver) {
            StreamObserver<RouteNote> requestObserver = new StreamObserver<RouteNote>() {

                @Override
                public void onNext(RouteNote value) {
                    notesDelivered.add(value);
                    responseObserver.onNext(value);
                }

                @Override
                public void onError(Throwable t) {
                    responseObserver.onError(t);
                }

                @Override
                public void onCompleted() {
                    responseObserver.onCompleted();
                }
            };
            return requestObserver;
        }
    };
    serviceRegistry.addService(routeChatImpl);
    client.routeChat().await(1, TimeUnit.SECONDS);
    String[] messages = { "First message", "Second message", "Third message", "Fourth message" };
    for (int i = 0; i < 4; i++) {
        verify(testHelper).onMessage(notesDelivered.get(i));
        assertEquals(messages[i], notesDelivered.get(i).getMessage());
    }
    verify(testHelper, never()).onRpcError(any(Throwable.class));
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ArrayList(java.util.ArrayList) RouteGuideImplBase(io.grpc.examples.routeguide.RouteGuideGrpc.RouteGuideImplBase) 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