Search in sources :

Example 81 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.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<>();
    // 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)

Example 82 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project grpc-java by grpc.

the class ManualFlowControlServer method main.

public static void main(String[] args) throws InterruptedException, IOException {
    // Service class implementation
    StreamingGreeterGrpc.StreamingGreeterImplBase svc = new StreamingGreeterGrpc.StreamingGreeterImplBase() {

        @Override
        public StreamObserver<HelloRequest> sayHelloStreaming(final StreamObserver<HelloReply> responseObserver) {
            // Set up manual flow control for the request stream. It feels backwards to configure the request
            // stream's flow control using the response stream's observer, but this is the way it is.
            final ServerCallStreamObserver<HelloReply> serverCallStreamObserver = (ServerCallStreamObserver<HelloReply>) responseObserver;
            serverCallStreamObserver.disableAutoRequest();
            // else message processing throughput will suffer.
            class OnReadyHandler implements Runnable {

                // Guard against spurious onReady() calls caused by a race between onNext() and onReady(). If the transport
                // toggles isReady() from false to true while onNext() is executing, but before onNext() checks isReady(),
                // request(1) would be called twice - once by onNext() and once by the onReady() scheduled during onNext()'s
                // execution.
                private boolean wasReady = false;

                @Override
                public void run() {
                    if (serverCallStreamObserver.isReady() && !wasReady) {
                        wasReady = true;
                        logger.info("READY");
                        // Signal the request sender to send one message. This happens when isReady() turns true, signaling that
                        // the receive buffer has enough free space to receive more messages. Calling request() serves to prime
                        // the message pump.
                        serverCallStreamObserver.request(1);
                    }
                }
            }
            final OnReadyHandler onReadyHandler = new OnReadyHandler();
            serverCallStreamObserver.setOnReadyHandler(onReadyHandler);
            // Give gRPC a StreamObserver that can observe and process incoming requests.
            return new StreamObserver<HelloRequest>() {

                @Override
                public void onNext(HelloRequest request) {
                    // Process the request and send a response or an error.
                    try {
                        // Accept and enqueue the request.
                        String name = request.getName();
                        logger.info("--> " + name);
                        // Simulate server "work"
                        Thread.sleep(100);
                        // Send a response.
                        String message = "Hello " + name;
                        logger.info("<-- " + message);
                        HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
                        responseObserver.onNext(reply);
                        // Check the provided ServerCallStreamObserver to see if it is still ready to accept more messages.
                        if (serverCallStreamObserver.isReady()) {
                            // Signal the sender to send another request. As long as isReady() stays true, the server will keep
                            // cycling through the loop of onNext() -> request(1)...onNext() -> request(1)... until the client runs
                            // out of messages and ends the loop (via onCompleted()).
                            // 
                            // If request() was called here with the argument of more than 1, the server might runs out of receive
                            // buffer space, and isReady() will turn false. When the receive buffer has sufficiently drained,
                            // isReady() will turn true, and the serverCallStreamObserver's onReadyHandler will be called to restart
                            // the message pump.
                            serverCallStreamObserver.request(1);
                        } else {
                            // If not, note that back-pressure has begun.
                            onReadyHandler.wasReady = false;
                        }
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                        responseObserver.onError(Status.UNKNOWN.withDescription("Error handling request").withCause(throwable).asException());
                    }
                }

                @Override
                public void onError(Throwable t) {
                    // End the response stream if the client presents an error.
                    t.printStackTrace();
                    responseObserver.onCompleted();
                }

                @Override
                public void onCompleted() {
                    // Signal the end of work when the client ends the request stream.
                    logger.info("COMPLETED");
                    responseObserver.onCompleted();
                }
            };
        }
    };
    final Server server = ServerBuilder.forPort(50051).addService(svc).build().start();
    logger.info("Listening on " + server.getPort());
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("Shutting down");
            try {
                server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
        }
    });
    server.awaitTermination();
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Server(io.grpc.Server)

Example 83 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project grpc-java by grpc.

the class FakeControlPlaneXdsIntegrationTest method startServer.

private void startServer(Map<String, ?> bootstrapOverride) throws Exception {
    SimpleServiceGrpc.SimpleServiceImplBase simpleServiceImpl = new SimpleServiceGrpc.SimpleServiceImplBase() {

        @Override
        public void unaryRpc(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
            SimpleResponse response = SimpleResponse.newBuilder().setResponseMessage("Hi, xDS!").build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    };
    XdsServerBuilder serverBuilder = XdsServerBuilder.forPort(0, InsecureServerCredentials.create()).addService(simpleServiceImpl).overrideBootstrapForTest(bootstrapOverride);
    server = serverBuilder.build().start();
    testServerPort = server.getPort();
    logger.log(Level.FINE, "server started");
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) SimpleResponse(io.grpc.testing.protobuf.SimpleResponse) SimpleServiceGrpc(io.grpc.testing.protobuf.SimpleServiceGrpc) SimpleRequest(io.grpc.testing.protobuf.SimpleRequest)

Example 84 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project grpc-java by grpc.

the class ClientXdsClientV3Test method createLrsService.

@Override
protected BindableService createLrsService() {
    return new LoadReportingServiceImplBase() {

        @Override
        public StreamObserver<LoadStatsRequest> streamLoadStats(StreamObserver<LoadStatsResponse> responseObserver) {
            assertThat(lrsEnded.get()).isTrue();
            lrsEnded.set(false);
            @SuppressWarnings("unchecked") StreamObserver<LoadStatsRequest> requestObserver = mock(StreamObserver.class);
            LrsRpcCall call = new LrsRpcCallV3(requestObserver, responseObserver);
            Context.current().addListener(new CancellationListener() {

                @Override
                public void cancelled(Context context) {
                    lrsEnded.set(true);
                }
            }, MoreExecutors.directExecutor());
            loadReportCalls.offer(call);
            return requestObserver;
        }
    };
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) Context(io.grpc.Context) UpstreamTlsContext(io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext) CertificateValidationContext(io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CertificateValidationContext) CommonTlsContext(io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CommonTlsContext) LoadStatsRequest(io.envoyproxy.envoy.service.load_stats.v3.LoadStatsRequest) CancellationListener(io.grpc.Context.CancellationListener) LoadReportingServiceImplBase(io.envoyproxy.envoy.service.load_stats.v3.LoadReportingServiceGrpc.LoadReportingServiceImplBase)

Example 85 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project grpc-java by grpc.

the class HealthServiceImpl method watch.

@Override
public void watch(HealthCheckRequest request, final StreamObserver<HealthCheckResponse> responseObserver) {
    final String service = request.getService();
    synchronized (watchLock) {
        ServingStatus status = statusMap.get(service);
        responseObserver.onNext(getResponseForWatch(status));
        IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean> serviceWatchers = watchers.get(service);
        if (serviceWatchers == null) {
            serviceWatchers = new IdentityHashMap<>();
            watchers.put(service, serviceWatchers);
        }
        serviceWatchers.put(responseObserver, Boolean.TRUE);
    }
    Context.current().addListener(new CancellationListener() {

        @Override
        public // Called when the client has closed the stream
        void cancelled(Context context) {
            synchronized (watchLock) {
                IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean> serviceWatchers = watchers.get(service);
                if (serviceWatchers != null) {
                    serviceWatchers.remove(responseObserver);
                    if (serviceWatchers.isEmpty()) {
                        watchers.remove(service);
                    }
                }
            }
        }
    }, MoreExecutors.directExecutor());
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) Context(io.grpc.Context) ServingStatus(io.grpc.health.v1.HealthCheckResponse.ServingStatus) HealthCheckResponse(io.grpc.health.v1.HealthCheckResponse) CancellationListener(io.grpc.Context.CancellationListener) IdentityHashMap(java.util.IdentityHashMap)

Aggregations

StreamObserver (io.grpc.stub.StreamObserver)133 Test (org.junit.Test)95 CountDownLatch (java.util.concurrent.CountDownLatch)50 ArrayList (java.util.ArrayList)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)38 StreamObserver (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver)27 StatusRuntimeException (io.grpc.StatusRuntimeException)26 Status (io.grpc.Status)20 List (java.util.List)18 BeamFnApi (org.apache.beam.model.fnexecution.v1.BeamFnApi)18 ManagedChannel (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel)18 CompletableFuture (java.util.concurrent.CompletableFuture)17 ExecutorService (java.util.concurrent.ExecutorService)16 SegmentId (io.pravega.controller.stream.api.grpc.v1.Controller.SegmentId)14 ServerRequest (io.pravega.controller.stream.api.grpc.v1.Controller.ServerRequest)14 VisibleForTesting (com.google.common.annotations.VisibleForTesting)12 Strings (com.google.common.base.Strings)12 Throwables (com.google.common.base.Throwables)12 ImmutableMap (com.google.common.collect.ImmutableMap)12 AuthHandler (io.pravega.auth.AuthHandler)12