Search in sources :

Example 6 with StreamController

use of com.google.api.gax.rpc.StreamController in project java-bigtable by googleapis.

the class ReframingResponseObserver method onStartImpl.

/**
 * Callback that will be notified when the inner/upstream callable starts. This will in turn
 * notify the outer/downstreamObserver of stream start. Regardless of the
 * outer/downstreamObserver, the upstream controller will be put into manual flow control.
 *
 * @param controller The controller for the upstream stream.
 */
@Override
protected void onStartImpl(StreamController controller) {
    innerController = controller;
    innerController.disableAutoInboundFlowControl();
    outerResponseObserver.onStart(new StreamController() {

        @Override
        public void disableAutoInboundFlowControl() {
            Preconditions.checkState(!hasStarted, "Can't disable automatic flow control once the stream has started");
            autoFlowControl = false;
            numRequested.set(0);
        }

        @Override
        public void request(int count) {
            // innerController.request(int) is indirectly invoked in deliver().
            ReframingResponseObserver.this.onRequest(count);
        }

        @Override
        public void cancel() {
            ReframingResponseObserver.this.onCancel();
        }
    });
    hasStarted = true;
    if (autoFlowControl) {
        numRequested.set(Integer.MAX_VALUE);
        deliver();
    }
}
Also used : StreamController(com.google.api.gax.rpc.StreamController)

Example 7 with StreamController

use of com.google.api.gax.rpc.StreamController in project toolkit by googleapis.

the class ShowcaseTest method canHaveARandomChat.

@Test
public void canHaveARandomChat() throws InterruptedException {
    List<String> responses = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    List<String> inputs = IntStream.range(0, 5).mapToObj(idx -> new Random().ints(20).mapToObj(Integer::toString).collect(Collectors.joining("->"))).collect(Collectors.toList());
    client.chatCallable().call(new BidiStreamObserver<EchoRequest, EchoResponse>() {

        @Override
        public void onReady(ClientStream<EchoRequest> stream) {
            inputs.forEach(message -> stream.send(EchoRequest.newBuilder().setContent(message).build()));
            stream.closeSend();
        }

        @Override
        public void onStart(StreamController controller) {
        // skip...
        }

        @Override
        public void onResponse(EchoResponse response) {
            responses.add(response.getContent());
        }

        @Override
        public void onError(Throwable t) {
            fail("error not expected");
        }

        @Override
        public void onComplete() {
            latch.countDown();
        }
    });
    latch.await(7, TimeUnit.SECONDS);
    assertThat(responses).containsExactlyElementsIn(inputs).inOrder();
}
Also used : SequenceServiceClient(com.google.showcase.v1beta1.SequenceServiceClient) IntStream(java.util.stream.IntStream) BidiStreamObserver(com.google.api.gax.rpc.BidiStreamObserver) EchoSettings(com.google.showcase.v1beta1.EchoSettings) SequenceReport(com.google.showcase.v1beta1.SequenceReport) SequenceServiceSettings(com.google.showcase.v1beta1.SequenceServiceSettings) RunWith(org.junit.runner.RunWith) Random(java.util.Random) AttemptSequenceRequest(com.google.showcase.v1beta1.AttemptSequenceRequest) EchoClient(com.google.showcase.v1beta1.EchoClient) ArrayList(java.util.ArrayList) After(org.junit.After) Assert.fail(org.junit.Assert.fail) ServerStream(com.google.api.gax.rpc.ServerStream) Code(com.google.rpc.Code) Before(org.junit.Before) ClientStream(com.google.api.gax.rpc.ClientStream) Sequence(com.google.showcase.v1beta1.Sequence) EchoRequest(com.google.showcase.v1beta1.EchoRequest) EchoResponse(com.google.showcase.v1beta1.EchoResponse) BlockResponse(com.google.showcase.v1beta1.BlockResponse) ExpandRequest(com.google.showcase.v1beta1.ExpandRequest) Status(com.google.rpc.Status) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) AbortedException(com.google.api.gax.rpc.AbortedException) Collectors(java.util.stream.Collectors) StatusRuntimeException(io.grpc.StatusRuntimeException) TimeUnit(java.util.concurrent.TimeUnit) ApiStreamObserver(com.google.api.gax.rpc.ApiStreamObserver) CountDownLatch(java.util.concurrent.CountDownLatch) Duration(com.google.protobuf.Duration) List(java.util.List) BlockRequest(com.google.showcase.v1beta1.BlockRequest) StreamController(com.google.api.gax.rpc.StreamController) EchoResponse(com.google.showcase.v1beta1.EchoResponse) ArrayList(java.util.ArrayList) EchoRequest(com.google.showcase.v1beta1.EchoRequest) CountDownLatch(java.util.concurrent.CountDownLatch) StreamController(com.google.api.gax.rpc.StreamController) Random(java.util.Random) Test(org.junit.Test)

Example 8 with StreamController

use of com.google.api.gax.rpc.StreamController in project java-bigtable by googleapis.

the class ReframingResponseObserverTest method testFailedRecoveryHandling.

/**
 * Test the scenario where the reframer throws an exception on incoming data and the upstream
 * throws an exception during cleanup when cancel is called.
 */
@Test
public void testFailedRecoveryHandling() {
    MockResponseObserver<String> outerObserver = new MockResponseObserver<>(true);
    final RuntimeException fakeReframerError = new RuntimeException("fake reframer error");
    Reframer<String, String> brokenReframer = new Reframer<String, String>() {

        @Override
        public void push(String ignored) {
            throw fakeReframerError;
        }

        @Override
        public boolean hasFullFrame() {
            return false;
        }

        @Override
        public boolean hasPartialFrame() {
            return false;
        }

        @Override
        public String pop() {
            throw new IllegalStateException("should not be called");
        }
    };
    ReframingResponseObserver<String, String> middleware = new ReframingResponseObserver<>(outerObserver, brokenReframer);
    // Configure the mock inner controller to fail cancellation.
    StreamController mockInnerController = Mockito.mock(StreamController.class);
    RuntimeException fakeCancelError = new RuntimeException("fake cancel error");
    Mockito.doThrow(fakeCancelError).when(mockInnerController).cancel();
    // Jumpstart a call & feed it data
    middleware.onStartImpl(mockInnerController);
    middleware.onResponseImpl("1");
    // Make sure that the outer observer was notified with the reframer, which contains a suppressed
    // cancellation error.
    Throwable finalError = outerObserver.getFinalError();
    Truth.assertThat(finalError).isSameInstanceAs(fakeReframerError);
    Truth.assertThat(ImmutableList.of(finalError.getSuppressed())).hasSize(1);
    Truth.assertThat(finalError.getSuppressed()[0]).isInstanceOf(IllegalStateException.class);
    Truth.assertThat(finalError.getSuppressed()[0]).hasMessageThat().isEqualTo("Failed to cancel upstream while recovering from an unexpected error");
    Truth.assertThat(finalError.getSuppressed()[0].getCause()).isSameInstanceAs(fakeCancelError);
}
Also used : MockResponseObserver(com.google.cloud.bigtable.gaxx.testing.MockStreamingApi.MockResponseObserver) MockStreamController(com.google.cloud.bigtable.gaxx.testing.MockStreamingApi.MockStreamController) StreamController(com.google.api.gax.rpc.StreamController) Test(org.junit.Test)

Example 9 with StreamController

use of com.google.api.gax.rpc.StreamController in project java-spanner by googleapis.

the class GapicSpannerRpc method executeQuery.

@Override
public StreamingCall executeQuery(ExecuteSqlRequest request, ResultStreamConsumer consumer, @Nullable Map<Option, ?> options) {
    GrpcCallContext context = newCallContext(options, request.getSession(), request, SpannerGrpc.getExecuteStreamingSqlMethod());
    SpannerResponseObserver responseObserver = new SpannerResponseObserver(consumer);
    spannerStub.executeStreamingSqlCallable().call(request, responseObserver, context);
    final StreamController controller = responseObserver.getController();
    return new StreamingCall() {

        @Override
        public void request(int numMessage) {
            controller.request(numMessage);
        }

        // TODO(hzyi): streamController currently does not support cancel with message. Add
        // this in gax and update this method later
        @Override
        public void cancel(String message) {
            controller.cancel();
        }
    };
}
Also used : StreamController(com.google.api.gax.rpc.StreamController) GrpcCallContext(com.google.api.gax.grpc.GrpcCallContext)

Example 10 with StreamController

use of com.google.api.gax.rpc.StreamController in project java-spanner by googleapis.

the class GapicSpannerRpc method read.

@Override
public StreamingCall read(ReadRequest request, ResultStreamConsumer consumer, @Nullable Map<Option, ?> options) {
    GrpcCallContext context = newCallContext(options, request.getSession(), request, SpannerGrpc.getReadMethod());
    SpannerResponseObserver responseObserver = new SpannerResponseObserver(consumer);
    spannerStub.streamingReadCallable().call(request, responseObserver, context);
    final StreamController controller = responseObserver.getController();
    return new StreamingCall() {

        @Override
        public void request(int numMessage) {
            controller.request(numMessage);
        }

        // TODO(hzyi): streamController currently does not support cancel with message. Add
        // this in gax and update this method later
        @Override
        public void cancel(String message) {
            controller.cancel();
        }
    };
}
Also used : StreamController(com.google.api.gax.rpc.StreamController) GrpcCallContext(com.google.api.gax.grpc.GrpcCallContext)

Aggregations

StreamController (com.google.api.gax.rpc.StreamController)21 Duration (org.threeten.bp.Duration)4 ServerStreamingAttemptException (com.google.api.gax.retrying.ServerStreamingAttemptException)3 ApiCallContext (com.google.api.gax.rpc.ApiCallContext)3 CancellationException (java.util.concurrent.CancellationException)3 Test (org.junit.Test)3 GrpcCallContext (com.google.api.gax.grpc.GrpcCallContext)2 Duration (com.google.protobuf.Duration)2 StatusRuntimeException (io.grpc.StatusRuntimeException)2 ArrayList (java.util.ArrayList)2 AudioFormat (javax.sound.sampled.AudioFormat)2 DataLine (javax.sound.sampled.DataLine)2 Info (javax.sound.sampled.DataLine.Info)2 TargetDataLine (javax.sound.sampled.TargetDataLine)2 AbortedException (com.google.api.gax.rpc.AbortedException)1 ApiStreamObserver (com.google.api.gax.rpc.ApiStreamObserver)1 BidiStreamObserver (com.google.api.gax.rpc.BidiStreamObserver)1 ClientStream (com.google.api.gax.rpc.ClientStream)1 ResponseObserver (com.google.api.gax.rpc.ResponseObserver)1 ServerStream (com.google.api.gax.rpc.ServerStream)1