Search in sources :

Example 6 with StreamObserver

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

the class RouteGuideClientTest method getFeature_error.

/**
   * Example for testing blocking unary call.
   */
@Test
public void getFeature_error() {
    Point requestPoint = Point.newBuilder().setLatitude(-1).setLongitude(-1).build();
    final AtomicReference<Point> pointDelivered = new AtomicReference<Point>();
    final StatusRuntimeException fakeError = new StatusRuntimeException(Status.DATA_LOSS);
    // implement the fake service
    RouteGuideImplBase getFeatureImpl = new RouteGuideImplBase() {

        @Override
        public void getFeature(Point point, StreamObserver<Feature> responseObserver) {
            pointDelivered.set(point);
            responseObserver.onError(fakeError);
        }
    };
    serviceRegistry.addService(getFeatureImpl);
    client.getFeature(-1, -1);
    assertEquals(requestPoint, pointDelivered.get());
    ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(testHelper).onRpcError(errorCaptor.capture());
    assertEquals(fakeError.getStatus(), Status.fromThrowable(errorCaptor.getValue()));
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) StatusRuntimeException(io.grpc.StatusRuntimeException) AtomicReference(java.util.concurrent.atomic.AtomicReference) RouteGuideImplBase(io.grpc.examples.routeguide.RouteGuideGrpc.RouteGuideImplBase) Test(org.junit.Test)

Example 7 with StreamObserver

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

the class CascadingTest method startChainingServer.

/**
   * Create a chain of client to server calls which can be cancelled top down.
   *
   * @return a Future that completes when call chain is created
   */
private Future<?> startChainingServer(final int depthThreshold) throws IOException {
    final AtomicInteger serversReady = new AtomicInteger();
    final SettableFuture<Void> chainReady = SettableFuture.create();
    class ChainingService extends TestServiceGrpc.TestServiceImplBase {

        @Override
        public void unaryCall(final SimpleRequest request, final StreamObserver<SimpleResponse> responseObserver) {
            ((ServerCallStreamObserver) responseObserver).setOnCancelHandler(new Runnable() {

                @Override
                public void run() {
                    receivedCancellations.countDown();
                }
            });
            if (serversReady.incrementAndGet() == depthThreshold) {
                // Stop recursion
                chainReady.set(null);
                return;
            }
            Context.currentContextExecutor(otherWork).execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        blockingStub.unaryCall(request);
                    } catch (StatusRuntimeException e) {
                        Status status = e.getStatus();
                        if (status.getCode() == Status.Code.CANCELLED) {
                            observedCancellations.countDown();
                        } else {
                            responseObserver.onError(e);
                        }
                    }
                }
            });
        }
    }
    server = InProcessServerBuilder.forName("channel").executor(otherWork).addService(new ChainingService()).build().start();
    return chainReady;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Status(io.grpc.Status) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StatusRuntimeException(io.grpc.StatusRuntimeException) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest)

Example 8 with StreamObserver

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

the class CascadingTest method testDeadlinePropagation.

@Test
public void testDeadlinePropagation() throws Exception {
    final AtomicInteger recursionDepthRemaining = new AtomicInteger(3);
    final SettableFuture<Deadline> finalDeadline = SettableFuture.create();
    class DeadlineSaver extends TestServiceGrpc.TestServiceImplBase {

        @Override
        public void unaryCall(final SimpleRequest request, final StreamObserver<SimpleResponse> responseObserver) {
            Context.currentContextExecutor(otherWork).execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (recursionDepthRemaining.decrementAndGet() == 0) {
                            finalDeadline.set(Context.current().getDeadline());
                            responseObserver.onNext(SimpleResponse.getDefaultInstance());
                        } else {
                            responseObserver.onNext(blockingStub.unaryCall(request));
                        }
                        responseObserver.onCompleted();
                    } catch (Exception ex) {
                        responseObserver.onError(ex);
                    }
                }
            });
        }
    }
    server = InProcessServerBuilder.forName("channel").executor(otherWork).addService(new DeadlineSaver()).build().start();
    Deadline initialDeadline = Deadline.after(1, TimeUnit.MINUTES);
    blockingStub.withDeadline(initialDeadline).unaryCall(SimpleRequest.getDefaultInstance());
    assertNotSame(initialDeadline, finalDeadline);
    // Since deadline is re-calculated at each hop, some variance is acceptable and expected.
    assertAbout(deadline()).that(finalDeadline.get()).isWithin(1, TimeUnit.SECONDS).of(initialDeadline);
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Deadline(io.grpc.Deadline) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) IOException(java.io.IOException) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 9 with StreamObserver

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

the class CascadingTest method startCallTreeServer.

/**
   * Create a tree of client to server calls where each received call on the server
   * fans out to two downstream calls. Uses SimpleRequest.response_size to limit the nodeCount
   * of the tree. One of the leaves will ABORT to trigger cancellation back up to tree.
   */
private void startCallTreeServer(int depthThreshold) throws IOException {
    final AtomicInteger nodeCount = new AtomicInteger((2 << depthThreshold) - 1);
    server = InProcessServerBuilder.forName("channel").executor(otherWork).addService(ServerInterceptors.intercept(service, new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            // Respond with the headers but nothing else.
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ReqT>() {

                @Override
                public void onMessage(final ReqT message) {
                    Messages.SimpleRequest req = (Messages.SimpleRequest) message;
                    if (nodeCount.decrementAndGet() == 0) {
                        // we are in the final leaf node so trigger an ABORT upwards
                        Context.currentContextExecutor(otherWork).execute(new Runnable() {

                            @Override
                            public void run() {
                                call.close(Status.ABORTED, new Metadata());
                            }
                        });
                    } else if (req.getResponseSize() != 0) {
                        // We are in a non leaf node so fire off two requests
                        req = req.toBuilder().setResponseSize(req.getResponseSize() - 1).build();
                        for (int i = 0; i < 2; i++) {
                            asyncStub.unaryCall(req, new StreamObserver<Messages.SimpleResponse>() {

                                @Override
                                public void onNext(Messages.SimpleResponse value) {
                                }

                                @Override
                                public void onError(Throwable t) {
                                    Status status = Status.fromThrowable(t);
                                    if (status.getCode() == Status.Code.CANCELLED) {
                                        observedCancellations.countDown();
                                    }
                                    // Propagate closure upwards.
                                    try {
                                        call.close(status, new Metadata());
                                    } catch (IllegalStateException t2) {
                                    // Ignore error if already closed.
                                    }
                                }

                                @Override
                                public void onCompleted() {
                                }
                            });
                        }
                    }
                }

                @Override
                public void onCancel() {
                    receivedCancellations.countDown();
                }
            };
        }
    })).build();
    server.start();
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Status(io.grpc.Status) ServerCallHandler(io.grpc.ServerCallHandler) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) Metadata(io.grpc.Metadata) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse)

Example 10 with StreamObserver

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

the class MoreInProcessTest method asyncClientStreaming_serverErrorPriorToRequest.

@Test
public void asyncClientStreaming_serverErrorPriorToRequest() throws Exception {
    // implement a service
    final Status fakeError = Status.INVALID_ARGUMENT;
    TestServiceImplBase clientStreamingImpl = new TestServiceImplBase() {

        @Override
        public StreamObserver<StreamingInputCallRequest> streamingInputCall(StreamObserver<StreamingInputCallResponse> responseObserver) {
            // send error directly
            responseObserver.onError(new StatusRuntimeException(fakeError));
            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(fakeError.getCode(), Status.fromThrowable(throwableRef.get()).getCode());
    assertNull(responseRef.get());
}
Also used : Status(io.grpc.Status) StreamObserver(io.grpc.stub.StreamObserver) StreamingInputCallRequest(io.grpc.testing.integration.Messages.StreamingInputCallRequest) StatusRuntimeException(io.grpc.StatusRuntimeException) TestServiceImplBase(io.grpc.testing.integration.TestServiceGrpc.TestServiceImplBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StreamingInputCallResponse(io.grpc.testing.integration.Messages.StreamingInputCallResponse) 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