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

The following examples show how to use io.grpc.ClientCall#start() . 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: ClientAuthInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyServiceUri() throws IOException {
  ClientCall<String, Integer> interceptedCall;

  doReturn("example.com:443").when(channel).authority();
  interceptedCall = interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  interceptedCall.start(listener, new Metadata());
  verify(credentials).getRequestMetadata(URI.create("https://example.com/a.service"));
  interceptedCall.cancel("Cancel for test", null);

  doReturn("example.com:123").when(channel).authority();
  interceptedCall = interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  interceptedCall.start(listener, new Metadata());
  verify(credentials).getRequestMetadata(URI.create("https://example.com:123/a.service"));
  interceptedCall.cancel("Cancel for test", null);
}
 
Example 2
Source File: ClientAuthInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithOAuth2Credential() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final OAuth2Credentials oAuth2Credentials = new OAuth2Credentials() {
    @Override
    public AccessToken refreshAccessToken() throws IOException {
      return token;
    }
  };
  interceptor = new ClientAuthInterceptor(oAuth2Credentials, executor);
  ClientCall<String, Integer> interceptedCall =
      interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  Metadata headers = new Metadata();
  interceptedCall.start(listener, headers);
  assertEquals(listener, call.responseListener);
  assertEquals(headers, call.headers);
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"Bearer allyourbase"},
      Iterables.toArray(authorization, String.class));
}
 
Example 3
Source File: ManagedChannelImplIdlenessTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void updateOobChannelAddresses_newAddressConnects() {
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata()); // Create LB
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
  Helper helper = helperCaptor.getValue();
  ManagedChannel oobChannel = helper.createOobChannel(servers.get(0), "localhost");

  oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

  helper.updateOobChannelAddresses(oobChannel, servers.get(1));

  oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
  MockClientTransportInfo t1 = newTransports.poll();
  t1.listener.transportReady();
}
 
Example 4
Source File: ManagedChannelImplIdlenessTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void updateSubchannelAddresses_existingAddressDoesNotConnect() {
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata()); // Create LB
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
  Helper helper = helperCaptor.getValue();
  Subchannel subchannel = createSubchannelSafely(helper, servers.get(0), Attributes.EMPTY);

  subchannel.requestConnection();
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

  List<SocketAddress> changedList = new ArrayList<>(servers.get(0).getAddresses());
  changedList.add(new FakeSocketAddress("aDifferentServer"));
  helper.updateSubchannelAddresses(subchannel, new EquivalentAddressGroup(changedList));

  subchannel.requestConnection();
  assertNull(newTransports.poll());
}
 
Example 5
Source File: LoggingInterceptorTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
private static Listener simulateCall(
    RequestLogger requestLogger,
    Detail detail,
    Summary summary,
    MethodDescriptor methodDescriptor,
    Channel nextChannel,
    ClientCall nextCall) {
  LoggingInterceptor interceptor =
      new LoggingInterceptor(requestLogger, detail.getRawRequestHeaders(), summary.getEndpoint());

  // Simulate a call (mocked channel doesn't actually make a call).
  ClientCall call = interceptor.interceptCall(methodDescriptor, null, nextChannel);
  Metadata upstreamHeaders = new Metadata();
  call.start(new Listener() {}, upstreamHeaders);
  call.sendMessage(detail.getRequest());

  // Capture the response listener and return this so we can test with different responses.
  ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.forClass(Listener.class);
  verify(nextCall).start(listenerCaptor.capture(), eq(upstreamHeaders));
  return listenerCaptor.getValue();
}
 
Example 6
Source File: ClientAuthInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyCredentialToHeaders() throws IOException {
  ListMultimap<String, String> values = LinkedListMultimap.create();
  values.put("Authorization", "token1");
  values.put("Authorization", "token2");
  values.put("Extra-Authorization", "token3");
  values.put("Extra-Authorization", "token4");
  when(credentials.getRequestMetadata(any(URI.class))).thenReturn(Multimaps.asMap(values));
  ClientCall<String, Integer> interceptedCall =
      interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  Metadata headers = new Metadata();
  interceptedCall.start(listener, headers);
  assertEquals(listener, call.responseListener);
  assertEquals(headers, call.headers);

  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token1", "token2"},
      Iterables.toArray(authorization, String.class));
  Iterable<String> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token3", "token4"},
      Iterables.toArray(extraAuthorization, String.class));
}
 
Example 7
Source File: GrpcStreamClientCall.java    From saluki with Apache License 2.0 5 votes vote down vote up
static void startCall(ClientCall<Message, Message> call,
    ClientCall.Listener<Message> responseListener, boolean streamingResponse) {
  call.start(responseListener, new Metadata());
  if (streamingResponse) {
    call.request(1);
  } else {
    call.request(2);
  }
}
 
Example 8
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pickerReturnsStreamTracer_delayed() {
  ClientStream mockStream = mock(ClientStream.class);
  ClientStreamTracer.Factory factory1 = mock(ClientStreamTracer.Factory.class);
  ClientStreamTracer.Factory factory2 = mock(ClientStreamTracer.Factory.class);
  createChannel();

  CallOptions callOptions = CallOptions.DEFAULT.withStreamTracerFactory(factory1);
  ClientCall<String, Integer> call = channel.newCall(method, callOptions);
  call.start(mockCallListener, new Metadata());

  Subchannel subchannel =
      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, factory2));

  updateBalancingStateSafely(helper, READY, mockPicker);
  assertEquals(1, executor.runDueTasks());

  verify(mockPicker).pickSubchannel(any(PickSubchannelArgs.class));
  verify(mockTransport).newStream(same(method), any(Metadata.class), callOptionsCaptor.capture());
  assertEquals(
      Arrays.asList(factory1, factory2),
      callOptionsCaptor.getValue().getStreamTracerFactories());
  // The factories are safely not stubbed because we do not expect any usage of them.
  verifyZeroInteractions(factory1);
  verifyZeroInteractions(factory2);
}
 
Example 9
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nameResolutionFailed_delayedTransportShutdownCancelsBackoff() {
  Status error = Status.UNAVAILABLE.withCause(new Throwable("fake name resolution error"));

  FakeNameResolverFactory nameResolverFactory =
      new FakeNameResolverFactory.Builder(expectedUri).setError(error).build();
  channelBuilder.nameResolverFactory(nameResolverFactory);
  // Name resolution is started as soon as channel is created.
  createChannel();
  verify(mockLoadBalancer).handleNameResolutionError(same(error));

  FakeClock.ScheduledTask nameResolverBackoff = getNameResolverRefresh();
  assertNotNull(nameResolverBackoff);
  assertFalse(nameResolverBackoff.isCancelled());

  // Add a pending call to the delayed transport
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  Metadata headers = new Metadata();
  call.start(mockCallListener, headers);

  // The pending call on the delayed transport stops the name resolver backoff from cancelling
  channel.shutdown();
  assertFalse(nameResolverBackoff.isCancelled());

  // Notify that a subchannel is ready, which drains the delayed transport
  SubchannelPicker picker = mock(SubchannelPicker.class);
  Status status = Status.UNAVAILABLE.withDescription("for test");
  when(picker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(PickResult.withDrop(status));
  updateBalancingStateSafely(helper, READY, picker);
  executor.runDueTasks();
  verify(mockCallListener).onClose(same(status), any(Metadata.class));

  assertTrue(nameResolverBackoff.isCancelled());
}
 
Example 10
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void subchannelChannel_normalUsage() {
  createChannel();
  Subchannel subchannel =
      createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
  verify(balancerRpcExecutorPool, never()).getObject();

  Channel sChannel = subchannel.asChannel();
  verify(balancerRpcExecutorPool).getObject();

  Metadata headers = new Metadata();
  CallOptions callOptions = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS);

  // Subchannel must be READY when creating the RPC.
  requestConnectionSafely(helper, subchannel);
  verify(mockTransportFactory)
      .newClientTransport(
          any(SocketAddress.class), any(ClientTransportOptions.class), any(ChannelLogger.class));
  MockClientTransportInfo transportInfo = transports.poll();
  ConnectionClientTransport mockTransport = transportInfo.transport;
  ManagedClientTransport.Listener transportListener = transportInfo.listener;
  transportListener.transportReady();

  ClientCall<String, Integer> call = sChannel.newCall(method, callOptions);
  call.start(mockCallListener, headers);
  verify(mockTransport).newStream(same(method), same(headers), callOptionsCaptor.capture());

  CallOptions capturedCallOption = callOptionsCaptor.getValue();
  assertThat(capturedCallOption.getDeadline()).isSameInstanceAs(callOptions.getDeadline());
  assertThat(capturedCallOption.getOption(GrpcUtil.CALL_OPTIONS_RPC_OWNED_BY_BALANCER)).isTrue();
}
 
Example 11
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 12
Source File: LoadClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  while (true) {
    maxOutstanding.acquireUninterruptibly();
    if (shutdown) {
      maxOutstanding.release();
      return;
    }
    final ClientCall<ByteBuf, ByteBuf> call =
        channel.newCall(LoadServer.GENERIC_STREAMING_PING_PONG_METHOD, CallOptions.DEFAULT);
    call.start(new ClientCall.Listener<ByteBuf>() {
      long now = System.nanoTime();

      @Override
      public void onMessage(ByteBuf message) {
        delay(System.nanoTime() - now);
        if (shutdown) {
          call.cancel("Shutting down", null);
          return;
        }
        call.request(1);
        call.sendMessage(genericRequest.slice());
        now = System.nanoTime();
      }

      @Override
      public void onClose(Status status, Metadata trailers) {
        maxOutstanding.release();
        Level level = shutdown ? Level.FINE : Level.INFO;
        if (!status.isOk() && status.getCode() != Status.Code.CANCELLED) {
          log.log(level, "Error in Generic Async Ping-Pong call", status.getCause());
        }
      }
    }, new Metadata());
    call.request(1);
    call.sendMessage(genericRequest.slice());
  }
}
 
Example 13
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void immediateDeadlineExceeded() {
  createChannel();
  ClientCall<String, Integer> call =
      channel.newCall(method, CallOptions.DEFAULT.withDeadlineAfter(0, TimeUnit.NANOSECONDS));
  call.start(mockCallListener, new Metadata());
  assertEquals(1, executor.runDueTasks());

  verify(mockCallListener).onClose(statusCaptor.capture(), any(Metadata.class));
  Status status = statusCaptor.getValue();
  assertSame(Status.DEADLINE_EXCEEDED.getCode(), status.getCode());
}
 
Example 14
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 15
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void hedgingScheduledThenChannelShutdown_hedgeShouldStillHappen_newCallShouldFail() {
  Map<String, Object> hedgingPolicy = new HashMap<>();
  hedgingPolicy.put("maxAttempts", 3D);
  hedgingPolicy.put("hedgingDelay", "10s");
  hedgingPolicy.put("nonFatalStatusCodes", Arrays.<Object>asList("UNAVAILABLE"));
  Map<String, Object> methodConfig = new HashMap<>();
  Map<String, Object> name = new HashMap<>();
  name.put("service", "service");
  methodConfig.put("name", Arrays.<Object>asList(name));
  methodConfig.put("hedgingPolicy", hedgingPolicy);
  Map<String, Object> rawServiceConfig = new HashMap<>();
  rawServiceConfig.put("methodConfig", Arrays.<Object>asList(methodConfig));

  FakeNameResolverFactory nameResolverFactory =
      new FakeNameResolverFactory.Builder(expectedUri)
          .setServers(Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
          .build();
  ManagedChannelServiceConfig managedChannelServiceConfig =
      createManagedChannelServiceConfig(rawServiceConfig, null);
  nameResolverFactory.nextConfigOrError.set(
      ConfigOrError.fromConfig(managedChannelServiceConfig));

  channelBuilder.nameResolverFactory(nameResolverFactory);
  channelBuilder.executor(MoreExecutors.directExecutor());
  channelBuilder.enableRetry();

  requestConnection = false;
  createChannel();

  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata());
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(Helper.class);
  verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture());
  helper = helperCaptor.getValue();
  verify(mockLoadBalancer).handleResolvedAddresses(
      ResolvedAddresses.newBuilder()
          .setAddresses(nameResolverFactory.servers)
          .build());

  // simulating request connection and then transport ready after resolved address
  Subchannel subchannel =
      createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
  when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(PickResult.withSubchannel(subchannel));
  requestConnectionSafely(helper, subchannel);
  MockClientTransportInfo transportInfo = transports.poll();
  ConnectionClientTransport mockTransport = transportInfo.transport;
  ClientStream mockStream = mock(ClientStream.class);
  ClientStream mockStream2 = mock(ClientStream.class);
  when(mockTransport.newStream(same(method), any(Metadata.class), any(CallOptions.class)))
      .thenReturn(mockStream).thenReturn(mockStream2);
  transportInfo.listener.transportReady();
  updateBalancingStateSafely(helper, READY, mockPicker);

  ArgumentCaptor<ClientStreamListener> streamListenerCaptor =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream).start(streamListenerCaptor.capture());

  // in hedging delay backoff
  timer.forwardTime(5, TimeUnit.SECONDS);
  assertThat(timer.numPendingTasks()).isEqualTo(1);
  // first hedge fails
  streamListenerCaptor.getValue().closed(Status.UNAVAILABLE, new Metadata());
  verify(mockStream2, never()).start(any(ClientStreamListener.class));

  // shutdown during backoff period
  channel.shutdown();

  assertThat(timer.numPendingTasks()).isEqualTo(1);
  verify(mockCallListener, never()).onClose(any(Status.class), any(Metadata.class));

  ClientCall<String, Integer> call2 = channel.newCall(method, CallOptions.DEFAULT);
  call2.start(mockCallListener2, new Metadata());

  ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
  verify(mockCallListener2).onClose(statusCaptor.capture(), any(Metadata.class));
  assertSame(Status.Code.UNAVAILABLE, statusCaptor.getValue().getCode());
  assertEquals("Channel shutdown invoked", statusCaptor.getValue().getDescription());

  // backoff ends
  timer.forwardTime(5, TimeUnit.SECONDS);
  assertThat(timer.numPendingTasks()).isEqualTo(1);
  verify(mockStream2).start(streamListenerCaptor.capture());
  verify(mockLoadBalancer, never()).shutdown();
  assertFalse(
      "channel.isTerminated() is expected to be false but was true",
      channel.isTerminated());

  streamListenerCaptor.getValue().closed(Status.INTERNAL, new Metadata());
  assertThat(timer.numPendingTasks()).isEqualTo(0);
  verify(mockLoadBalancer).shutdown();
  // simulating the shutdown of load balancer triggers the shutdown of subchannel
  shutdownSafely(helper, subchannel);
  // simulating transport shutdown & terminated
  transportInfo.listener.transportShutdown(Status.INTERNAL);
  transportInfo.listener.transportTerminated();
  assertTrue(
      "channel.isTerminated() is expected to be true but was false",
      channel.isTerminated());
}
 
Example 16
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 17
Source File: ManagedChannelImplIdlenessTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void realTransportsHoldsOffIdleness() throws Exception {
  final EquivalentAddressGroup addressGroup = servers.get(1);

  // Start a call, which goes to delayed transport
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata());

  // Verify that we have exited the idle mode
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
  Helper helper = helperCaptor.getValue();
  assertTrue(channel.inUseStateAggregator.isInUse());

  // Assume LoadBalancer has received an address, then create a subchannel.
  Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY);
  subchannel.requestConnection();
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

  SubchannelPicker mockPicker = mock(SubchannelPicker.class);
  when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(PickResult.withSubchannel(subchannel));
  helper.updateBalancingState(READY, mockPicker);
  // Delayed transport creates real streams in the app executor
  executor.runDueTasks();

  // Delayed transport exits in-use, while real transport has not entered in-use yet.
  assertFalse(channel.inUseStateAggregator.isInUse());

  // Now it's in-use
  t0.listener.transportInUse(true);
  assertTrue(channel.inUseStateAggregator.isInUse());

  // As long as the transport is in-use, the channel won't go idle.
  timer.forwardTime(IDLE_TIMEOUT_SECONDS * 2, TimeUnit.SECONDS);
  assertTrue(channel.inUseStateAggregator.isInUse());

  t0.listener.transportInUse(false);
  assertFalse(channel.inUseStateAggregator.isInUse());
  // And allow the channel to go idle.
  timer.forwardTime(IDLE_TIMEOUT_SECONDS - 1, TimeUnit.SECONDS);
  verify(mockLoadBalancer, never()).shutdown();
  timer.forwardTime(1, TimeUnit.SECONDS);
  verify(mockLoadBalancer).shutdown();
}
 
Example 18
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 19
Source File: ClientCalls.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private static <ReqT, RespT> void startCall(
    ClientCall<ReqT, RespT> call,
    StartableListener<RespT> responseListener) {
  call.start(responseListener, new Metadata());
  responseListener.onStart();
}
 
Example 20
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));
}