io.grpc.Deadline Java Examples

The following examples show how to use io.grpc.Deadline. 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: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 7 votes vote down vote up
@Test
public void contextDeadlineShouldBePropagatedToStream() {
  Context context = Context.current()
      .withDeadlineAfter(1000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor);
  Context origContext = context.attach();

  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);
  call.start(callListener, new Metadata());

  context.detach(origContext);

  ArgumentCaptor<Deadline> deadlineCaptor = ArgumentCaptor.forClass(Deadline.class);
  verify(stream).setDeadline(deadlineCaptor.capture());

  assertTimeoutBetween(deadlineCaptor.getValue().timeRemaining(TimeUnit.MILLISECONDS), 600, 1000);
}
 
Example #2
Source File: CASFileCacheTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void newInputRemovesNonExistentEntry() throws IOException, InterruptedException {
  Digest nonexistentDigest =
      Digest.newBuilder().setHash("file_does_not_exist").setSizeBytes(1).build();
  String nonexistentKey = fileCache.getKey(nonexistentDigest, false);
  Entry entry = new Entry(nonexistentKey, 1, Deadline.after(10, SECONDS));
  entry.before = entry;
  entry.after = entry;
  storage.put(nonexistentKey, entry);
  NoSuchFileException noSuchFileException = null;
  try (InputStream in = fileCache.newInput(nonexistentDigest, 0)) {
    fail("should not get here");
  } catch (NoSuchFileException e) {
    noSuchFileException = e;
  }

  assertThat(noSuchFileException).isNotNull();
  assertThat(storage.containsKey(nonexistentKey)).isFalse();
}
 
Example #3
Source File: ClientCallImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void contextDeadlineShouldNotOverrideSmallerCallOptionsDeadline() {
  Context context = Context.current()
      .withDeadlineAfter(2000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor);
  Context origContext = context.attach();

  CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS);
  ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
      method,
      MoreExecutors.directExecutor(),
      callOpts,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      /* retryEnabled= */ false);
  call.start(callListener, new Metadata());

  context.detach(origContext);

  ArgumentCaptor<Deadline> deadlineCaptor = ArgumentCaptor.forClass(Deadline.class);
  verify(stream).setDeadline(deadlineCaptor.capture());

  assertTimeoutBetween(deadlineCaptor.getValue().timeRemaining(TimeUnit.MILLISECONDS), 600, 1000);
}
 
Example #4
Source File: ClientCallImpl.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static void logIfContextNarrowedTimeout(
    Deadline effectiveDeadline, @Nullable Deadline outerCallDeadline,
    @Nullable Deadline callDeadline) {
  if (!log.isLoggable(Level.FINE) || effectiveDeadline == null
      || !effectiveDeadline.equals(outerCallDeadline)) {
    return;
  }

  long effectiveTimeout = max(0, effectiveDeadline.timeRemaining(TimeUnit.NANOSECONDS));
  StringBuilder builder = new StringBuilder(String.format(
      "Call timeout set to '%d' ns, due to context deadline.", effectiveTimeout));
  if (callDeadline == null) {
    builder.append(" Explicit call timeout was not set.");
  } else {
    long callTimeout = callDeadline.timeRemaining(TimeUnit.NANOSECONDS);
    builder.append(String.format(" Explicit call timeout was '%d' ns.", callTimeout));
  }

  log.fine(builder.toString());
}
 
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: GrpclbFallbackTestClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private GrpclbRouteType doRpcAndGetPath(Deadline deadline) {
  logger.info("doRpcAndGetPath deadline: " + deadline);
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setFillGrpclbRouteType(true)
      .build();
  GrpclbRouteType result = GrpclbRouteType.GRPCLB_ROUTE_TYPE_UNKNOWN;
  try {
    SimpleResponse response = blockingStub
        .withDeadline(deadline)
        .unaryCall(request);
    result = response.getGrpclbRouteType();
  } catch (StatusRuntimeException ex) {
    logger.warning("doRpcAndGetPath failed. Status: " + ex);
    return GrpclbRouteType.GRPCLB_ROUTE_TYPE_UNKNOWN;
  }
  logger.info("doRpcAndGetPath. GrpclbRouteType result: " + result);
  if (result != GrpclbRouteType.GRPCLB_ROUTE_TYPE_FALLBACK
      && result != GrpclbRouteType.GRPCLB_ROUTE_TYPE_BACKEND) {
    throw new AssertionError("Received invalid LB route type. This suggests "
        + "that the server hasn't implemented this test correctly.");
  }
  return result;
}
 
Example #7
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 #8
Source File: ClientCallImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static void logIfContextNarrowedTimeout(
    Deadline effectiveDeadline, @Nullable Deadline outerCallDeadline,
    @Nullable Deadline callDeadline) {
  if (!log.isLoggable(Level.FINE) || effectiveDeadline == null
      || outerCallDeadline != effectiveDeadline) {
    return;
  }

  long effectiveTimeout = max(0, effectiveDeadline.timeRemaining(TimeUnit.NANOSECONDS));
  StringBuilder builder = new StringBuilder(String.format(
      "Call timeout set to '%d' ns, due to context deadline.", effectiveTimeout));
  if (callDeadline == null) {
    builder.append(" Explicit call timeout was not set.");
  } else {
    long callTimeout = callDeadline.timeRemaining(TimeUnit.NANOSECONDS);
    builder.append(String.format(" Explicit call timeout was '%d' ns.", callTimeout));
  }

  log.fine(builder.toString());
}
 
Example #9
Source File: DeadlineSubject.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares for a check that the subject is deadline within the given tolerance of an
 * expected value that will be provided in the next call in the fluent chain.
 */
@CheckReturnValue
public TolerantDeadlineComparison isWithin(final long delta, final TimeUnit timeUnit) {
  return new TolerantDeadlineComparison() {
    @Override
    public void of(Deadline expected) {
      Deadline actual = actual();
      checkNotNull(actual, "actual value cannot be null. expected=%s", expected);

      // This is probably overkill, but easier than thinking about overflow.
      BigInteger actualTimeRemaining = BigInteger.valueOf(actual.timeRemaining(NANOSECONDS));
      BigInteger expectedTimeRemaining = BigInteger.valueOf(expected.timeRemaining(NANOSECONDS));
      BigInteger deltaNanos = BigInteger.valueOf(timeUnit.toNanos(delta));
      if (actualTimeRemaining.subtract(expectedTimeRemaining).abs().compareTo(deltaNanos) > 0) {
        failWithoutActual(
            simpleFact(
                lenientFormat(
                    "%s and <%s> should have been within <%sns> of each other",
                    actualAsString(), expected, deltaNanos)));
      }
    }
  };
}
 
Example #10
Source File: ServerImpl.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private Context.CancellableContext createContext(
    Metadata headers, StatsTraceContext statsTraceCtx) {
  Long timeoutNanos = headers.get(TIMEOUT_KEY);

  Context baseContext =
      statsTraceCtx
          .serverFilterContext(rootContext)
          .withValue(io.grpc.InternalServer.SERVER_CONTEXT_KEY, ServerImpl.this);

  if (timeoutNanos == null) {
    return baseContext.withCancellation();
  }

  Context.CancellableContext context =
      baseContext.withDeadline(
          Deadline.after(timeoutNanos, NANOSECONDS, ticker),
          transport.getScheduledExecutorService());

  return context;
}
 
Example #11
Source File: AbstractClientStreamTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void deadlineTimeoutPopulatedToHeaders() {
  AbstractClientStream.Sink sink = mock(AbstractClientStream.Sink.class);
  ClientStream stream = new BaseAbstractClientStream(
      allocator, new BaseTransportState(statsTraceCtx, transportTracer), sink, statsTraceCtx,
      transportTracer);

  stream.setDeadline(Deadline.after(1, TimeUnit.SECONDS));
  stream.start(mockListener);

  ArgumentCaptor<Metadata> headersCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(sink).writeHeaders(headersCaptor.capture(), ArgumentMatchers.<byte[]>any());

  Metadata headers = headersCaptor.getValue();
  assertTrue(headers.containsKey(GrpcUtil.TIMEOUT_KEY));
  assertThat(headers.get(GrpcUtil.TIMEOUT_KEY).longValue())
      .isLessThan(TimeUnit.SECONDS.toNanos(1));
  assertThat(headers.get(GrpcUtil.TIMEOUT_KEY).longValue())
      .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(600));
}
 
Example #12
Source File: ClientCallImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void streamCancelAbortsDeadlineTimer() {
  fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);

  ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)),
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      /* retryEnabled= */ false);
  call.start(callListener, new Metadata());
  call.cancel("canceled", null);

  // Run the deadline timer, which should have been cancelled by the previous call to cancel()
  fakeClock.forwardNanos(TimeUnit.SECONDS.toNanos(1) + 1);

  verify(stream, times(1)).cancel(statusCaptor.capture());

  assertEquals(Status.CANCELLED.getCode(), statusCaptor.getValue().getCode());
}
 
Example #13
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 #14
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void contextDeadlineShouldOverrideLargerCallOptionsDeadline() {
  Context context = Context.current()
      .withDeadlineAfter(1000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor);
  Context origContext = context.attach();

  CallOptions callOpts = baseCallOptions.withDeadlineAfter(2000, TimeUnit.MILLISECONDS);
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      callOpts,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);
  call.start(callListener, new Metadata());

  context.detach(origContext);

  ArgumentCaptor<Deadline> deadlineCaptor = ArgumentCaptor.forClass(Deadline.class);
  verify(stream).setDeadline(deadlineCaptor.capture());

  assertTimeoutBetween(deadlineCaptor.getValue().timeRemaining(TimeUnit.MILLISECONDS), 600, 1000);
}
 
Example #15
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void contextDeadlineShouldNotOverrideSmallerCallOptionsDeadline() {
  Context context = Context.current()
      .withDeadlineAfter(2000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor);
  Context origContext = context.attach();

  CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS);
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      callOpts,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);
  call.start(callListener, new Metadata());

  context.detach(origContext);

  ArgumentCaptor<Deadline> deadlineCaptor = ArgumentCaptor.forClass(Deadline.class);
  verify(stream).setDeadline(deadlineCaptor.capture());

  assertTimeoutBetween(deadlineCaptor.getValue().timeRemaining(TimeUnit.MILLISECONDS), 600, 1000);
}
 
Example #16
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void callOptionsDeadlineShouldBePropagatedToStream() {
  CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS);
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      callOpts,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);
  call.start(callListener, new Metadata());

  ArgumentCaptor<Deadline> deadlineCaptor = ArgumentCaptor.forClass(Deadline.class);
  verify(stream).setDeadline(deadlineCaptor.capture());

  assertTimeoutBetween(deadlineCaptor.getValue().timeRemaining(TimeUnit.MILLISECONDS), 600, 1000);
}
 
Example #17
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void expiredDeadlineCancelsStream_CallOptions() {
  fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);
  // The deadline needs to be a number large enough to get encompass the call to start, otherwise
  // the scheduled cancellation won't be created, and the call will fail early.
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)),
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);

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

  fakeClock.forwardNanos(TimeUnit.SECONDS.toNanos(1) + 1);

  verify(stream, times(1)).cancel(statusCaptor.capture());
  assertEquals(Status.Code.DEADLINE_EXCEEDED, statusCaptor.getValue().getCode());
}
 
Example #18
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void streamCancelAbortsDeadlineTimer() {
  fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);

  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)),
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);
  call.start(callListener, new Metadata());
  call.cancel("canceled", null);

  // Run the deadline timer, which should have been cancelled by the previous call to cancel()
  fakeClock.forwardNanos(TimeUnit.SECONDS.toNanos(1) + 1);

  verify(stream, times(1)).cancel(statusCaptor.capture());

  assertEquals(Status.CANCELLED.getCode(), statusCaptor.getValue().getCode());
}
 
Example #19
Source File: AbstractClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void deadlineTimeoutPopulatedToHeaders() {
  AbstractClientStream.Sink sink = mock(AbstractClientStream.Sink.class);
  ClientStream stream = new BaseAbstractClientStream(
      allocator, new BaseTransportState(statsTraceCtx, transportTracer), sink, statsTraceCtx,
      transportTracer);

  stream.setDeadline(Deadline.after(1, TimeUnit.SECONDS));
  stream.start(mockListener);

  ArgumentCaptor<Metadata> headersCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(sink).writeHeaders(headersCaptor.capture(), any(byte[].class));

  Metadata headers = headersCaptor.getValue();
  assertTrue(headers.containsKey(GrpcUtil.TIMEOUT_KEY));
  assertThat(headers.get(GrpcUtil.TIMEOUT_KEY).longValue())
      .isLessThan(TimeUnit.SECONDS.toNanos(1));
  assertThat(headers.get(GrpcUtil.TIMEOUT_KEY).longValue())
      .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(600));
}
 
Example #20
Source File: ClientCallImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void contextDeadlineShouldOverrideLargerCallOptionsDeadline() {
  Context context = Context.current()
      .withDeadlineAfter(1000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor);
  Context origContext = context.attach();

  CallOptions callOpts = baseCallOptions.withDeadlineAfter(2000, TimeUnit.MILLISECONDS);
  ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
      method,
      MoreExecutors.directExecutor(),
      callOpts,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      /* retryEnabled= */ false);
  call.start(callListener, new Metadata());

  context.detach(origContext);

  ArgumentCaptor<Deadline> deadlineCaptor = ArgumentCaptor.forClass(Deadline.class);
  verify(stream).setDeadline(deadlineCaptor.capture());

  assertTimeoutBetween(deadlineCaptor.getValue().timeRemaining(TimeUnit.MILLISECONDS), 600, 1000);
}
 
Example #21
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 #22
Source File: ShardWorkerContext.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Override
public void resumePoller(
    Poller poller,
    String name,
    QueueEntry queueEntry,
    ExecutionStage.Value stage,
    Runnable onFailure,
    Deadline deadline) {
  String operationName = queueEntry.getExecuteEntry().getOperationName();
  poller.resume(
      () -> {
        boolean success = false;
        try {
          success =
              operationPoller.poll(queueEntry, stage, System.currentTimeMillis() + 30 * 1000);
        } catch (IOException e) {
          logger.log(
              Level.SEVERE, format("%s: poller: error while polling %s", name, operationName), e);
        }

        logger.log(
            Level.INFO,
            format(
                "%s: poller: Completed Poll for %s: %s",
                name, operationName, success ? "OK" : "Failed"));
        if (!success) {
          onFailure.run();
        }
        return success;
      },
      () -> {
        logger.log(
            Level.INFO, format("%s: poller: Deadline expired for %s", name, operationName));
        onFailure.run();
      },
      deadline);
}
 
Example #23
Source File: ReportResultStage.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Override
protected OperationContext tick(OperationContext operationContext) throws InterruptedException {
  workerContext.resumePoller(
      operationContext.poller,
      "ReportResultStage",
      operationContext.queueEntry,
      EXECUTING,
      this::cancelTick,
      Deadline.after(60, SECONDS));
  try {
    return reportPolled(operationContext);
  } finally {
    operationContext.poller.pause();
  }
}
 
Example #24
Source File: Poller.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private Duration getWaitTime() {
  checkNotNull(periodDeadline);
  Deadline waitDeadline = expirationDeadline.minimum(periodDeadline);
  long waitMicros = waitDeadline.timeRemaining(MICROSECONDS);
  if (waitMicros <= 0) {
    return Duration.getDefaultInstance();
  }
  return Durations.fromMicros(waitMicros);
}
 
Example #25
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 #26
Source File: FluxMethodBridge.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private FluxInvocation(FluxSink<Object> sink, Object[] args) {
    StreamObserver<Object> grpcStreamObserver = new ClientResponseObserver<Object, Object>() {
        @Override
        public void beforeStart(ClientCallStreamObserver requestStream) {
            sink.onCancel(() -> requestStream.cancel("React subscription cancelled", null));
        }

        @Override
        public void onNext(Object value) {
            sink.next(value);
        }

        @Override
        public void onError(Throwable error) {
            sink.error(error);
        }

        @Override
        public void onCompleted() {
            sink.complete();
        }
    };

    Object[] grpcArgs = new Object[]{
            grpcArgPos < 0 ? Empty.getDefaultInstance() : args[grpcArgPos],
            grpcStreamObserver
    };

    GRPC_STUB invocationStub = handleCallMetadata(args)
            .withDeadline(Deadline.after(timeout.toMillis(), TimeUnit.MILLISECONDS));

    try {
        grpcMethod.invoke(invocationStub, grpcArgs);
    } catch (Exception e) {
        sink.error(e);
    }
}
 
Example #27
Source File: ClientCallImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void expiredDeadlineCancelsStream_CallOptions() {
  fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);
  // The deadline needs to be a number large enough to get encompass the call to start, otherwise
  // the scheduled cancellation won't be created, and the call will fail early.
  ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions.withDeadline(
          Deadline.after(1, TimeUnit.SECONDS, fakeClock.getDeadlineTicker())),
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      /* retryEnabled= */ false);

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

  fakeClock.forwardTime(1000, TimeUnit.MILLISECONDS);

  // Verify cancel sent to application when deadline just past
  verify(callListener).onClose(statusCaptor.capture(), metadataArgumentCaptor.capture());
  assertThat(statusCaptor.getValue().getDescription())
      .matches("deadline exceeded after [0-9]+\\.[0-9]+s. \\[remote_addr=127\\.0\\.0\\.1:443\\]");
  assertThat(statusCaptor.getValue().getCode()).isEqualTo(Code.DEADLINE_EXCEEDED);
  verify(stream, never()).cancel(statusCaptor.capture());

  fakeClock.forwardNanos(DEADLINE_EXPIRATION_CANCEL_DELAY_NANOS - 1);
  verify(stream, never()).cancel(any(Status.class));

  // verify cancel send to server is delayed with DEADLINE_EXPIRATION_CANCEL_DELAY
  fakeClock.forwardNanos(1);
  verify(stream).cancel(statusCaptor.capture());
  assertEquals(Status.Code.DEADLINE_EXCEEDED, statusCaptor.getValue().getCode());
  assertThat(statusCaptor.getValue().getDescription())
      .matches("deadline exceeded after [0-9]+\\.[0-9]+s. \\[remote_addr=127\\.0\\.0\\.1:443\\]");
}
 
Example #28
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 #29
Source File: LockTest.java    From etcd-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithSessionLease() throws Exception {
    LockResponse lr = lockClient.lock(KeyUtils.bs("mylock"))
            .deadline(Deadline.after(500, TimeUnit.MILLISECONDS)).sync();

    ByteString lockKey = lr.getKey();
    assertNotNull(lockKey);
    assertTrue(kvClient.txnIf().exists(lockKey).sync().getSucceeded());

    assertNotNull(lockClient.unlock(lockKey).sync());
    assertFalse(kvClient.txnIf().exists(lockKey).sync().getSucceeded());
}
 
Example #30
Source File: InputFetcher.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private long runInterruptibly(Stopwatch stopwatch) throws InterruptedException {
  final Thread fetcherThread = Thread.currentThread();
  workerContext.resumePoller(
      operationContext.poller,
      "InputFetcher",
      operationContext.queueEntry,
      QUEUED,
      () -> fetcherThread.interrupt(),
      Deadline.after(60, SECONDS));
  try {
    return fetchPolled(stopwatch);
  } finally {
    operationContext.poller.pause();
  }
}