Java Code Examples for io.grpc.ClientCall#halfClose()

The following examples show how to use io.grpc.ClientCall#halfClose() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ErrorHandlingClient.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Narwhal"));
      // Cause is not transmitted over the wire.
      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example 2
Source File: ErrorHandlingClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Narwhal"));
      // Cause is not transmitted over the wire.
      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example 3
Source File: DetailErrorSample.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
      try {
        Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
      } catch (IllegalArgumentException e) {
        throw new VerifyException(e);
      }

      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example 4
Source File: DetailErrorSample.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
      try {
        Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
      } catch (IllegalArgumentException e) {
        throw new VerifyException(e);
      }

      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example 5
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void serverStreamingShouldBeFlowControlled() throws Exception {
  final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
      .addResponseParameters(ResponseParameters.newBuilder().setSize(100000))
      .addResponseParameters(ResponseParameters.newBuilder().setSize(100001))
      .build();
  final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
      StreamingOutputCallResponse.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[100000]))).build(),
      StreamingOutputCallResponse.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[100001]))).build());

  long start = System.nanoTime();

  final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
  ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call =
      channel.newCall(TestServiceGrpc.getStreamingOutputCallMethod(), CallOptions.DEFAULT);
  call.start(new ClientCall.Listener<StreamingOutputCallResponse>() {
    @Override
    public void onHeaders(Metadata headers) {}

    @Override
    public void onMessage(final StreamingOutputCallResponse message) {
      queue.add(message);
    }

    @Override
    public void onClose(Status status, Metadata trailers) {
      queue.add(status);
    }
  }, new Metadata());
  call.sendMessage(request);
  call.halfClose();

  // Time how long it takes to get the first response.
  call.request(1);
  Object response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
  assertTrue(response instanceof StreamingOutputCallResponse);
  assertResponse(goldenResponses.get(0), (StreamingOutputCallResponse) response);
  long firstCallDuration = System.nanoTime() - start;

  // Without giving additional flow control, make sure that we don't get another response. We wait
  // until we are comfortable the next message isn't coming. We may have very low nanoTime
  // resolution (like on Windows) or be using a testing, in-process transport where message
  // handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time
  // to at least 1ms.
  assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS));

  // Make sure that everything still completes.
  call.request(1);
  response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
  assertTrue(response instanceof StreamingOutputCallResponse);
  assertResponse(goldenResponses.get(1), (StreamingOutputCallResponse) response);
  assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
}
 
Example 6
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void inprocessTransportManualFlow() throws Exception {
  final Semaphore semaphore = new Semaphore(1);
  ServerServiceDefinition service = ServerServiceDefinition.builder(
      new ServiceDescriptor("some", STREAMING_METHOD))
      .addMethod(STREAMING_METHOD, ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            int iteration;

            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              final ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.setOnReadyHandler(new Runnable() {
                @Override
                public void run() {
                  while (serverCallObserver.isReady()) {
                    serverCallObserver.onNext(iteration);
                  }
                  iteration++;
                  semaphore.release();
                }
              });
              return new ServerCalls.NoopStreamObserver<Integer>() {
                @Override
                public void onCompleted() {
                  serverCallObserver.onCompleted();
                }
              };
            }
          }))
      .build();
  long tag = System.nanoTime();
  InProcessServerBuilder.forName("go-with-the-flow" + tag).addService(service).build().start();
  ManagedChannel channel = InProcessChannelBuilder.forName("go-with-the-flow" + tag).build();
  final ClientCall<Integer, Integer> clientCall = channel.newCall(STREAMING_METHOD,
      CallOptions.DEFAULT);
  final CountDownLatch latch = new CountDownLatch(1);
  final int[] receivedMessages = new int[6];
  clientCall.start(new ClientCall.Listener<Integer>() {
    int index;

    @Override
    public void onMessage(Integer message) {
      receivedMessages[index++] = message;
    }

    @Override
    public void onClose(Status status, Metadata trailers) {
      latch.countDown();
    }
  }, new Metadata());
  semaphore.acquire();
  clientCall.request(1);
  semaphore.acquire();
  clientCall.request(2);
  semaphore.acquire();
  clientCall.request(3);
  clientCall.halfClose();
  latch.await(5, TimeUnit.SECONDS);
  // Very that number of messages produced in each onReady handler call matches the number
  // requested by the client.
  assertArrayEquals(new int[]{0, 1, 1, 2, 2, 2}, receivedMessages);
}
 
Example 7
Source File: ByteStreamServiceTest.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
@Test
public void writePutsIntoBlobStore() throws IOException, InterruptedException {
  ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!");
  Digest digest = DIGEST_UTIL.compute(helloWorld);
  String uuid = UUID.randomUUID().toString();
  String resourceName = createBlobUploadResourceName(uuid, digest);

  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ClientCall<WriteRequest, WriteResponse> call =
      channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT);
  ClientCall.Listener<WriteResponse> callListener =
      new ClientCall.Listener<WriteResponse>() {
        boolean complete = false;
        boolean callHalfClosed = false;

        @Override
        public void onReady() {
          while (call.isReady()) {
            if (complete) {
              if (!callHalfClosed) {
                call.halfClose();
                callHalfClosed = true;
              }
              return;
            }

            call.sendMessage(
                WriteRequest.newBuilder()
                    .setResourceName(resourceName)
                    .setData(helloWorld)
                    .setFinishWrite(true)
                    .build());
            complete = true;
          }
        }
      };

  call.start(callListener, new Metadata());
  call.request(1);

  verify(simpleBlobStore, times(1))
      .put(eq(digest.getHash()), eq(digest.getSizeBytes()), any(InputStream.class));
}
 
Example 8
Source File: ByteStreamServiceTest.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
@Test
public void writeCanBeResumed() throws IOException, InterruptedException {
  ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!");
  Digest digest = DIGEST_UTIL.compute(helloWorld);
  String uuid = UUID.randomUUID().toString();
  String resourceName = createBlobUploadResourceName(uuid, digest);

  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ClientCall<WriteRequest, WriteResponse> initialCall =
      channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT);
  ByteString initialData = helloWorld.substring(0, 6);
  ClientCall.Listener<WriteResponse> initialCallListener =
      new ClientCall.Listener<WriteResponse>() {
        boolean complete = false;
        boolean callHalfClosed = false;

        @Override
        public void onReady() {
          while (initialCall.isReady()) {
            if (complete) {
              if (!callHalfClosed) {
                initialCall.halfClose();
                callHalfClosed = true;
              }
              return;
            }

            initialCall.sendMessage(
                WriteRequest.newBuilder()
                    .setResourceName(resourceName)
                    .setData(initialData)
                    .build());
            complete = true;
          }
        }
      };

  initialCall.start(initialCallListener, new Metadata());
  initialCall.request(1);

  ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);
  QueryWriteStatusResponse response =
      service.queryWriteStatus(
          QueryWriteStatusRequest.newBuilder().setResourceName(resourceName).build());
  assertThat(response.getCommittedSize()).isEqualTo(initialData.size());
  assertThat(response.getComplete()).isFalse();

  ClientCall<WriteRequest, WriteResponse> finishCall =
      channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT);
  ClientCall.Listener<WriteResponse> finishCallListener =
      new ClientCall.Listener<WriteResponse>() {
        boolean complete = false;
        boolean callHalfClosed = false;

        @Override
        public void onReady() {
          while (finishCall.isReady()) {
            if (complete) {
              if (!callHalfClosed) {
                finishCall.halfClose();
                callHalfClosed = true;
              }
              return;
            }

            finishCall.sendMessage(
                WriteRequest.newBuilder()
                    .setResourceName(resourceName)
                    .setWriteOffset(initialData.size())
                    .setData(helloWorld.substring(initialData.size()))
                    .setFinishWrite(true)
                    .build());
            complete = true;
          }
        }
      };

  finishCall.start(finishCallListener, new Metadata());
  finishCall.request(1);

  ArgumentCaptor<InputStream> inputStreamCaptor = ArgumentCaptor.forClass(InputStream.class);

  verify(simpleBlobStore, times(1))
      .put(eq(digest.getHash()), eq(digest.getSizeBytes()), inputStreamCaptor.capture());
  InputStream inputStream = inputStreamCaptor.getValue();
  assertThat(inputStream.available()).isEqualTo(helloWorld.size());
  byte[] data = new byte[helloWorld.size()];
  assertThat(inputStream.read(data)).isEqualTo(helloWorld.size());
  assertThat(data).isEqualTo(helloWorld.toByteArray());
}
 
Example 9
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void serverStreamingShouldBeFlowControlled() throws Exception {
  final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
      .addResponseParameters(ResponseParameters.newBuilder().setSize(100000))
      .addResponseParameters(ResponseParameters.newBuilder().setSize(100001))
      .build();
  final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
      StreamingOutputCallResponse.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[100000]))).build(),
      StreamingOutputCallResponse.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[100001]))).build());

  long start = System.nanoTime();

  final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
  ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call =
      channel.newCall(TestServiceGrpc.getStreamingOutputCallMethod(), CallOptions.DEFAULT);
  call.start(new ClientCall.Listener<StreamingOutputCallResponse>() {
    @Override
    public void onHeaders(Metadata headers) {}

    @Override
    public void onMessage(final StreamingOutputCallResponse message) {
      queue.add(message);
    }

    @Override
    public void onClose(Status status, Metadata trailers) {
      queue.add(status);
    }
  }, new Metadata());
  call.sendMessage(request);
  call.halfClose();

  // Time how long it takes to get the first response.
  call.request(1);
  Object response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
  assertTrue(response instanceof StreamingOutputCallResponse);
  assertResponse(goldenResponses.get(0), (StreamingOutputCallResponse) response);
  long firstCallDuration = System.nanoTime() - start;

  // Without giving additional flow control, make sure that we don't get another response. We wait
  // until we are comfortable the next message isn't coming. We may have very low nanoTime
  // resolution (like on Windows) or be using a testing, in-process transport where message
  // handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time
  // to at least 1ms.
  assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS));

  // Make sure that everything still completes.
  call.request(1);
  response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
  assertTrue(response instanceof StreamingOutputCallResponse);
  assertResponse(goldenResponses.get(1), (StreamingOutputCallResponse) response);
  assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
}
 
Example 10
Source File: XdsTestClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void runQps() throws InterruptedException, ExecutionException {
  final SettableFuture<Void> failure = SettableFuture.create();
  final class PeriodicRpc implements Runnable {

    @Override
    public void run() {
      final long requestId;
      final Set<XdsStatsWatcher> savedWatchers = new HashSet<>();
      synchronized (lock) {
        currentRequestId += 1;
        requestId = currentRequestId;
        savedWatchers.addAll(watchers);
      }

      SimpleRequest request = SimpleRequest.newBuilder().setFillServerId(true).build();
      ManagedChannel channel = channels.get((int) (requestId % channels.size()));
      final ClientCall<SimpleRequest, SimpleResponse> call =
          channel.newCall(
              TestServiceGrpc.getUnaryCallMethod(),
              CallOptions.DEFAULT.withDeadlineAfter(rpcTimeoutSec, TimeUnit.SECONDS));
      call.start(
          new ClientCall.Listener<SimpleResponse>() {
            private String hostname;

            @Override
            public void onMessage(SimpleResponse response) {
              hostname = response.getHostname();
              // TODO(ericgribkoff) Currently some test environments cannot access the stats RPC
              // service and rely on parsing stdout.
              if (printResponse) {
                System.out.println(
                    "Greeting: Hello world, this is "
                        + hostname
                        + ", from "
                        + call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
              }
            }

            @Override
            public void onClose(Status status, Metadata trailers) {
              if (printResponse && !status.isOk()) {
                logger.log(Level.WARNING, "Greeting RPC failed with status {0}", status);
              }
              for (XdsStatsWatcher watcher : savedWatchers) {
                watcher.rpcCompleted(requestId, hostname);
              }
            }
          },
          new Metadata());

      call.sendMessage(request);
      call.request(1);
      call.halfClose();
    }
  }

  long nanosPerQuery = TimeUnit.SECONDS.toNanos(1) / qps;
  ListenableScheduledFuture<?> future =
      exec.scheduleAtFixedRate(new PeriodicRpc(), 0, nanosPerQuery, TimeUnit.NANOSECONDS);

  Futures.addCallback(
      future,
      new FutureCallback<Object>() {

        @Override
        public void onFailure(Throwable t) {
          failure.setException(t);
        }

        @Override
        public void onSuccess(Object o) {}
      },
      MoreExecutors.directExecutor());

  failure.get();
}
 
Example 11
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void channelsAndSubchannels_instrumented0(boolean success) throws Exception {
  createChannel();

  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);

  // Channel stat bumped when ClientCall.start() called
  assertEquals(0, getStats(channel).callsStarted);
  call.start(mockCallListener, new Metadata());
  assertEquals(1, getStats(channel).callsStarted);

  ClientStream mockStream = mock(ClientStream.class);
  ClientStreamTracer.Factory factory = mock(ClientStreamTracer.Factory.class);
  AbstractSubchannel subchannel =
      (AbstractSubchannel) createSubchannelSafely(
          helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
  requestConnectionSafely(helper, subchannel);
  MockClientTransportInfo transportInfo = transports.poll();
  transportInfo.listener.transportReady();
  ClientTransport mockTransport = transportInfo.transport;
  when(mockTransport.newStream(
          any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class)))
      .thenReturn(mockStream);
  when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(
      PickResult.withSubchannel(subchannel, factory));

  // subchannel stat bumped when call gets assigned to it
  assertEquals(0, getStats(subchannel).callsStarted);
  updateBalancingStateSafely(helper, READY, mockPicker);
  assertEquals(1, executor.runDueTasks());
  verify(mockStream).start(streamListenerCaptor.capture());
  assertEquals(1, getStats(subchannel).callsStarted);

  ClientStreamListener streamListener = streamListenerCaptor.getValue();
  call.halfClose();

  // closing stream listener affects subchannel stats immediately
  assertEquals(0, getStats(subchannel).callsSucceeded);
  assertEquals(0, getStats(subchannel).callsFailed);
  streamListener.closed(success ? Status.OK : Status.UNKNOWN, new Metadata());
  if (success) {
    assertEquals(1, getStats(subchannel).callsSucceeded);
    assertEquals(0, getStats(subchannel).callsFailed);
  } else {
    assertEquals(0, getStats(subchannel).callsSucceeded);
    assertEquals(1, getStats(subchannel).callsFailed);
  }

  // channel stats bumped when the ClientCall.Listener is notified
  assertEquals(0, getStats(channel).callsSucceeded);
  assertEquals(0, getStats(channel).callsFailed);
  executor.runDueTasks();
  if (success) {
    assertEquals(1, getStats(channel).callsSucceeded);
    assertEquals(0, getStats(channel).callsFailed);
  } else {
    assertEquals(0, getStats(channel).callsSucceeded);
    assertEquals(1, getStats(channel).callsFailed);
  }
}
 
Example 12
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void channelsAndSubchannels_oob_instrumented0(boolean success) throws Exception {
  // set up
  ClientStream mockStream = mock(ClientStream.class);
  createChannel();

  OobChannel oobChannel = (OobChannel) helper.createOobChannel(addressGroup, "oobauthority");
  AbstractSubchannel oobSubchannel = (AbstractSubchannel) oobChannel.getSubchannel();
  FakeClock callExecutor = new FakeClock();
  CallOptions options =
      CallOptions.DEFAULT.withExecutor(callExecutor.getScheduledExecutorService());
  ClientCall<String, Integer> call = oobChannel.newCall(method, options);
  Metadata headers = new Metadata();

  // Channel stat bumped when ClientCall.start() called
  assertEquals(0, getStats(oobChannel).callsStarted);
  call.start(mockCallListener, headers);
  assertEquals(1, getStats(oobChannel).callsStarted);

  MockClientTransportInfo transportInfo = transports.poll();
  ConnectionClientTransport mockTransport = transportInfo.transport;
  ManagedClientTransport.Listener transportListener = transportInfo.listener;
  when(mockTransport.newStream(same(method), same(headers), any(CallOptions.class)))
      .thenReturn(mockStream);

  // subchannel stat bumped when call gets assigned to it
  assertEquals(0, getStats(oobSubchannel).callsStarted);
  transportListener.transportReady();
  callExecutor.runDueTasks();
  verify(mockStream).start(streamListenerCaptor.capture());
  assertEquals(1, getStats(oobSubchannel).callsStarted);

  ClientStreamListener streamListener = streamListenerCaptor.getValue();
  call.halfClose();

  // closing stream listener affects subchannel stats immediately
  assertEquals(0, getStats(oobSubchannel).callsSucceeded);
  assertEquals(0, getStats(oobSubchannel).callsFailed);
  streamListener.closed(success ? Status.OK : Status.UNKNOWN, new Metadata());
  if (success) {
    assertEquals(1, getStats(oobSubchannel).callsSucceeded);
    assertEquals(0, getStats(oobSubchannel).callsFailed);
  } else {
    assertEquals(0, getStats(oobSubchannel).callsSucceeded);
    assertEquals(1, getStats(oobSubchannel).callsFailed);
  }

  // channel stats bumped when the ClientCall.Listener is notified
  assertEquals(0, getStats(oobChannel).callsSucceeded);
  assertEquals(0, getStats(oobChannel).callsFailed);
  callExecutor.runDueTasks();
  if (success) {
    assertEquals(1, getStats(oobChannel).callsSucceeded);
    assertEquals(0, getStats(oobChannel).callsFailed);
  } else {
    assertEquals(0, getStats(oobChannel).callsSucceeded);
    assertEquals(1, getStats(oobChannel).callsFailed);
  }
  // oob channel is separate from the original channel
  assertEquals(0, getStats(channel).callsSucceeded);
  assertEquals(0, getStats(channel).callsFailed);
}
 
Example 13
Source File: ServerCallsTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void inprocessTransportManualFlow() throws Exception {
  final Semaphore semaphore = new Semaphore(1);
  ServerServiceDefinition service = ServerServiceDefinition.builder(
      new ServiceDescriptor("some", STREAMING_METHOD))
      .addMethod(STREAMING_METHOD, ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            int iteration;

            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              final ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.setOnReadyHandler(new Runnable() {
                @Override
                public void run() {
                  while (serverCallObserver.isReady()) {
                    serverCallObserver.onNext(iteration);
                  }
                  iteration++;
                  semaphore.release();
                }
              });
              return new ServerCalls.NoopStreamObserver<Integer>() {
                @Override
                public void onCompleted() {
                  serverCallObserver.onCompleted();
                }
              };
            }
          }))
      .build();
  long tag = System.nanoTime();
  InProcessServerBuilder.forName("go-with-the-flow" + tag).addService(service).build().start();
  ManagedChannel channel = InProcessChannelBuilder.forName("go-with-the-flow" + tag).build();
  final ClientCall<Integer, Integer> clientCall = channel.newCall(STREAMING_METHOD,
      CallOptions.DEFAULT);
  final CountDownLatch latch = new CountDownLatch(1);
  final int[] receivedMessages = new int[6];
  clientCall.start(new ClientCall.Listener<Integer>() {
    int index;

    @Override
    public void onMessage(Integer message) {
      receivedMessages[index++] = message;
    }

    @Override
    public void onClose(Status status, Metadata trailers) {
      latch.countDown();
    }
  }, new Metadata());
  semaphore.acquire();
  clientCall.request(1);
  semaphore.acquire();
  clientCall.request(2);
  semaphore.acquire();
  clientCall.request(3);
  clientCall.halfClose();
  assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
  // Very that number of messages produced in each onReady handler call matches the number
  // requested by the client.
  assertArrayEquals(new int[]{0, 1, 1, 2, 2, 2}, receivedMessages);
}