Java Code Examples for io.grpc.Deadline#after()

The following examples show how to use io.grpc.Deadline#after() . 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: ServiceConfigInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nearerDeadlineKept_new() {
  // TODO(carl-mastrangelo): the deadlines are very large because they change over time.
  // This should be fixed, and is tracked in https://github.com/grpc/grpc-java/issues/2531
  JsonObj name = new JsonObj("service", "service");
  JsonObj methodConfig = new JsonObj("name", new JsonList(name), "timeout", "1s");
  JsonObj serviceConfig = new JsonObj("methodConfig", new JsonList(methodConfig));

  interceptor.handleUpdate(serviceConfig);

  Deadline existingDeadline = Deadline.after(1234567890, TimeUnit.NANOSECONDS);
  interceptor.interceptCall(
      methodDescriptor, CallOptions.DEFAULT.withDeadline(existingDeadline), channel);

  verify(channel).newCall(eq(methodDescriptor), callOptionsCap.capture());
  assertThat(callOptionsCap.getValue().getDeadline()).isNotEqualTo(existingDeadline);
}
 
Example 2
Source File: GrpcClient.java    From etcd-java with Apache License 2.0 6 votes vote down vote up
protected <ReqT,R> ListenableFuture<R> fuCall(MethodDescriptor<ReqT,R> method, ReqT request,
        CallOptions callOptions, long timeoutMs) {
    if (timeoutMs <= 0L) {
        timeoutMs = defaultTimeoutMs;
    }
    if (timeoutMs > 0L) {
        Deadline deadline = callOptions.getDeadline();
        Deadline timeoutDeadline = Deadline.after(timeoutMs, MILLISECONDS);
        if (deadline == null || timeoutDeadline.isBefore(deadline)) {
            callOptions = callOptions.withDeadline(timeoutDeadline);
        } else if (deadline.isExpired()) {
            return Futures.immediateFailedFuture(
                    Status.DEADLINE_EXCEEDED.asRuntimeException());
        }
    }
    final CallOptions finalCallOpts = callOptions;
    return sendViaEventLoop && !isEventThread.satisfied()
            ? Futures.submitAsync(() -> fuCall(method, request, finalCallOpts), ses)
                    : fuCall(method, request, finalCallOpts);
}
 
Example 3
Source File: ServiceConfigInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nearerDeadlineKept_existing() {
  JsonObj name = new JsonObj("service", "service");
  JsonObj methodConfig = new JsonObj("name", new JsonList(name), "timeout", "100000s");
  JsonObj serviceConfig = new JsonObj("methodConfig", new JsonList(methodConfig));
  ManagedChannelServiceConfig parsedServiceConfig =
      createManagedChannelServiceConfig(serviceConfig);

  interceptor.handleUpdate(parsedServiceConfig);

  Deadline existingDeadline = Deadline.after(1000, TimeUnit.NANOSECONDS);
  interceptor.interceptCall(
      methodDescriptor, CallOptions.DEFAULT.withDeadline(existingDeadline), channel);

  verify(channel).newCall(eq(methodDescriptor), callOptionsCap.capture());
  assertThat(callOptionsCap.getValue().getDeadline()).isEqualTo(existingDeadline);
}
 
Example 4
Source File: CASFileCacheTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void readRemovesNonexistentEntry() throws IOException, InterruptedException {
  ByteString content = ByteString.copyFromUtf8("Hello, World");
  Blob blob = new Blob(content, DIGEST_UTIL);

  fileCache.put(blob);
  String key = fileCache.getKey(blob.getDigest(), /* isExecutable=*/ false);
  // putCreatesFile verifies this
  Files.delete(fileCache.getPath(key));
  // update entry with expired deadline
  storage.get(key).existsDeadline = Deadline.after(0, SECONDS);

  try (InputStream in = fileCache.newInput(blob.getDigest(), /* offset=*/ 0)) {
    fail("should not get here");
  } catch (NoSuchFileException e) {
    // success
  }
  assertThat(storage.containsKey(key)).isFalse();
}
 
Example 5
Source File: ServiceConfigInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nearerDeadlineKept_new() {
  // TODO(carl-mastrangelo): the deadlines are very large because they change over time.
  // This should be fixed, and is tracked in https://github.com/grpc/grpc-java/issues/2531
  JsonObj name = new JsonObj("service", "service");
  JsonObj methodConfig = new JsonObj("name", new JsonList(name), "timeout", "1s");
  JsonObj serviceConfig = new JsonObj("methodConfig", new JsonList(methodConfig));
  ManagedChannelServiceConfig parsedServiceConfig =
      createManagedChannelServiceConfig(serviceConfig);

  interceptor.handleUpdate(parsedServiceConfig);

  Deadline existingDeadline = Deadline.after(1234567890, TimeUnit.NANOSECONDS);
  interceptor.interceptCall(
      methodDescriptor, CallOptions.DEFAULT.withDeadline(existingDeadline), channel);

  verify(channel).newCall(eq(methodDescriptor), callOptionsCap.capture());
  assertThat(callOptionsCap.getValue().getDeadline()).isNotEqualTo(existingDeadline);
}
 
Example 6
Source File: CASFileCache.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private boolean directoryEntryExists(
    Path path, DirectoryEntry dirEntry, Map<Digest, Directory> directoriesIndex) {
  if (!dirEntry.existsDeadline.isExpired()) {
    return true;
  }

  if (directoryExists(path, dirEntry.directory, directoriesIndex)) {
    dirEntry.existsDeadline = Deadline.after(10, SECONDS);
    return true;
  }
  return false;
}
 
Example 7
Source File: StubConfigTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigureDeadline() {
  Deadline deadline = Deadline.after(2, NANOSECONDS);
  // Create a default stub
  TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel);
  assertNull(stub.getCallOptions().getDeadline());
  // Reconfigure it
  TestServiceGrpc.TestServiceBlockingStub reconfiguredStub = stub.withDeadline(deadline);
  // New altered config
  assertEquals(deadline, reconfiguredStub.getCallOptions().getDeadline());
  // Default config unchanged
  assertNull(stub.getCallOptions().getDeadline());
}
 
Example 8
Source File: CascadingTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeadlinePropagation() throws Exception {
  final AtomicInteger recursionDepthRemaining = new AtomicInteger(3);
  final SettableFuture<Deadline> finalDeadline = SettableFuture.create();
  class DeadlineSaver extends TestServiceGrpc.TestServiceImplBase {
    @Override
    public void unaryCall(final SimpleRequest request,
        final StreamObserver<SimpleResponse> responseObserver) {
      Context.currentContextExecutor(otherWork).execute(new Runnable() {
        @Override
        public void run() {
          try {
            if (recursionDepthRemaining.decrementAndGet() == 0) {
              finalDeadline.set(Context.current().getDeadline());
              responseObserver.onNext(SimpleResponse.getDefaultInstance());
            } else {
              responseObserver.onNext(blockingStub.unaryCall(request));
            }
            responseObserver.onCompleted();
          } catch (Exception ex) {
            responseObserver.onError(ex);
          }
        }
      });
    }
  }

  server = InProcessServerBuilder.forName("channel").executor(otherWork)
      .addService(new DeadlineSaver())
      .build().start();

  Deadline initialDeadline = Deadline.after(1, TimeUnit.MINUTES);
  blockingStub.withDeadline(initialDeadline).unaryCall(SimpleRequest.getDefaultInstance());
  assertNotSame(initialDeadline, finalDeadline);
  // Since deadline is re-calculated at each hop, some variance is acceptable and expected.
  assertAbout(deadline())
      .that(finalDeadline.get()).isWithin(1, TimeUnit.SECONDS).of(initialDeadline);
}
 
Example 9
Source File: GrpclbFallbackTestClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void runSlowFallbackAfterStartup() throws Exception {
  initStub();
  assertEquals(
      GrpclbRouteType.GRPCLB_ROUTE_TYPE_BACKEND,
      doRpcAndGetPath(Deadline.after(20, TimeUnit.SECONDS)));
  runShellCmd(blackholeLbAndBackendAddrsCmd);
  final Deadline fallbackDeadline = Deadline.after(40, TimeUnit.SECONDS);
  waitForFallbackAndDoRpcs(fallbackDeadline);
}
 
Example 10
Source File: CascadingTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeadlinePropagation() throws Exception {
  final AtomicInteger recursionDepthRemaining = new AtomicInteger(3);
  final SettableFuture<Deadline> finalDeadline = SettableFuture.create();
  class DeadlineSaver extends TestServiceGrpc.TestServiceImplBase {
    @Override
    public void unaryCall(final SimpleRequest request,
        final StreamObserver<SimpleResponse> responseObserver) {
      Context.currentContextExecutor(otherWork).execute(new Runnable() {
        @Override
        public void run() {
          try {
            if (recursionDepthRemaining.decrementAndGet() == 0) {
              finalDeadline.set(Context.current().getDeadline());
              responseObserver.onNext(SimpleResponse.getDefaultInstance());
            } else {
              responseObserver.onNext(blockingStub.unaryCall(request));
            }
            responseObserver.onCompleted();
          } catch (Exception ex) {
            responseObserver.onError(ex);
          }
        }
      });
    }
  }

  server = InProcessServerBuilder.forName("channel").executor(otherWork)
      .addService(new DeadlineSaver())
      .build().start();

  Deadline initialDeadline = Deadline.after(1, TimeUnit.MINUTES);
  blockingStub.withDeadline(initialDeadline).unaryCall(SimpleRequest.getDefaultInstance());
  assertNotSame(initialDeadline, finalDeadline);
  // Since deadline is re-calculated at each hop, some variance is acceptable and expected.
  assertAbout(deadline())
      .that(finalDeadline.get()).isWithin(1, TimeUnit.SECONDS).of(initialDeadline);
}
 
Example 11
Source File: CASFileCache.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private boolean entryExists(Entry e) {
  if (!e.existsDeadline.isExpired()) {
    return true;
  }

  if (Files.exists(getPath(e.key))) {
    e.existsDeadline = Deadline.after(10, SECONDS);
    return true;
  }
  return false;
}
 
Example 12
Source File: AbstractStubTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void settingCallOptionsWorks() {
    ManagedChannel channel = serverRule.getChannel();
    Deadline deadline = Deadline.after(42, TimeUnit.SECONDS);

    ReactorGreeterGrpc.ReactorGreeterStub stub = ReactorGreeterGrpc.newReactorStub(channel).withDeadline(deadline);

    assertThat(stub.getCallOptions().getDeadline()).isEqualTo(deadline);
}
 
Example 13
Source File: AbstractStubTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void settingCallOptionsWorks() {
    ManagedChannel channel = serverRule.getChannel();
    Deadline deadline = Deadline.after(42, TimeUnit.SECONDS);

    RxGreeterGrpc.RxGreeterStub stub = RxGreeterGrpc.newRxStub(channel).withDeadline(deadline);

    assertThat(stub.getCallOptions().getDeadline()).isEqualTo(deadline);
}
 
Example 14
Source File: ServiceConfigInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nearerDeadlineKept_existing() {
  JsonObj name = new JsonObj("service", "service");
  JsonObj methodConfig = new JsonObj("name", new JsonList(name), "timeout", "100000s");
  JsonObj serviceConfig = new JsonObj("methodConfig", new JsonList(methodConfig));

  interceptor.handleUpdate(serviceConfig);

  Deadline existingDeadline = Deadline.after(1000, TimeUnit.NANOSECONDS);
  interceptor.interceptCall(
      methodDescriptor, CallOptions.DEFAULT.withDeadline(existingDeadline), channel);

  verify(channel).newCall(eq(methodDescriptor), callOptionsCap.capture());
  assertThat(callOptionsCap.getValue().getDeadline()).isEqualTo(existingDeadline);
}
 
Example 15
Source File: StubConfigTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigureDeadline() {
  Deadline deadline = Deadline.after(2, NANOSECONDS);
  // Create a default stub
  TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel);
  assertNull(stub.getCallOptions().getDeadline());
  // Reconfigure it
  TestServiceGrpc.TestServiceBlockingStub reconfiguredStub = stub.withDeadline(deadline);
  // New altered config
  assertEquals(deadline, reconfiguredStub.getCallOptions().getDeadline());
  // Default config unchanged
  assertNull(stub.getCallOptions().getDeadline());
}
 
Example 16
Source File: CASFileCache.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
private void processRootFile(
    Path file,
    ImmutableList.Builder<Path> computeDirs,
    ImmutableList.Builder<Path> deleteFiles,
    ImmutableMap.Builder<Object, Entry> fileKeys)
    throws IOException, InterruptedException {

  String basename = file.getFileName().toString();

  // ignore our directories index database
  // indexes will be removed and rebuilt for compute
  if (!basename.equals(directoriesIndexDbName)) {
    FileStatus stat = stat(file, false);

    // mark directory for later key compute
    if (file.toString().endsWith("_dir")) {
      if (stat.isDirectory()) {
        synchronized (computeDirs) {
          computeDirs.add(file);
        }
      } else {
        synchronized (deleteFiles) {
          deleteFiles.add(file);
        }
      }
    } else if (stat.isDirectory()) {
      synchronized (deleteFiles) {
        deleteFiles.add(file);
      }
    } else {
      // if cas is full or entry is oversized or empty, mark file for later deletion.
      long size = stat.getSize();
      if (sizeInBytes + size > maxSizeInBytes || size > maxEntrySizeInBytes || size == 0) {
        synchronized (deleteFiles) {
          deleteFiles.add(file);
        }
      } else {
        // get the key entry from the file name.
        FileEntryKey fileEntryKey = parseFileEntryKey(basename, stat.getSize());

        // if key entry file name cannot be parsed, mark file for later deletion.
        if (fileEntryKey == null
            || stat.isReadOnlyExecutable() != fileEntryKey.getIsExecutable()) {
          synchronized (deleteFiles) {
            deleteFiles.add(file);
          }
        } else {
          // populate key it is not currently stored.
          String key = fileEntryKey.getKey();
          Entry e = new Entry(key, size, Deadline.after(10, SECONDS));
          synchronized (fileKeys) {
            fileKeys.put(getFileKey(root.resolve(key), stat), e);
          }
          storage.put(e.key, e);
          onPut.accept(fileEntryKey.getDigest());
          synchronized (CASFileCache.this) {
            e.decrementReference(header);
          }
          sizeInBytes += size;
        }
      }
    }
  }
}
 
Example 17
Source File: Poller.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
public Poller(Duration period) {
  checkState(period.getSeconds() > 0 || period.getNanos() >= 1000);
  periodMicros = period.getSeconds() * 1000000 + period.getNanos() / 1000;
  periodDeadline = Deadline.after(periodMicros, MICROSECONDS);
}
 
Example 18
Source File: GrpclbFallbackTestClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void runFastFallbackBeforeStartup() throws Exception {
  runShellCmd(unrouteLbAndBackendAddrsCmd);
  final Deadline fallbackDeadline = Deadline.after(5, TimeUnit.SECONDS);
  initStub();
  waitForFallbackAndDoRpcs(fallbackDeadline);
}
 
Example 19
Source File: GrpclbFallbackTestClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void runSlowFallbackBeforeStartup() throws Exception {
  runShellCmd(blackholeLbAndBackendAddrsCmd);
  final Deadline fallbackDeadline = Deadline.after(20, TimeUnit.SECONDS);
  initStub();
  waitForFallbackAndDoRpcs(fallbackDeadline);
}
 
Example 20
Source File: HelloClient.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
protected static Deadline getDeadline() {
    return Deadline.after(10, TimeUnit.SECONDS);
}