io.grpc.inprocess.InProcessChannelBuilder Java Examples

The following examples show how to use io.grpc.inprocess.InProcessChannelBuilder. 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: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthException() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    when(hcsf.get()).thenThrow(InterruptedException.class);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));

    thrown.expect(StatusRuntimeException.class);
    thrown.expect(hasProperty("status", is(Status.INTERNAL)));
    blockingStub.check(HealthCheckRequest.newBuilder().build());

}
 
Example #2
Source File: GoalStateProvisionerClientTest.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();

    // Create a server, add service, start, and register for automatic graceful shutdown.
    grpcCleanup.register(InProcessServerBuilder
            .forName(serverName).directExecutor().addService(serviceImpl).build().start());

    // Create a client channel and register for automatic graceful shutdown.
    ManagedChannel channel = grpcCleanup.register(
            InProcessChannelBuilder.forName(serverName).directExecutor().build());

    // Create a client using the in-process channel;
    client = new GoalStateProvisionerClient(channel);
}
 
Example #3
Source File: ProtoReflectionServiceTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  reflectionService = ProtoReflectionService.newInstance();
  Server server =
      InProcessServerBuilder.forName("proto-reflection-test")
          .directExecutor()
          .addService(reflectionService)
          .addService(new ReflectableServiceGrpc.ReflectableServiceImplBase() {})
          .fallbackHandlerRegistry(handlerRegistry)
          .build()
          .start();
  grpcCleanupRule.register(server);
  ManagedChannel channel =
      grpcCleanupRule.register(
          InProcessChannelBuilder.forName("proto-reflection-test").directExecutor().build());
  stub = ServerReflectionGrpc.newStub(channel);
}
 
Example #4
Source File: FlairCachingServiceIntTest.java    From flair-engine with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    String serverName = InProcessServerBuilder.generateName();

    grpcCleanup.register(InProcessServerBuilder
            .forName(serverName)
            .directExecutor()
            .addService(cacheService)
            .build()
            .start());

    channel = grpcCleanup.register(InProcessChannelBuilder
            .forName(serverName)
            .directExecutor()
            .build());

    when(managedChannelFactory.getInstance()).thenReturn(channel);
}
 
Example #5
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthServing() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    HealthCheckStatus hcs = mock(HealthCheckStatus.class);
    when(hcs.isHealthy()).thenReturn(true);
    when(hcsf.get()).thenReturn(hcs);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));


    HealthCheckResponse reply = blockingStub.check(HealthCheckRequest.newBuilder().build());

    assertEquals(HealthCheckResponse.ServingStatus.SERVING, reply.getStatus());
}
 
Example #6
Source File: FeastClientTest.java    From feast with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  this.grpcRule = new GrpcCleanupRule();
  // setup fake serving service
  String serverName = InProcessServerBuilder.generateName();
  this.grpcRule.register(
      InProcessServerBuilder.forName(serverName)
          .directExecutor()
          .addService(this.servingMock)
          .build()
          .start());

  // setup test feast client target
  ManagedChannel channel =
      this.grpcRule.register(
          InProcessChannelBuilder.forName(serverName).directExecutor().build());
  this.client = new FeastClient(channel);
}
 
Example #7
Source File: HeaderServerInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  GreeterImplBase greeterImplBase =
      new GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
          responseObserver.onNext(HelloReply.getDefaultInstance());
          responseObserver.onCompleted();
        }
      };
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
      .addService(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example #8
Source File: GrpcServerTestBase.java    From grpc-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Before
public final void setupChannels() throws IOException {
    if(gRpcServerProperties.isEnabled()) {
        ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress("localhost", getPort());
        Resource certChain = Optional.ofNullable(gRpcServerProperties.getSecurity())
                .map(GRpcServerProperties.SecurityProperties::getCertChain)
                .orElse(null);
        if(null!= certChain){
            ((NettyChannelBuilder)channelBuilder)
                    .useTransportSecurity()
                    .sslContext(GrpcSslContexts.forClient().trustManager(certChain.getInputStream()).build());
        }else{
            channelBuilder.usePlaintext();
        }


        channel = onChannelBuild(channelBuilder).build();
    }
    if(StringUtils.hasText(gRpcServerProperties.getInProcessServerName())){
        inProcChannel = onChannelBuild(
                            InProcessChannelBuilder.forName(gRpcServerProperties.getInProcessServerName())
                            .usePlaintext()
                        ).build();

    }
}
 
Example #9
Source File: ByteStreamServiceTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void missingBlobReadIsNotFound() {
  ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!");
  Digest digest = DIGEST_UTIL.compute(helloWorld);

  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);

  when(simpleBlobStore.get(eq(digest.getHash()), any(OutputStream.class)))
      .thenReturn(immediateFuture(false));
  ReadRequest request =
      ReadRequest.newBuilder().setResourceName(createBlobDownloadResourceName(digest)).build();
  StatusRuntimeException notFoundException = null;
  try {
    if (service.read(request).hasNext()) {
      fail("no responses should be available");
    }
  } catch (StatusRuntimeException e) {
    assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Code.NOT_FOUND);
    notFoundException = e;
  }
  assertThat(notFoundException).isNotNull();
}
 
Example #10
Source File: GrpcRemoteDownloaderTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private GrpcRemoteDownloader newDownloader(RemoteCacheClient cacheClient) throws IOException {
  final RemoteOptions remoteOptions = Options.getDefaults(RemoteOptions.class);
  final RemoteRetrier retrier =
      TestUtils.newRemoteRetrier(
          () -> new ExponentialBackoff(remoteOptions),
          RemoteRetrier.RETRIABLE_GRPC_ERRORS,
          retryService);
  final ReferenceCountedChannel channel =
      new ReferenceCountedChannel(
          InProcessChannelBuilder.forName(fakeServerName).directExecutor().build());
  return new GrpcRemoteDownloader(
      channel.retain(),
      Optional.<CallCredentials>empty(),
      retrier,
      withEmptyMetadata,
      cacheClient,
      remoteOptions);
}
 
Example #11
Source File: ReactorGRpcBenchmark.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup
public void setup() throws IOException {
    System.out.println("---------- SETUP ONCE -------------");
    ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(Runtime.getRuntime()
                                                .availableProcessors());
    reactiveServer =
        InProcessServerBuilder.forName("benchmark-reactiveServer")
                              .scheduledExecutorService(scheduledExecutorService)
                              .addService(new BenchmarkReactorServerServiceImpl(100000))
                              .build()
                              .start();

    reactiveChannel = InProcessChannelBuilder.forName("benchmark-reactiveServer")
                                             .build();
    reactiveClient = ReactorBenchmarkServiceGrpc.newReactorStub(reactiveChannel);
}
 
Example #12
Source File: ByteStreamServiceTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void completedWriteQueryIsFound() 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);

  when(simpleBlobStore.containsKey(digest.getHash())).thenReturn(true);

  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);
  QueryWriteStatusResponse response =
      service.queryWriteStatus(
          QueryWriteStatusRequest.newBuilder().setResourceName(resourceName).build());
  assertThat(response)
      .isEqualTo(
          QueryWriteStatusResponse.newBuilder()
              .setCommittedSize(digest.getSizeBytes())
              .setComplete(true)
              .build());
  verify(simpleBlobStore, times(1)).containsKey(eq(digest.getHash()));
}
 
Example #13
Source File: GrpcRetryInterceptorTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryOnUnavailable() throws IOException {
  String uniqueName = InProcessServerBuilder.generateName();
  ExecutionImpl service = new ExecutionImpl(Status.UNAVAILABLE, 0);
  InProcessServerBuilder.forName(uniqueName).addService(service).build().start();
  CallCounter beforeRetry = new CallCounter();
  ManagedChannel channel =
      InProcessChannelBuilder.forName(uniqueName)
          .intercept(
              new RetryClientInterceptor(
                  RetryPolicy.builder().setMaxRetries(2).setBeforeRetry(beforeRetry).build()))
          .build();
  ExecutionBlockingStub stub = ExecutionGrpc.newBlockingStub(channel);
  try {
    stub.execute(ExecuteRequest.newBuilder().build()).forEachRemaining(resp -> {});
    Assert.fail("Final retry should cause an exception");
  } catch (StatusRuntimeException ex) {
    Assert.assertEquals(Status.Code.UNAVAILABLE, ex.getStatus().getCode());
  }

  Assert.assertEquals(3, service.calls);
  Assert.assertEquals(2, beforeRetry.calls);
}
 
Example #14
Source File: TestRemoteExecutionClients.java    From buck with Apache License 2.0 6 votes vote down vote up
public TestRemoteExecutionClients(List<BindableService> services) throws IOException {
  eventBus = new DefaultBuckEventBus(new DefaultClock(), new BuildId("dontcare"));
  String serverName = "uniquish-" + new Random().nextLong();

  InProcessServerBuilder serverBuilder =
      InProcessServerBuilder.forName(serverName).directExecutor();
  for (BindableService service : services) {
    serverBuilder.addService(service);
  }

  server = serverBuilder.build().start();
  ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build();

  clients =
      new GrpcRemoteExecutionClients(
          "buck",
          channel,
          channel,
          100,
          MetadataProviderFactory.emptyMetadataProvider(),
          eventBus,
          FakeBuckConfig.builder()
              .build()
              .getView(RemoteExecutionConfig.class)
              .getStrategyConfig());
}
 
Example #15
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthNotServing() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    HealthCheckStatus hcs = mock(HealthCheckStatus.class);
    when(hcs.isHealthy()).thenReturn(false);
    when(hcsf.get()).thenReturn(hcs);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));


    HealthCheckResponse reply = blockingStub.check(HealthCheckRequest.newBuilder().build());

    assertEquals(HealthCheckResponse.ServingStatus.NOT_SERVING, reply.getStatus());
}
 
Example #16
Source File: HelloWorldClientTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();

  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder
      .forName(serverName).directExecutor().addService(serviceImpl).build().start());

  // Create a client channel and register for automatic graceful shutdown.
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());

  // Create a HelloWorldClient using the in-process channel;
  client = new HelloWorldClient(channel);
}
 
Example #17
Source File: TestExternalJobProgressUpdates.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  final String name = InProcessServerBuilder.generateName();
  server = InProcessServerBuilder.forName(name)
    .directExecutor()
    .addService(new JobsServiceAdapter(p(LocalJobsService.class)))
    .addService(new Chronicle(p(LocalJobsService.class)))
    .build();
  server.start();

  channel = InProcessChannelBuilder.forName(name)
    .directExecutor()
    .build();
  asyncStub = JobsServiceGrpc.newStub(channel);

  query = getFile("tpch_quoted.sql");
}
 
Example #18
Source File: TestChronicle.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws IOException {
  final String name = InProcessServerBuilder.generateName();
  server = InProcessServerBuilder.forName(name)
    .directExecutor()
    .addService(new JobsServiceAdapter(p(LocalJobsService.class)))
    .addService(new Chronicle(p(LocalJobsService.class)))
    .build();
  server.start();

  channel = InProcessChannelBuilder.forName(name)
    .directExecutor()
    .build();

  asyncStub = JobsServiceGrpc.newStub(channel);
  chronicleStub = ChronicleGrpc.newBlockingStub(channel);
}
 
Example #19
Source File: GrpcCASTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void putAddsExpiration() throws IOException, InterruptedException {
  ByteString uploadContent = ByteString.copyFromUtf8("uploaded");
  Digest digest = DIGEST_UTIL.compute(uploadContent);
  String instanceName = "test";
  ListMultimap<Digest, Runnable> onExpirations =
      MultimapBuilder.hashKeys().arrayListValues().build();
  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ByteStreamUploader uploader = mock(ByteStreamUploader.class);
  GrpcCAS cas = new GrpcCAS(instanceName, channel, uploader, onExpirations);
  Runnable onExpiration = mock(Runnable.class);
  cas.put(new Blob(uploadContent, digest), onExpiration);
  verify(uploader, times(1))
      .uploadBlob(eq(HashCode.fromString(digest.getHash())), any(Chunker.class));
  assertThat(onExpirations.get(digest)).containsExactly(onExpiration);
  verifyZeroInteractions(onExpiration);
}
 
Example #20
Source File: GrpcServerRule.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Before the test has started, create the server and channel.
 */
@Override
protected void before() throws Throwable {
  serverName = UUID.randomUUID().toString();

  serviceRegistry = new MutableHandlerRegistry();

  InProcessServerBuilder serverBuilder = InProcessServerBuilder.forName(serverName)
      .fallbackHandlerRegistry(serviceRegistry);

  if (useDirectExecutor) {
    serverBuilder.directExecutor();
  }

  server = serverBuilder.build().start();

  InProcessChannelBuilder channelBuilder = InProcessChannelBuilder.forName(serverName);

  if (useDirectExecutor) {
    channelBuilder.directExecutor();
  }

  channel = channelBuilder.build();
}
 
Example #21
Source File: TitusClientImplTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException {
    final MockJobManagerService mockJobManagerService = new MockJobManagerService();

    testServer = InProcessServerBuilder
            .forName("testServer")
            .directExecutor()
            .addService(mockJobManagerService)
            .build()
            .start();

    final ManagedChannel channel = InProcessChannelBuilder
            .forName("testServer")
            .directExecutor()
            .usePlaintext(true)
            .build();
    final JobManagementServiceStub jobManagementServiceStub = JobManagementServiceGrpc.newStub(channel);
    final JobManagementServiceFutureStub jobManagementServiceFutureStub = JobManagementServiceGrpc.newFutureStub(channel);
    titusClient = new TitusClientImpl(jobManagementServiceStub, jobManagementServiceFutureStub, new DefaultRegistry());
}
 
Example #22
Source File: CompletableFutureStubTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void AbstractStubFeaturesShouldPropagate() throws Exception {
    com.google.common.base.Preconditions.checkArgument(true);
    Channel channel = InProcessChannelBuilder.forName("ignore").build();
    com.salesforce.jprotoc.GreeterGrpc8.GreeterCompletableFutureStub stub = com.salesforce.jprotoc.GreeterGrpc8
                    .newCompletableFutureStub(channel)
                    .withCompression("bz2")
                    .withMaxInboundMessageSize(42);

    Field innerStubField = com.salesforce.jprotoc.GreeterGrpc8.GreeterCompletableFutureStub.class.getDeclaredField("innerStub");
    innerStubField.setAccessible(true);
    com.salesforce.jprotoc.GreeterGrpc.GreeterFutureStub innerStub = (com.salesforce.jprotoc.GreeterGrpc.GreeterFutureStub) innerStubField.get(stub);

    assertEquals("bz2", stub.getCallOptions().getCompressor());
    assertEquals(new Integer(42), stub.getCallOptions().getMaxInboundMessageSize());

    assertEquals("bz2", innerStub.getCallOptions().getCompressor());
    assertEquals(new Integer(42), innerStub.getCallOptions().getMaxInboundMessageSize());

    assertEquals(stub.getCallOptions().toString(), innerStub.getCallOptions().toString());
}
 
Example #23
Source File: GrpcTccClientMessageSenderTest.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();

  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder.forName(serverName).
      fallbackHandlerRegistry(serviceRegistry).directExecutor().build().start());

  // Create a client channel and register for automatic graceful shutdown.
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());

  // Create a TccEventServiceStub using the in-process channel;
  service = new GrpcTccClientMessageSender(serviceConfig, channel, address, handler, null);
}
 
Example #24
Source File: LoggingInterceptorTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Before
public final void setUp() throws Exception {
  // Use a mutable service registry for later registering the service impl for each test case.
  fakeServer =
      InProcessServerBuilder.forName(fakeServerName)
          .fallbackHandlerRegistry(serviceRegistry)
          .directExecutor()
          .build()
          .start();
  logStream = Mockito.mock(AsynchronousFileOutputStream.class);
  clock = new ManualClock();
  interceptor = new LoggingInterceptor(logStream, clock);
  loggedChannel =
      ClientInterceptors.intercept(
          InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(), interceptor);
}
 
Example #25
Source File: ByteStreamServiceTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void missingWriteQueryIsNotFound() throws IOException {
  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();
  ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);

  StatusRuntimeException notFoundException = null;
  try {
    service.queryWriteStatus(
        QueryWriteStatusRequest.newBuilder().setResourceName(resourceName).build());
  } catch (StatusRuntimeException e) {
    assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Code.NOT_FOUND);
    notFoundException = e;
  }
  assertThat(notFoundException).isNotNull();
}
 
Example #26
Source File: ByteStreamUploaderTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Test(expected = IOException.class)
public void uploadBlobPropagatesIOExceptionFromIncompleteUpload()
    throws IOException, InterruptedException {
  serviceRegistry.addService(
      new ByteStreamImplBase() {
        @Override
        public StreamObserver<WriteRequest> write(
            StreamObserver<WriteResponse> responseObserver) {
          responseObserver.onNext(WriteResponse.newBuilder().setCommittedSize(1).build());
          responseObserver.onCompleted();
          return new StreamObserver<WriteRequest>() {
            @Override
            public void onNext(WriteRequest request) {}

            @Override
            public void onError(Throwable t) {}

            @Override
            public void onCompleted() {}
          };
        }
      });
  ByteStreamUploader uploader =
      new ByteStreamUploader(
          /* instanceName=*/ null,
          InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(),
          /* callCredentials=*/ null,
          /* callTimeoutSecs=*/ 1,
          NO_RETRIES);
  Chunker chunker = Chunker.builder().setInput(ByteString.copyFromUtf8("Hello, World!")).build();
  uploader.uploadBlob(HashCode.fromInt(42), chunker);
}
 
Example #27
Source File: RouteGuideServerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  features = new ArrayList<>();
  // Use directExecutor for both InProcessServerBuilder and InProcessChannelBuilder can reduce the
  // usage timeouts and latches in test. But we still add timeout and latches where they would be
  // needed if no directExecutor were used, just for demo purpose.
  server = new RouteGuideServer(
      InProcessServerBuilder.forName(serverName).directExecutor(), 0, features);
  server.start();
  // Create a client channel and register for automatic graceful shutdown.
  inProcessChannel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example #28
Source File: MonitoringClientInterceptorIntegrationTest.java    From java-grpc-prometheus with Apache License 2.0 5 votes vote down vote up
private HelloServiceStub createClientStub(Configuration configuration) {
  return HelloServiceGrpc.newStub(InProcessChannelBuilder.forName(grpcServerName)
      .usePlaintext()
      .intercept(MonitoringClientInterceptor.create(
          configuration.withCollectorRegistry(collectorRegistry)))
      .build());
}
 
Example #29
Source File: GrpcCASTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Test
public void writeIsResumable() throws Exception {
  UUID uuid = UUID.randomUUID();
  ByteString writeContent = ByteString.copyFromUtf8("written");
  Digest digest = DIGEST_UTIL.compute(writeContent);
  String instanceName = "test";
  HashCode hash = HashCode.fromString(digest.getHash());
  String resourceName =
      ByteStreamUploader.uploadResourceName(instanceName, uuid, hash, digest.getSizeBytes());

  // better test might just put a full gRPC CAS behind an in-process and validate state
  SettableFuture<ByteString> content = SettableFuture.create();
  serviceRegistry.addService(
      new ByteStreamServiceWriter(resourceName, content, (int) digest.getSizeBytes()));

  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  GrpcCAS cas = new GrpcCAS(instanceName, channel, /* uploader=*/ null, onExpirations);
  RequestMetadata requestMetadata = RequestMetadata.getDefaultInstance();
  Write initialWrite = cas.getWrite(digest, uuid, requestMetadata);
  try (OutputStream writeOut = initialWrite.getOutput(1, SECONDS, () -> {})) {
    writeContent.substring(0, 4).writeTo(writeOut);
  }
  Write finalWrite = cas.getWrite(digest, uuid, requestMetadata);
  try (OutputStream writeOut = finalWrite.getOutput(1, SECONDS, () -> {})) {
    writeContent.substring(4).writeTo(writeOut);
  }
  assertThat(content.get(1, TimeUnit.SECONDS)).isEqualTo(writeContent);
}
 
Example #30
Source File: GrpcActionCacheTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  fakeServer =
      InProcessServerBuilder.forName(fakeServerName)
          .fallbackHandlerRegistry(serviceRegistry)
          .directExecutor()
          .build()
          .start();

  ac =
      new GrpcActionCache(
          instanceName, InProcessChannelBuilder.forName(fakeServerName).directExecutor().build());
}