Search in sources :

Example 1 with CompatRequest

use of io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest in project servicetalk by apple.

the class ProtocolCompatibilityTest method serviceTalkServer.

private static TestServerContext serviceTalkServer(final ErrorMode errorMode, final boolean ssl, final GrpcExecutionStrategy strategy, @Nullable final String compression, @Nullable final Duration timeout, Queue<Throwable> reqStreamError) throws Exception {
    final Compat.CompatService compatService = new Compat.CompatService() {

        @Override
        public Publisher<CompatResponse> bidirectionalStreamingCall(final GrpcServiceContext ctx, final Publisher<CompatRequest> pub) {
            reqStreamError.add(SERVER_PROCESSED_TOKEN);
            maybeThrowFromRpc(errorMode);
            return pub.map(req -> response(req.getId())).beforeFinally(errorConsumer());
        }

        @Override
        public Single<CompatResponse> clientStreamingCall(final GrpcServiceContext ctx, final Publisher<CompatRequest> pub) {
            reqStreamError.add(SERVER_PROCESSED_TOKEN);
            maybeThrowFromRpc(errorMode);
            return pub.collect(() -> 0, (sum, req) -> sum + req.getId()).map(this::response).beforeFinally(errorConsumer());
        }

        @Override
        public Single<CompatResponse> scalarCall(final GrpcServiceContext ctx, final CompatRequest req) {
            maybeThrowFromRpc(errorMode);
            return succeeded(response(req.getId()));
        }

        @Override
        public Publisher<CompatResponse> serverStreamingCall(final GrpcServiceContext ctx, final CompatRequest req) {
            maybeThrowFromRpc(errorMode);
            return Publisher.fromIterable(() -> IntStream.range(0, req.getId()).iterator()).map(this::response);
        }

        private CompatResponse response(final int value) {
            if (errorMode == ErrorMode.SIMPLE_IN_RESPONSE) {
                throwGrpcStatusException();
            } else if (errorMode == ErrorMode.STATUS_IN_RESPONSE) {
                throwGrpcStatusExceptionWithStatus();
            }
            return computeResponse(value);
        }

        private TerminalSignalConsumer errorConsumer() {
            return new TerminalSignalConsumer() {

                @Override
                public void onComplete() {
                }

                @Override
                public void onError(final Throwable throwable) {
                    reqStreamError.add(throwable);
                }

                @Override
                public void cancel() {
                    reqStreamError.add(new IOException("cancelled"));
                }
            };
        }
    };
    final ServiceFactory serviceFactory = new ServiceFactory.Builder().bufferEncoders(serviceTalkCompressions(compression)).bufferDecoderGroup(serviceTalkDecompression(compression)).bidirectionalStreamingCall(strategy, compatService).clientStreamingCall(strategy, compatService).scalarCall(strategy, compatService).serverStreamingCall(strategy, compatService).build();
    final ServerContext serverContext = serviceTalkServerBuilder(errorMode, ssl, timeout, b -> b.executionStrategy(strategy)).listenAndAwait(serviceFactory);
    return TestServerContext.fromServiceTalkServerContext(serverContext);
}
Also used : Arrays(java.util.Arrays) CompatResponse(io.servicetalk.grpc.netty.CompatProto.ResponseContainer.CompatResponse) EmptyBufferDecoderGroup(io.servicetalk.encoding.api.EmptyBufferDecoderGroup) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) GrpcClientMetadata(io.servicetalk.grpc.api.GrpcClientMetadata) TerminalSignalConsumer(io.servicetalk.concurrent.api.TerminalSignalConsumer) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) SourceAdapters.fromSource(io.servicetalk.concurrent.api.SourceAdapters.fromSource) BidirectionalStreamingCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.BidirectionalStreamingCallMetadata) Future(java.util.concurrent.Future) StatusProto(io.grpc.protobuf.StatusProto) Arrays.asList(java.util.Arrays.asList) Duration(java.time.Duration) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) Status(io.grpc.Status) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) HttpProtocolConfigs.h2(io.servicetalk.http.netty.HttpProtocolConfigs.h2) DefaultTestCerts.loadServerKey(io.servicetalk.test.resources.DefaultTestCerts.loadServerKey) GrpcStatus(io.servicetalk.grpc.api.GrpcStatus) BlockingCompatClient(io.servicetalk.grpc.netty.CompatProto.Compat.BlockingCompatClient) BlockingQueue(java.util.concurrent.BlockingQueue) Processors.newSingleProcessor(io.servicetalk.concurrent.api.Processors.newSingleProcessor) Arguments(org.junit.jupiter.params.provider.Arguments) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) BlockingIterable(io.servicetalk.concurrent.BlockingIterable) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ClientStreamingCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.ClientStreamingCallMetadata) GRPC_TIMEOUT_HEADER_KEY(io.servicetalk.grpc.internal.DeadlineUtils.GRPC_TIMEOUT_HEADER_KEY) Compat(io.servicetalk.grpc.netty.CompatProto.Compat) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Any(com.google.protobuf.Any) Matchers.is(org.hamcrest.Matchers.is) DefaultGrpcClientMetadata(io.servicetalk.grpc.api.DefaultGrpcClientMetadata) Codec(io.grpc.Codec) GrpcClientBuilder(io.servicetalk.grpc.api.GrpcClientBuilder) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Compressor(io.grpc.Compressor) BlockingCompatService(io.servicetalk.grpc.netty.CompatProto.Compat.BlockingCompatService) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) CANCELLED(io.servicetalk.grpc.api.GrpcStatusCode.CANCELLED) Decompressor(io.grpc.Decompressor) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Server(io.grpc.Server) Nullable(javax.annotation.Nullable) SslContext(io.netty.handler.ssl.SslContext) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) IOException(java.io.IOException) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) NettyBufferEncoders(io.servicetalk.encoding.netty.NettyBufferEncoders) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) GrpcExecutionStrategy(io.servicetalk.grpc.api.GrpcExecutionStrategy) DefaultTestCerts.loadServerPem(io.servicetalk.test.resources.DefaultTestCerts.loadServerPem) ArrayDeque(java.util.ArrayDeque) HttpServers(io.servicetalk.http.netty.HttpServers) GrpcSslContexts(io.grpc.netty.GrpcSslContexts) CompatRequest(io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest) SocketAddress(java.net.SocketAddress) ManagedChannel(io.grpc.ManagedChannel) GrpcStatusCode(io.servicetalk.grpc.api.GrpcStatusCode) DEFAULT_TIMEOUT_SECONDS(io.servicetalk.concurrent.internal.TestTimeoutConstants.DEFAULT_TIMEOUT_SECONDS) GrpcStatusException(io.servicetalk.grpc.api.GrpcStatusException) GrpcExecutionStrategies.defaultStrategy(io.servicetalk.grpc.api.GrpcExecutionStrategies.defaultStrategy) StreamObserver(io.grpc.stub.StreamObserver) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BufferDecoderGroup(io.servicetalk.encoding.api.BufferDecoderGroup) MethodSource(org.junit.jupiter.params.provider.MethodSource) ScalarCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.ScalarCallMetadata) BufferDecoderGroupBuilder(io.servicetalk.encoding.api.BufferDecoderGroupBuilder) GrpcExecutionStrategies.offloadNever(io.servicetalk.grpc.api.GrpcExecutionStrategies.offloadNever) DEADLINE_EXCEEDED(io.servicetalk.grpc.api.GrpcStatusCode.DEADLINE_EXCEEDED) PublisherSource(io.servicetalk.concurrent.PublisherSource) Collection(java.util.Collection) GrpcPayloadWriter(io.servicetalk.grpc.api.GrpcPayloadWriter) InetSocketAddress(java.net.InetSocketAddress) GrpcServiceContext(io.servicetalk.grpc.api.GrpcServiceContext) Identity(io.servicetalk.encoding.api.Identity) CompatClient(io.servicetalk.grpc.netty.CompatProto.Compat.CompatClient) List(java.util.List) GrpcExecutionContext(io.servicetalk.grpc.api.GrpcExecutionContext) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) CompressorRegistry(io.grpc.CompressorRegistry) Queue(java.util.Queue) Duration.ofMillis(java.time.Duration.ofMillis) IntStream(java.util.stream.IntStream) Publisher.never(io.servicetalk.concurrent.api.Publisher.never) CsvSource(org.junit.jupiter.params.provider.CsvSource) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) Processor(io.servicetalk.concurrent.SingleSource.Processor) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) OPENSSL(io.servicetalk.transport.api.SslProvider.OPENSSL) DecompressorRegistry(io.grpc.DecompressorRegistry) ServerStreamingCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.ServerStreamingCallMetadata) GrpcServerBuilder(io.servicetalk.grpc.api.GrpcServerBuilder) BufferEncoder(io.servicetalk.encoding.api.BufferEncoder) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServiceFactory(io.servicetalk.grpc.netty.CompatProto.Compat.ServiceFactory) ServerContext(io.servicetalk.transport.api.ServerContext) Processors.newPublisherProcessor(io.servicetalk.concurrent.api.Processors.newPublisherProcessor) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Any.pack(com.google.protobuf.Any.pack) Collections(java.util.Collections) HttpClients(io.servicetalk.http.netty.HttpClients) SECONDS(java.util.concurrent.TimeUnit.SECONDS) TerminalSignalConsumer(io.servicetalk.concurrent.api.TerminalSignalConsumer) ServiceFactory(io.servicetalk.grpc.netty.CompatProto.Compat.ServiceFactory) Compat(io.servicetalk.grpc.netty.CompatProto.Compat) Publisher(io.servicetalk.concurrent.api.Publisher) IOException(java.io.IOException) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingCompatService(io.servicetalk.grpc.netty.CompatProto.Compat.BlockingCompatService) CompatResponse(io.servicetalk.grpc.netty.CompatProto.ResponseContainer.CompatResponse) GrpcServiceContext(io.servicetalk.grpc.api.GrpcServiceContext) CompatRequest(io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest)

Example 2 with CompatRequest

use of io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest in project servicetalk by apple.

the class ProtocolCompatibilityTest method grpcJavaClient.

// Wrap grpc client in our client interface to simplify test code
private static CompatClient grpcJavaClient(final SocketAddress address, @Nullable final String compression, final boolean ssl, @Nullable Duration timeout) throws Exception {
    final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(address);
    if (ssl) {
        final SslContext context = GrpcSslContexts.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        builder.sslContext(context);
    } else {
        builder.usePlaintext();
    }
    final ManagedChannel channel = builder.build();
    // stub is immutable and each builder step returns a new instance.
    CompatGrpc.CompatStub stub = CompatGrpc.newStub(channel);
    if (compression != null) {
        stub = stub.withCompression(compression);
    }
    if (null != timeout) {
        stub = stub.withDeadlineAfter(timeout.toNanos(), NANOSECONDS);
    }
    final CompatGrpc.CompatStub finalStub = stub;
    return new CompatClient() {

        @Override
        public GrpcExecutionContext executionContext() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Publisher<CompatResponse> bidirectionalStreamingCall(final Publisher<CompatRequest> request) {
            final PublisherSource.Processor<CompatResponse, CompatResponse> processor = newPublisherProcessor(3);
            sendRequest(request, finalStub.bidirectionalStreamingCall(adaptResponse(processor)));
            return fromSource(processor);
        }

        @Override
        public Publisher<CompatResponse> bidirectionalStreamingCall(final GrpcClientMetadata metadata, final Publisher<CompatRequest> request) {
            return bidirectionalStreamingCall(request);
        }

        @Deprecated
        @Override
        public Publisher<CompatResponse> bidirectionalStreamingCall(final BidirectionalStreamingCallMetadata metadata, final Publisher<CompatRequest> request) {
            return bidirectionalStreamingCall(request);
        }

        @SuppressWarnings("unchecked")
        @Override
        public Single<CompatResponse> clientStreamingCall(final Publisher<CompatRequest> request) {
            final Processor<CompatResponse, CompatResponse> processor = newSingleProcessor();
            final StreamObserver<CompatRequest> requestObserver = finalStub.clientStreamingCall(adaptResponse(processor));
            sendRequest(request, requestObserver);
            return (Single<CompatResponse>) processor;
        }

        @Deprecated
        @Override
        public Single<CompatResponse> clientStreamingCall(final ClientStreamingCallMetadata metadata, final Publisher<CompatRequest> request) {
            return clientStreamingCall(request);
        }

        @Override
        public Single<CompatResponse> clientStreamingCall(final GrpcClientMetadata metadata, final Publisher<CompatRequest> request) {
            return clientStreamingCall(request);
        }

        @SuppressWarnings("unchecked")
        @Override
        public Single<CompatResponse> scalarCall(final CompatRequest request) {
            final Processor<CompatResponse, CompatResponse> processor = newSingleProcessor();
            finalStub.scalarCall(request, adaptResponse(processor));
            return (Single<CompatResponse>) processor;
        }

        @Deprecated
        @Override
        public Single<CompatResponse> scalarCall(final ScalarCallMetadata metadata, final CompatRequest request) {
            return scalarCall(request);
        }

        @Override
        public Single<CompatResponse> scalarCall(final GrpcClientMetadata metadata, final CompatRequest request) {
            return scalarCall(request);
        }

        @Override
        public Publisher<CompatResponse> serverStreamingCall(final CompatRequest request) {
            final PublisherSource.Processor<CompatResponse, CompatResponse> processor = newPublisherProcessor(3);
            finalStub.serverStreamingCall(request, adaptResponse(processor));
            return fromSource(processor);
        }

        @Deprecated
        @Override
        public Publisher<CompatResponse> serverStreamingCall(final ServerStreamingCallMetadata metadata, final CompatRequest request) {
            return serverStreamingCall(request);
        }

        @Override
        public Publisher<CompatResponse> serverStreamingCall(final GrpcClientMetadata metadata, final CompatRequest request) {
            return serverStreamingCall(request);
        }

        @Override
        public void close() throws Exception {
            channel.shutdown().awaitTermination(DEFAULT_TIMEOUT_SECONDS, SECONDS);
        }

        @Override
        public Completable closeAsync() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Completable onClose() {
            throw new UnsupportedOperationException();
        }

        @Override
        public BlockingCompatClient asBlockingClient() {
            throw new UnsupportedOperationException();
        }

        private void sendRequest(final Publisher<CompatRequest> request, final StreamObserver<CompatRequest> requestObserver) {
            request.whenOnComplete(requestObserver::onCompleted).whenOnError(requestObserver::onError).forEach(requestObserver::onNext);
        }

        private StreamObserver<CompatResponse> adaptResponse(final Processor<CompatResponse, CompatResponse> processor) {
            return new StreamObserver<CompatResponse>() {

                @Override
                public void onNext(final CompatResponse value) {
                    processor.onSuccess(value);
                }

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

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

        private StreamObserver<CompatResponse> adaptResponse(final PublisherSource.Processor<CompatResponse, CompatResponse> processor) {
            return new StreamObserver<CompatResponse>() {

                @Override
                public void onNext(final CompatResponse value) {
                    processor.onNext(value);
                }

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

                @Override
                public void onCompleted() {
                    processor.onComplete();
                }
            };
        }
    };
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) BidirectionalStreamingCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.BidirectionalStreamingCallMetadata) Processors.newSingleProcessor(io.servicetalk.concurrent.api.Processors.newSingleProcessor) Processor(io.servicetalk.concurrent.SingleSource.Processor) Processors.newPublisherProcessor(io.servicetalk.concurrent.api.Processors.newPublisherProcessor) PublisherSource(io.servicetalk.concurrent.PublisherSource) ScalarCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.ScalarCallMetadata) Publisher(io.servicetalk.concurrent.api.Publisher) GrpcClientMetadata(io.servicetalk.grpc.api.GrpcClientMetadata) DefaultGrpcClientMetadata(io.servicetalk.grpc.api.DefaultGrpcClientMetadata) ServerStreamingCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.ServerStreamingCallMetadata) Single(io.servicetalk.concurrent.api.Single) BlockingCompatClient(io.servicetalk.grpc.netty.CompatProto.Compat.BlockingCompatClient) CompatClient(io.servicetalk.grpc.netty.CompatProto.Compat.CompatClient) CompatResponse(io.servicetalk.grpc.netty.CompatProto.ResponseContainer.CompatResponse) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) ManagedChannel(io.grpc.ManagedChannel) CompatRequest(io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest) ClientStreamingCallMetadata(io.servicetalk.grpc.netty.CompatProto.Compat.ClientStreamingCallMetadata) SslContext(io.netty.handler.ssl.SslContext)

Example 3 with CompatRequest

use of io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest in project servicetalk by apple.

the class ProtocolCompatibilityTest method timeoutMidRequest.

@ParameterizedTest
@CsvSource({ "false,false,false", "false,false,true", "false,true,false", "false,true,true", "true,false,false", "true,false,true", "true,true,false", "true,true,true" })
void timeoutMidRequest(boolean stClient, boolean stServer, boolean clientInitiatedTimeout) throws Exception {
    Duration clientTimeout = clientInitiatedTimeout ? DEFAULT_DEADLINE : null;
    Duration serverTimeout = clientInitiatedTimeout ? null : DEFAULT_DEADLINE;
    BlockingQueue<Throwable> serverErrorQueue = new ArrayBlockingQueue<>(16);
    final TestServerContext server = stServer ? serviceTalkServer(ErrorMode.NONE, false, offloadNever(), null, null, serverErrorQueue) : grpcJavaServer(ErrorMode.NONE, false, null);
    try (ServerContext proxyCtx = buildTimeoutProxy(server.listenAddress(), serverTimeout, false)) {
        final CompatClient client = stClient ? serviceTalkClient(proxyCtx.listenAddress(), false, null, clientTimeout) : grpcJavaClient(proxyCtx.listenAddress(), null, false, clientTimeout);
        try {
            PublisherSource.Processor<CompatRequest, CompatRequest> reqPub = newPublisherProcessor();
            reqPub.onNext(CompatRequest.newBuilder().setId(3).build());
            validateGrpcErrorInResponse(client.bidirectionalStreamingCall(fromSource(reqPub)).toFuture(), false, clientInitiatedTimeout ? DEADLINE_EXCEEDED : CANCELLED, null);
            // It is possible that the timeout on the client occurred before writing the request, in which case the
            // server will never request the request, and therefore no error is expected.
            Throwable cause = serverErrorQueue.poll(DEFAULT_DEADLINE.toNanos() * 2, NANOSECONDS);
            if (cause != null) {
                assertThat(cause, is(SERVER_PROCESSED_TOKEN));
                cause = serverErrorQueue.take();
                assertThat(cause, instanceOf(IOException.class));
            }
        } finally {
            closeAll(server, client);
        }
    }
}
Also used : ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ServerContext(io.servicetalk.transport.api.ServerContext) PublisherSource(io.servicetalk.concurrent.PublisherSource) BlockingCompatClient(io.servicetalk.grpc.netty.CompatProto.Compat.BlockingCompatClient) CompatClient(io.servicetalk.grpc.netty.CompatProto.Compat.CompatClient) Duration(java.time.Duration) IOException(java.io.IOException) CompatRequest(io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest) CsvSource(org.junit.jupiter.params.provider.CsvSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with CompatRequest

use of io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest in project servicetalk by apple.

the class ProtocolCompatibilityTest method grpcJavaServer.

private static TestServerContext grpcJavaServer(final ErrorMode errorMode, final boolean ssl, @Nullable final String compression) throws Exception {
    final NettyServerBuilder builder = NettyServerBuilder.forAddress(localAddress(0));
    if (ssl) {
        builder.useTransportSecurity(loadServerPem(), loadServerKey());
    }
    if (compression != null) {
        DecompressorRegistry dRegistry = DecompressorRegistry.emptyInstance();
        CompressorRegistry cRegistry = CompressorRegistry.newEmptyInstance();
        Compressor gz = new Codec.Gzip();
        Compressor id = Codec.Identity.NONE;
        if (compression.equals(gz.getMessageEncoding())) {
            dRegistry = dRegistry.with((Decompressor) gz, true);
            cRegistry.register(gz);
        }
        // Always include identity otherwise it's not available
        dRegistry = dRegistry.with((Decompressor) id, false);
        cRegistry.register(id);
        builder.decompressorRegistry(dRegistry);
        builder.compressorRegistry(cRegistry);
    } else {
        builder.decompressorRegistry(DecompressorRegistry.emptyInstance());
        builder.compressorRegistry(CompressorRegistry.newEmptyInstance());
    }
    final Server server = builder.addService(new CompatGrpc.CompatImplBase() {

        @Override
        public void scalarCall(final CompatRequest request, final StreamObserver<CompatResponse> responseObserver) {
            try {
                responseObserver.onNext(response(request.getId()));
                responseObserver.onCompleted();
            } catch (final Throwable t) {
                responseObserver.onError(t);
            }
        }

        @Override
        public StreamObserver<CompatRequest> clientStreamingCall(final StreamObserver<CompatResponse> responseObserver) {
            return new StreamObserver<CompatRequest>() {

                int sum;

                @Override
                public void onNext(final CompatRequest value) {
                    sum += value.getId();
                }

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

                @Override
                public void onCompleted() {
                    try {
                        responseObserver.onNext(response(sum));
                        responseObserver.onCompleted();
                    } catch (final Throwable t) {
                        responseObserver.onError(t);
                    }
                }
            };
        }

        @Override
        public void serverStreamingCall(final CompatRequest request, final StreamObserver<CompatResponse> responseObserver) {
            for (int i = 0; i < request.getId(); ++i) {
                try {
                    responseObserver.onNext(response(i));
                } catch (final Throwable t) {
                    responseObserver.onError(t);
                    return;
                }
            }
            responseObserver.onCompleted();
        }

        @Override
        public StreamObserver<CompatRequest> bidirectionalStreamingCall(final StreamObserver<CompatResponse> responseObserver) {
            return new StreamObserver<CompatRequest>() {

                private boolean errored;

                @Override
                public void onNext(final CompatRequest demoRequest) {
                    try {
                        responseObserver.onNext(response(demoRequest.getId()));
                    } catch (final Throwable t) {
                        onError(t);
                    }
                }

                @Override
                public void onError(final Throwable t) {
                    if (errored) {
                        return;
                    }
                    errored = true;
                    responseObserver.onError(t);
                }

                @Override
                public void onCompleted() {
                    if (errored) {
                        return;
                    }
                    responseObserver.onCompleted();
                }
            };
        }

        private CompatResponse response(final int value) throws Exception {
            if (errorMode == ErrorMode.SIMPLE) {
                throw Status.INVALID_ARGUMENT.augmentDescription(CUSTOM_ERROR_MESSAGE).asException();
            }
            if (errorMode == ErrorMode.STATUS) {
                throw StatusProto.toStatusException(newStatus());
            }
            return computeResponse(value);
        }
    }).build().start();
    return TestServerContext.fromGrpcJavaServer(server);
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) Decompressor(io.grpc.Decompressor) Server(io.grpc.Server) Compressor(io.grpc.Compressor) DecompressorRegistry(io.grpc.DecompressorRegistry) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) IOException(java.io.IOException) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) GrpcStatusException(io.servicetalk.grpc.api.GrpcStatusException) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) CompressorRegistry(io.grpc.CompressorRegistry) CompatResponse(io.servicetalk.grpc.netty.CompatProto.ResponseContainer.CompatResponse) CompatRequest(io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest)

Aggregations

CompatRequest (io.servicetalk.grpc.netty.CompatProto.RequestContainer.CompatRequest)4 StreamObserver (io.grpc.stub.StreamObserver)3 PublisherSource (io.servicetalk.concurrent.PublisherSource)3 BlockingCompatClient (io.servicetalk.grpc.netty.CompatProto.Compat.BlockingCompatClient)3 CompatClient (io.servicetalk.grpc.netty.CompatProto.Compat.CompatClient)3 CompatResponse (io.servicetalk.grpc.netty.CompatProto.ResponseContainer.CompatResponse)3 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 Compressor (io.grpc.Compressor)2 CompressorRegistry (io.grpc.CompressorRegistry)2 Decompressor (io.grpc.Decompressor)2 DecompressorRegistry (io.grpc.DecompressorRegistry)2 ManagedChannel (io.grpc.ManagedChannel)2 Server (io.grpc.Server)2 StatusRuntimeException (io.grpc.StatusRuntimeException)2 NettyChannelBuilder (io.grpc.netty.NettyChannelBuilder)2 NettyServerBuilder (io.grpc.netty.NettyServerBuilder)2 SslContext (io.netty.handler.ssl.SslContext)2 Processor (io.servicetalk.concurrent.SingleSource.Processor)2 Processors.newPublisherProcessor (io.servicetalk.concurrent.api.Processors.newPublisherProcessor)2 Processors.newSingleProcessor (io.servicetalk.concurrent.api.Processors.newSingleProcessor)2