diff --git a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/ChannelPool.java b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/ChannelPool.java index c3e26dc4e2..12f226d2b6 100644 --- a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/ChannelPool.java +++ b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/ChannelPool.java @@ -55,7 +55,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * A {@link ManagedChannel} that will send requests round-robin via a set of channels. @@ -69,7 +68,7 @@ */ class ChannelPool extends ManagedChannel { @VisibleForTesting static final Logger LOG = Logger.getLogger(ChannelPool.class.getName()); - private static final Duration REFRESH_PERIOD = Duration.ofMinutes(50); + private static final java.time.Duration REFRESH_PERIOD = java.time.Duration.ofMinutes(50); private final ChannelPoolSettings settings; private final ChannelFactory channelFactory; diff --git a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java index 94099dd96b..137060595d 100644 --- a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java +++ b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java @@ -29,8 +29,12 @@ */ package com.google.api.gax.grpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiExceptionFactory; @@ -62,7 +66,6 @@ import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * GrpcCallContext encapsulates context data used to make a grpc call. @@ -84,9 +87,9 @@ public final class GrpcCallContext implements ApiCallContext { private final Channel channel; @Nullable private final Credentials credentials; private final CallOptions callOptions; - @Nullable private final Duration timeout; - @Nullable private final Duration streamWaitTimeout; - @Nullable private final Duration streamIdleTimeout; + @Nullable private final java.time.Duration timeout; + @Nullable private final java.time.Duration streamWaitTimeout; + @Nullable private final java.time.Duration streamIdleTimeout; @Nullable private final Integer channelAffinity; @Nullable private final RetrySettings retrySettings; @Nullable private final ImmutableSet retryableCodes; @@ -132,9 +135,9 @@ private GrpcCallContext( Channel channel, @Nullable Credentials credentials, CallOptions callOptions, - @Nullable Duration timeout, - @Nullable Duration streamWaitTimeout, - @Nullable Duration streamIdleTimeout, + @Nullable java.time.Duration timeout, + @Nullable java.time.Duration streamWaitTimeout, + @Nullable java.time.Duration streamIdleTimeout, @Nullable Integer channelAffinity, ImmutableMap> extraHeaders, ApiCallContextOptions options, @@ -228,8 +231,15 @@ public GrpcCallContext withEndpointContext(EndpointContext endpointContext) { endpointContext); } + /** This method is obsolete. Use {@link #withTimeoutDuration(java.time.Duration)} instead. */ + @Override + @ObsoleteApi("Use withTimeoutDuration(java.time.Duration) instead") + public GrpcCallContext withTimeout(@Nullable org.threeten.bp.Duration timeout) { + return withTimeoutDuration(toJavaTimeDuration(timeout)); + } + @Override - public GrpcCallContext withTimeout(@Nullable Duration timeout) { + public GrpcCallContext withTimeoutDuration(@Nullable java.time.Duration timeout) { // Default RetrySettings use 0 for RPC timeout. Treat that as disabled timeouts. if (timeout != null && (timeout.isZero() || timeout.isNegative())) { timeout = null; @@ -255,17 +265,37 @@ public GrpcCallContext withTimeout(@Nullable Duration timeout) { endpointContext); } + /** This method is obsolete. Use {@link #getTimeoutDuration()} instead. */ @Nullable @Override - public Duration getTimeout() { + @ObsoleteApi("Use getTimeoutDuration() instead") + public org.threeten.bp.Duration getTimeout() { + return toThreetenDuration(getTimeoutDuration()); + } + + @Nullable + @Override + public java.time.Duration getTimeoutDuration() { return timeout; } + /** + * This method is obsolete. Use {@link #withStreamWaitTimeoutDuration(java.time.Duration)} + * instead. + */ + @Override + @ObsoleteApi("Use withStreamWaitTimeoutDuration(java.time.Duration) instead") + public GrpcCallContext withStreamWaitTimeout( + @Nullable org.threeten.bp.Duration streamWaitTimeout) { + return withStreamWaitTimeoutDuration(toJavaTimeDuration(streamWaitTimeout)); + } + @Override - public GrpcCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeout) { + public GrpcCallContext withStreamWaitTimeoutDuration( + @Nullable java.time.Duration streamWaitTimeout) { if (streamWaitTimeout != null) { Preconditions.checkArgument( - streamWaitTimeout.compareTo(Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); + streamWaitTimeout.compareTo(java.time.Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); } return new GrpcCallContext( @@ -283,11 +313,23 @@ public GrpcCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeou endpointContext); } + /** + * This method is obsolete. Use {@link #withStreamIdleTimeoutDuration(java.time.Duration)} + * instead. + */ + @Override + @ObsoleteApi("Use withStreamIdleTimeoutDuration(java.time.Duration) instead") + public GrpcCallContext withStreamIdleTimeout( + @Nullable org.threeten.bp.Duration streamIdleTimeout) { + return withStreamIdleTimeoutDuration(toJavaTimeDuration(streamIdleTimeout)); + } + @Override - public GrpcCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTimeout) { + public GrpcCallContext withStreamIdleTimeoutDuration( + @Nullable java.time.Duration streamIdleTimeout) { if (streamIdleTimeout != null) { Preconditions.checkArgument( - streamIdleTimeout.compareTo(Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); + streamIdleTimeout.compareTo(java.time.Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); } return new GrpcCallContext( @@ -424,17 +466,17 @@ public ApiCallContext merge(ApiCallContext inputCallContext) { newTracer = callOptions.getOption(TRACER_KEY); } - Duration newTimeout = grpcCallContext.timeout; + java.time.Duration newTimeout = grpcCallContext.timeout; if (newTimeout == null) { newTimeout = timeout; } - Duration newStreamWaitTimeout = grpcCallContext.streamWaitTimeout; + java.time.Duration newStreamWaitTimeout = grpcCallContext.streamWaitTimeout; if (newStreamWaitTimeout == null) { newStreamWaitTimeout = streamWaitTimeout; } - Duration newStreamIdleTimeout = grpcCallContext.streamIdleTimeout; + java.time.Duration newStreamIdleTimeout = grpcCallContext.streamIdleTimeout; if (newStreamIdleTimeout == null) { newStreamIdleTimeout = streamIdleTimeout; } @@ -496,25 +538,40 @@ public CallOptions getCallOptions() { return callOptions; } + /** This method is obsolete. Use {@link #getStreamWaitTimeoutDuration()} instead. */ + @Override + @Nullable + @ObsoleteApi("Use getStreamWaitTimeoutDuration() instead") + public org.threeten.bp.Duration getStreamWaitTimeout() { + return toThreetenDuration(getStreamWaitTimeoutDuration()); + } + /** * The stream wait timeout set for this context. * - * @see ApiCallContext#withStreamWaitTimeout(Duration) + * @see ApiCallContext#withStreamWaitTimeoutDuration(java.time.Duration) */ @Override @Nullable - public Duration getStreamWaitTimeout() { + public java.time.Duration getStreamWaitTimeoutDuration() { return streamWaitTimeout; } + /** This method is obsolete. Use {@link #getStreamIdleTimeoutDuration()} instead. */ + @Override + @Nullable + @ObsoleteApi("Use getStreamIdleTimeoutDuration() instead") + public org.threeten.bp.Duration getStreamIdleTimeout() { + return toThreetenDuration(getStreamIdleTimeoutDuration()); + } /** * The stream idle timeout set for this context. * - * @see ApiCallContext#withStreamIdleTimeout(Duration) + * @see ApiCallContext#withStreamIdleTimeoutDuration(java.time.Duration) */ @Override @Nullable - public Duration getStreamIdleTimeout() { + public java.time.Duration getStreamIdleTimeoutDuration() { return streamIdleTimeout; } diff --git a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcClientCalls.java b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcClientCalls.java index 80e8797f01..9ce896ca35 100644 --- a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcClientCalls.java +++ b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcClientCalls.java @@ -74,9 +74,9 @@ public static ClientCall newCall( Preconditions.checkNotNull(callOptions); // Try to convert the timeout into a deadline and use it if it occurs before the actual deadline - if (grpcContext.getTimeout() != null) { + if (grpcContext.getTimeoutDuration() != null) { Deadline newDeadline = - Deadline.after(grpcContext.getTimeout().toMillis(), TimeUnit.MILLISECONDS); + Deadline.after(grpcContext.getTimeoutDuration().toMillis(), TimeUnit.MILLISECONDS); Deadline oldDeadline = callOptions.getDeadline(); if (oldDeadline == null || newDeadline.isBefore(oldDeadline)) { diff --git a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java index 539e06cd69..91c38d916e 100644 --- a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java +++ b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java @@ -29,9 +29,13 @@ */ package com.google.api.gax.grpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.ExecutorProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; @@ -67,7 +71,6 @@ import java.util.logging.Logger; import javax.annotation.Nullable; import javax.net.ssl.KeyManagerFactory; -import org.threeten.bp.Duration; /** * InstantiatingGrpcChannelProvider is a TransportChannelProvider which constructs a gRPC @@ -106,8 +109,8 @@ public final class InstantiatingGrpcChannelProvider implements TransportChannelP @Nullable private final GrpcInterceptorProvider interceptorProvider; @Nullable private final Integer maxInboundMessageSize; @Nullable private final Integer maxInboundMetadataSize; - @Nullable private final Duration keepAliveTime; - @Nullable private final Duration keepAliveTimeout; + @Nullable private final java.time.Duration keepAliveTime; + @Nullable private final java.time.Duration keepAliveTimeout; @Nullable private final Boolean keepAliveWithoutCalls; private final ChannelPoolSettings channelPoolSettings; @Nullable private final Credentials credentials; @@ -490,13 +493,25 @@ public String getEndpoint() { return endpoint; } + /** This method is obsolete. Use {@link #getKeepAliveTimeDuration()} instead. */ + @ObsoleteApi("Use getKeepAliveTimeDuration() instead") + public org.threeten.bp.Duration getKeepAliveTime() { + return toThreetenDuration(getKeepAliveTimeDuration()); + } + /** The time without read activity before sending a keepalive ping. */ - public Duration getKeepAliveTime() { + public java.time.Duration getKeepAliveTimeDuration() { return keepAliveTime; } + /** This method is obsolete. Use {@link #getKeepAliveTimeoutDuration()} instead */ + @ObsoleteApi("Use getKeepAliveTimeoutDuration() instead") + public org.threeten.bp.Duration getKeepAliveTimeout() { + return toThreetenDuration(getKeepAliveTimeoutDuration()); + } + /** The time without read activity after sending a keepalive ping. */ - public Duration getKeepAliveTimeout() { + public java.time.Duration getKeepAliveTimeoutDuration() { return keepAliveTimeout; } @@ -540,8 +555,8 @@ public static final class Builder { @Nullable private GrpcInterceptorProvider interceptorProvider; @Nullable private Integer maxInboundMessageSize; @Nullable private Integer maxInboundMetadataSize; - @Nullable private Duration keepAliveTime; - @Nullable private Duration keepAliveTimeout; + @Nullable private java.time.Duration keepAliveTime; + @Nullable private java.time.Duration keepAliveTimeout; @Nullable private Boolean keepAliveWithoutCalls; @Nullable private ApiFunction channelConfigurator; @Nullable private Credentials credentials; @@ -679,25 +694,53 @@ public Integer getMaxInboundMetadataSize() { return maxInboundMetadataSize; } + /** + * This method is obsolete. Use {@link #setKeepAliveTimeDuration(java.time.Duration)} instead. + */ + @ObsoleteApi("Use setKeepAliveTimeDuration(java.time.Duration) instead") + public Builder setKeepAliveTime(org.threeten.bp.Duration duration) { + return setKeepAliveTimeDuration(toJavaTimeDuration(duration)); + } /** The time without read activity before sending a keepalive ping. */ - public Builder setKeepAliveTime(Duration duration) { + public Builder setKeepAliveTimeDuration(java.time.Duration duration) { this.keepAliveTime = duration; return this; } + /** This method is obsolete. Use {@link #getKeepAliveTimeDuration()} instead. */ + @ObsoleteApi("Use getKeepAliveTimeDuration() instead") + public org.threeten.bp.Duration getKeepAliveTime() { + return toThreetenDuration(getKeepAliveTimeDuration()); + } + /** The time without read activity before sending a keepalive ping. */ - public Duration getKeepAliveTime() { + public java.time.Duration getKeepAliveTimeDuration() { return keepAliveTime; } + /** + * This method is obsolete. Use {@link #setKeepAliveTimeoutDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use setKeepAliveTimeoutDuration(java.time.Duration) instead") + public Builder setKeepAliveTimeout(org.threeten.bp.Duration duration) { + return setKeepAliveTimeoutDuration(toJavaTimeDuration(duration)); + } + /** The time without read activity after sending a keepalive ping. */ - public Builder setKeepAliveTimeout(Duration duration) { + public Builder setKeepAliveTimeoutDuration(java.time.Duration duration) { this.keepAliveTimeout = duration; return this; } + /** This method is obsolete. Use {@link #getKeepAliveTimeoutDuration()} instead */ + @ObsoleteApi("Use getKeepAliveTimeoutDuration() instead") + public org.threeten.bp.Duration getKeepAliveTimeout() { + return toThreetenDuration(getKeepAliveTimeoutDuration()); + } + /** The time without read activity after sending a keepalive ping. */ - public Duration getKeepAliveTimeout() { + public java.time.Duration getKeepAliveTimeoutDuration() { return keepAliveTimeout; } diff --git a/gax-java/gax-grpc/src/main/java/com/google/longrunning/stub/OperationsStubSettings.java b/gax-java/gax-grpc/src/main/java/com/google/longrunning/stub/OperationsStubSettings.java index 85da6db5c1..47c3a981b8 100644 --- a/gax-java/gax-grpc/src/main/java/com/google/longrunning/stub/OperationsStubSettings.java +++ b/gax-java/gax-grpc/src/main/java/com/google/longrunning/stub/OperationsStubSettings.java @@ -63,7 +63,6 @@ import com.google.longrunning.WaitOperationRequest; import com.google.protobuf.Empty; import java.io.IOException; -import org.threeten.bp.Duration; /** Settings class to configure an instance of {@link OperationsStub}. */ public class OperationsStubSettings extends StubSettings { @@ -243,13 +242,13 @@ public static class Builder extends StubSettings.Builder context.withTimeoutDuration(jt), + tt -> context.withTimeout(tt), + c -> c.getTimeoutDuration(), + c -> c.getTimeout()); } @Test void testWithNegativeTimeout() { - assertNull(GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(-1L)).getTimeout()); + assertNull( + GrpcCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(-1L)) + .getTimeoutDuration()); } @Test void testWithZeroTimeout() { - assertNull(GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(0L)).getTimeout()); + assertNull( + GrpcCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(0L)) + .getTimeoutDuration()); } @Test void testWithShorterTimeout() { GrpcCallContext ctxWithLongTimeout = - GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(10)); + GrpcCallContext.createDefault().withTimeoutDuration(java.time.Duration.ofSeconds(10)); // Sanity check - Truth.assertThat(ctxWithLongTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(10)); + Truth.assertThat(ctxWithLongTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(10)); // Shorten the timeout and make sure it changed - GrpcCallContext ctxWithShorterTimeout = ctxWithLongTimeout.withTimeout(Duration.ofSeconds(5)); - Truth.assertThat(ctxWithShorterTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(5)); + GrpcCallContext ctxWithShorterTimeout = + ctxWithLongTimeout.withTimeoutDuration(java.time.Duration.ofSeconds(5)); + Truth.assertThat(ctxWithShorterTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(5)); } @Test void testWithLongerTimeout() { GrpcCallContext ctxWithShortTimeout = - GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(5)); + GrpcCallContext.createDefault().withTimeoutDuration(java.time.Duration.ofSeconds(5)); // Sanity check - Truth.assertThat(ctxWithShortTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(5)); + Truth.assertThat(ctxWithShortTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(5)); // Try to extend the timeout and verify that it was ignored GrpcCallContext ctxWithUnchangedTimeout = - ctxWithShortTimeout.withTimeout(Duration.ofSeconds(10)); - Truth.assertThat(ctxWithUnchangedTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(5)); + ctxWithShortTimeout.withTimeoutDuration(java.time.Duration.ofSeconds(10)); + Truth.assertThat(ctxWithUnchangedTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(5)); } @Test void testMergeWithNullTimeout() { - Duration timeout = Duration.ofSeconds(10); - GrpcCallContext baseContext = GrpcCallContext.createDefault().withTimeout(timeout); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); + GrpcCallContext baseContext = GrpcCallContext.createDefault().withTimeoutDuration(timeout); GrpcCallContext defaultOverlay = GrpcCallContext.createDefault(); - Truth.assertThat(baseContext.merge(defaultOverlay).getTimeout()).isEqualTo(timeout); + Truth.assertThat(baseContext.merge(defaultOverlay).getTimeoutDuration()).isEqualTo(timeout); - GrpcCallContext explicitNullOverlay = GrpcCallContext.createDefault().withTimeout(null); - Truth.assertThat(baseContext.merge(explicitNullOverlay).getTimeout()).isEqualTo(timeout); + java.time.Duration callContextTimeout = null; + GrpcCallContext explicitNullOverlay = + GrpcCallContext.createDefault().withTimeoutDuration(callContextTimeout); + Truth.assertThat(baseContext.merge(explicitNullOverlay).getTimeoutDuration()) + .isEqualTo(timeout); } @Test void testMergeWithTimeout() { - Duration timeout = Duration.ofSeconds(19); + java.time.Duration timeout = java.time.Duration.ofSeconds(19); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); - GrpcCallContext ctx2 = GrpcCallContext.createDefault().withTimeout(timeout); + GrpcCallContext ctx2 = GrpcCallContext.createDefault().withTimeoutDuration(timeout); - Truth.assertThat(ctx1.merge(ctx2).getTimeout()).isEqualTo(timeout); + Truth.assertThat(ctx1.merge(ctx2).getTimeoutDuration()).isEqualTo(timeout); } @Test void testWithStreamingWaitTimeout() { - Duration timeout = Duration.ofSeconds(15); - GrpcCallContext context = GrpcCallContext.createDefault().withStreamWaitTimeout(timeout); - Truth.assertThat(context.getStreamWaitTimeout()).isEqualTo(timeout); + final long millis = 15; + GrpcCallContext context = GrpcCallContext.createDefault(); + testDurationMethod( + millis, + jt -> context.withStreamWaitTimeoutDuration(jt), + tt -> context.withStreamWaitTimeout(tt), + c -> c.getStreamWaitTimeoutDuration(), + c -> c.getStreamWaitTimeout()); } @Test void testMergeWithNullStreamingWaitTimeout() { - Duration timeout = Duration.ofSeconds(10); - GrpcCallContext baseContext = GrpcCallContext.createDefault().withStreamWaitTimeout(timeout); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); + GrpcCallContext baseContext = + GrpcCallContext.createDefault().withStreamWaitTimeoutDuration(timeout); GrpcCallContext defaultOverlay = GrpcCallContext.createDefault(); - Truth.assertThat(baseContext.merge(defaultOverlay).getStreamWaitTimeout()).isEqualTo(timeout); + Truth.assertThat(baseContext.merge(defaultOverlay).getStreamWaitTimeoutDuration()) + .isEqualTo(timeout); + java.time.Duration streamWaitTimeout = null; GrpcCallContext explicitNullOverlay = - GrpcCallContext.createDefault().withStreamWaitTimeout(null); - Truth.assertThat(baseContext.merge(explicitNullOverlay).getStreamWaitTimeout()) + GrpcCallContext.createDefault().withStreamWaitTimeoutDuration(streamWaitTimeout); + Truth.assertThat(baseContext.merge(explicitNullOverlay).getStreamWaitTimeoutDuration()) .isEqualTo(timeout); } @Test void testWithZeroStreamingWaitTimeout() { - Duration timeout = Duration.ZERO; + java.time.Duration timeout = java.time.Duration.ZERO; Truth.assertThat( - GrpcCallContext.createDefault().withStreamWaitTimeout(timeout).getStreamWaitTimeout()) + GrpcCallContext.createDefault() + .withStreamWaitTimeoutDuration(timeout) + .getStreamWaitTimeoutDuration()) .isEqualTo(timeout); } @Test void testMergeWithStreamingWaitTimeout() { - Duration timeout = Duration.ofSeconds(19); + java.time.Duration timeout = java.time.Duration.ofSeconds(19); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); - GrpcCallContext ctx2 = GrpcCallContext.createDefault().withStreamWaitTimeout(timeout); + GrpcCallContext ctx2 = GrpcCallContext.createDefault().withStreamWaitTimeoutDuration(timeout); - Truth.assertThat(ctx1.merge(ctx2).getStreamWaitTimeout()).isEqualTo(timeout); + Truth.assertThat(ctx1.merge(ctx2).getStreamWaitTimeoutDuration()).isEqualTo(timeout); } @Test void testWithStreamingIdleTimeout() { - Duration timeout = Duration.ofSeconds(15); - GrpcCallContext context = GrpcCallContext.createDefault().withStreamIdleTimeout(timeout); - Truth.assertThat(context.getStreamIdleTimeout()).isEqualTo(timeout); + final long millis = 15; + GrpcCallContext context = GrpcCallContext.createDefault(); + testDurationMethod( + millis, + jt -> context.withStreamIdleTimeoutDuration(jt), + tt -> context.withStreamIdleTimeout(tt), + c -> c.getStreamIdleTimeoutDuration(), + c -> c.getStreamIdleTimeout()); } @Test void testMergeWithNullStreamingIdleTimeout() { - Duration timeout = Duration.ofSeconds(10); - GrpcCallContext baseContext = GrpcCallContext.createDefault().withStreamIdleTimeout(timeout); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); + GrpcCallContext baseContext = + GrpcCallContext.createDefault().withStreamIdleTimeoutDuration(timeout); GrpcCallContext defaultOverlay = GrpcCallContext.createDefault(); - Truth.assertThat(baseContext.merge(defaultOverlay).getStreamIdleTimeout()).isEqualTo(timeout); + Truth.assertThat(baseContext.merge(defaultOverlay).getStreamIdleTimeoutDuration()) + .isEqualTo(timeout); + java.time.Duration idleTimeout = null; GrpcCallContext explicitNullOverlay = - GrpcCallContext.createDefault().withStreamIdleTimeout(null); - Truth.assertThat(baseContext.merge(explicitNullOverlay).getStreamIdleTimeout()) + GrpcCallContext.createDefault().withStreamIdleTimeoutDuration(idleTimeout); + Truth.assertThat(baseContext.merge(explicitNullOverlay).getStreamIdleTimeoutDuration()) .isEqualTo(timeout); } @Test void testWithZeroStreamingIdleTimeout() { - Duration timeout = Duration.ZERO; + java.time.Duration timeout = java.time.Duration.ZERO; Truth.assertThat( - GrpcCallContext.createDefault().withStreamIdleTimeout(timeout).getStreamIdleTimeout()) + GrpcCallContext.createDefault() + .withStreamIdleTimeoutDuration(timeout) + .getStreamIdleTimeoutDuration()) .isEqualTo(timeout); } @Test void testMergeWithStreamingIdleTimeout() { - Duration timeout = Duration.ofSeconds(19); + java.time.Duration timeout = java.time.Duration.ofSeconds(19); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); - GrpcCallContext ctx2 = GrpcCallContext.createDefault().withStreamIdleTimeout(timeout); + GrpcCallContext ctx2 = GrpcCallContext.createDefault().withStreamIdleTimeoutDuration(timeout); - Truth.assertThat(ctx1.merge(ctx2).getStreamIdleTimeout()).isEqualTo(timeout); + Truth.assertThat(ctx1.merge(ctx2).getStreamIdleTimeoutDuration()).isEqualTo(timeout); } @Test diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java index a24e777774..ea2103378e 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java @@ -59,7 +59,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class GrpcCallableFactoryTest { private InProcessServer inprocessServer; @@ -103,7 +102,7 @@ void createServerStreamingCallableRetryableExceptions() { ServerStreamingCallSettings.newBuilder() .setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofSeconds(1)) + .setTotalTimeoutDuration(java.time.Duration.ofSeconds(1)) .setMaxAttempts(1) .build()) .build(); @@ -128,7 +127,7 @@ void createServerStreamingCallableRetryableExceptions() { .setRetryableCodes(Code.INVALID_ARGUMENT) .setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofSeconds(1)) + .setTotalTimeoutDuration(java.time.Duration.ofSeconds(1)) .setMaxAttempts(1) .build()) .build(); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java index a22b5fa747..5bcd098255 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java @@ -62,7 +62,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; class GrpcClientCallsTest { @@ -195,10 +194,11 @@ void testTimeoutToDeadlineConversion() throws IOException { Mockito.when(mockChannel.newCall(Mockito.eq(descriptor), capturedCallOptions.capture())) .thenReturn(mockClientCall); - Duration timeout = Duration.ofSeconds(10); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); Deadline minExpectedDeadline = Deadline.after(timeout.getSeconds(), TimeUnit.SECONDS); - GrpcCallContext context = defaultCallContext.withChannel(mockChannel).withTimeout(timeout); + GrpcCallContext context = + defaultCallContext.withChannel(mockChannel).withTimeoutDuration(timeout); GrpcClientCalls.newCall(descriptor, context).start(mockListener, new Metadata()); @@ -227,13 +227,13 @@ void testTimeoutAfterDeadline() throws IOException { // Configure a timeout that occurs after the grpc deadline Deadline priorDeadline = Deadline.after(5, TimeUnit.SECONDS); - Duration timeout = Duration.ofSeconds(10); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); GrpcCallContext context = defaultCallContext .withChannel(mockChannel) .withCallOptions(CallOptions.DEFAULT.withDeadline(priorDeadline)) - .withTimeout(timeout); + .withTimeoutDuration(timeout); GrpcClientCalls.newCall(descriptor, context).start(mockListener, new Metadata()); @@ -259,7 +259,7 @@ void testTimeoutBeforeDeadline() throws IOException { .thenReturn(mockClientCall); // Configure a timeout that occurs before the grpc deadline - Duration timeout = Duration.ofSeconds(5); + java.time.Duration timeout = java.time.Duration.ofSeconds(5); Deadline subsequentDeadline = Deadline.after(10, TimeUnit.SECONDS); Deadline minExpectedDeadline = Deadline.after(timeout.getSeconds(), TimeUnit.SECONDS); @@ -267,7 +267,7 @@ void testTimeoutBeforeDeadline() throws IOException { defaultCallContext .withChannel(mockChannel) .withCallOptions(CallOptions.DEFAULT.withDeadline(subsequentDeadline)) - .withTimeout(timeout); + .withTimeoutDuration(timeout); GrpcClientCalls.newCall(descriptor, context).start(mockListener, new Metadata()); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java index 64d908de28..2359dc5d28 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java @@ -56,7 +56,6 @@ import javax.annotation.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import org.threeten.bp.Duration; class GrpcDirectStreamControllerTest { private static final int DEFAULT_AWAIT_TERMINATION_SEC = 10; @@ -100,11 +99,11 @@ public boolean canResume() { .setRetryableCodes(StatusCode.Code.DEADLINE_EXCEEDED) .setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofMinutes(1)) - .setInitialRpcTimeout(Duration.ofMillis(1)) - .setMaxRpcTimeout(Duration.ofMillis(1)) - .setInitialRetryDelay(Duration.ofMillis(1)) - .setMaxRetryDelay(Duration.ofMillis(1)) + .setTotalTimeoutDuration(java.time.Duration.ofMinutes(1)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(1)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1)) .build()) .build(); // Store a list of resources to manually close at the end of the test diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java index ad45b53a21..241f90b08a 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java @@ -69,21 +69,20 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class GrpcLongRunningTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(1L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(1L)) - .setInitialRpcTimeout(Duration.ofMillis(1L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(1L)) .setMaxAttempts(0) .setJittered(false) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(1L)) - .setTotalTimeout(Duration.ofMillis(5L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(1L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(5L)) .build(); private ManagedChannel channel; diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java index d982ec98c3..01bcf40243 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java @@ -30,6 +30,7 @@ package com.google.api.gax.grpc; import static com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.GCE_PRODUCTION_NAME_AFTER_2016; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -54,6 +55,7 @@ import io.grpc.alts.ComputeEngineChannelBuilder; import java.io.IOException; import java.security.GeneralSecurityException; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -63,6 +65,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.stream.Collectors; @@ -73,7 +76,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; class InstantiatingGrpcChannelProviderTest extends AbstractMtlsTransportChannelTest { private static final String DEFAULT_ENDPOINT = "test.googleapis.com:443"; @@ -124,20 +126,45 @@ void testEndpointBadPort() { @Test void testKeepAlive() { - Duration keepaliveTime = Duration.ofSeconds(1); - Duration keepaliveTimeout = Duration.ofSeconds(2); - boolean keepaliveWithoutCalls = true; - - InstantiatingGrpcChannelProvider provider = - InstantiatingGrpcChannelProvider.newBuilder() - .setKeepAliveTime(keepaliveTime) - .setKeepAliveTimeout(keepaliveTimeout) - .setKeepAliveWithoutCalls(keepaliveWithoutCalls) - .build(); - - assertEquals(provider.getKeepAliveTime(), keepaliveTime); - assertEquals(provider.getKeepAliveTimeout(), keepaliveTimeout); - assertEquals(provider.getKeepAliveWithoutCalls(), keepaliveWithoutCalls); + final long millis = 15; + InstantiatingGrpcChannelProvider.Builder builder = + InstantiatingGrpcChannelProvider.newBuilder(); + Function javaTimeProviderSupplier = + jt -> + builder + .setKeepAliveTimeDuration(jt) + .setKeepAliveTimeoutDuration(jt) + .setKeepAliveWithoutCalls(Boolean.TRUE) + .build(); + Function threetenProviderSupplier = + tt -> + builder + .setKeepAliveTime(tt) + .setKeepAliveTimeout(tt) + .setKeepAliveWithoutCalls(Boolean.TRUE) + .build(); + testDurationMethod( + millis, + javaTimeProviderSupplier, + threetenProviderSupplier, + c -> c.getKeepAliveTimeDuration(), + c -> c.getKeepAliveTime()); + testDurationMethod( + millis, + javaTimeProviderSupplier, + threetenProviderSupplier, + c -> c.getKeepAliveTimeoutDuration(), + c -> c.getKeepAliveTimeout()); + assertEquals( + Boolean.TRUE, + javaTimeProviderSupplier + .apply(java.time.Duration.ofMillis(millis)) + .getKeepAliveWithoutCalls()); + assertEquals( + Boolean.TRUE, + threetenProviderSupplier + .apply(org.threeten.bp.Duration.ofMillis(millis)) + .getKeepAliveWithoutCalls()); } @Test @@ -186,8 +213,8 @@ void testWithPoolSize() throws IOException { @Test void testToBuilder() { - Duration keepaliveTime = Duration.ofSeconds(1); - Duration keepaliveTimeout = Duration.ofSeconds(2); + java.time.Duration keepaliveTime = java.time.Duration.ofSeconds(1); + java.time.Duration keepaliveTimeout = java.time.Duration.ofSeconds(2); ApiFunction channelConfigurator = builder -> { throw new UnsupportedOperationException(); @@ -200,9 +227,9 @@ void testToBuilder() { .setEndpoint("fake.endpoint:443") .setMaxInboundMessageSize(12345678) .setMaxInboundMetadataSize(4096) - .setKeepAliveTime(keepaliveTime) - .setKeepAliveTimeout(keepaliveTimeout) - .setKeepAliveWithoutCalls(true) + .setKeepAliveTimeDuration(keepaliveTime) + .setKeepAliveTimeoutDuration(keepaliveTimeout) + .setKeepAliveWithoutCalls(Boolean.TRUE) .setChannelConfigurator(channelConfigurator) .setChannelsPerCpu(2.5) .setDirectPathServiceConfig(directPathServiceConfig) @@ -213,8 +240,8 @@ void testToBuilder() { assertThat(builder.getEndpoint()).isEqualTo("fake.endpoint:443"); assertThat(builder.getMaxInboundMessageSize()).isEqualTo(12345678); assertThat(builder.getMaxInboundMetadataSize()).isEqualTo(4096); - assertThat(builder.getKeepAliveTime()).isEqualTo(keepaliveTime); - assertThat(builder.getKeepAliveTimeout()).isEqualTo(keepaliveTimeout); + assertThat(builder.getKeepAliveTimeDuration()).isEqualTo(keepaliveTime); + assertThat(builder.getKeepAliveTimeoutDuration()).isEqualTo(keepaliveTimeout); assertThat(builder.getChannelConfigurator()).isEqualTo(channelConfigurator); assertThat(builder.getPoolSize()).isEqualTo(5); assertThat(builder.build().directPathServiceConfig).isEqualTo(directPathServiceConfig); @@ -810,6 +837,7 @@ public void canUseDirectPath_nonGDUUniverseDomain() { } private static class FakeLogHandler extends Handler { + List records = new ArrayList<>(); @Override diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java index 6672f4c958..f08a3c3a89 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.grpc; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.gax.batching.BatchingSettings; @@ -58,9 +59,10 @@ import com.google.common.collect.Lists; import com.google.common.truth.Truth; import java.io.IOException; +import java.util.function.Function; +import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class SettingsTest { @@ -109,13 +111,13 @@ private static class FakeStubSettings extends StubSettings { RetrySettings settings = null; settings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(100L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.2) - .setMaxRetryDelay(Duration.ofMillis(1000L)) - .setInitialRpcTimeout(Duration.ofMillis(2000L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1000L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2000L)) .setRpcTimeoutMultiplier(1.5) - .setMaxRpcTimeout(Duration.ofMillis(30000L)) - .setTotalTimeout(Duration.ofMillis(45000L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(30000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(45000L)) .build(); definitions.put("default", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); @@ -221,7 +223,7 @@ private static Builder createDefault() { BatchingSettings.newBuilder() .setElementCountThreshold(800L) .setRequestByteThreshold(8388608L) - .setDelayThreshold(Duration.ofMillis(100)) + .setDelayThresholdDuration(java.time.Duration.ofMillis(100)) .build()); builder .fakeMethodBatching() @@ -334,11 +336,11 @@ void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() { @Test void callSettingsBuildFromTimeoutNoRetries() { - Duration timeout = Duration.ofMillis(60000); + java.time.Duration timeout = java.time.Duration.ofMillis(60000); UnaryCallSettings.Builder builderA = UnaryCallSettings.newUnaryCallSettingsBuilder(); - builderA.setSimpleTimeoutNoRetries(timeout); + builderA.setSimpleTimeoutNoRetriesDuration(timeout); UnaryCallSettings settingsA = builderA.build(); UnaryCallSettings.Builder builderB = @@ -347,17 +349,37 @@ void callSettingsBuildFromTimeoutNoRetries() { .setRetryableCodes() .setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(timeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(timeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ZERO) - .setInitialRpcTimeout(timeout) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) + .setInitialRpcTimeoutDuration(timeout) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(timeout) + .setMaxRpcTimeoutDuration(timeout) .setMaxAttempts(1) .build()); UnaryCallSettings settingsB = builderB.build(); assertEquals(settingsA, settingsB, "UnaryCallSettings"); } + + @Test + public void testWatchDogCheckInterval_backportMethodsBehaveCorrectly() { + final Function, StubSettings> build = + createBuilder -> { + try { + return createBuilder.get().build(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }; + testDurationMethod( + 123l, + jt -> + build.apply( + () -> FakeStubSettings.newBuilder().setStreamWatchdogCheckIntervalDuration(jt)), + tt -> build.apply(() -> FakeStubSettings.newBuilder().setStreamWatchdogCheckInterval(tt)), + ss -> ss.getStreamWatchdogCheckIntervalDuration(), + ss -> ss.getStreamWatchdogCheckInterval()); + } } diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java index 7945c23f8b..2cf42e33d6 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java @@ -63,7 +63,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class TimeoutTest { @@ -74,9 +73,12 @@ class TimeoutTest { private static final ImmutableSet emptyRetryCodes = ImmutableSet.of(); private static final ImmutableSet retryUnknownCode = ImmutableSet.of(StatusCode.Code.UNKNOWN); - private static final Duration totalTimeout = Duration.ofDays(DEADLINE_IN_DAYS); - private static final Duration maxRpcTimeout = Duration.ofMinutes(DEADLINE_IN_MINUTES); - private static final Duration initialRpcTimeout = Duration.ofSeconds(DEADLINE_IN_SECONDS); + private static final java.time.Duration totalTimeout = + java.time.Duration.ofDays(DEADLINE_IN_DAYS); + private static final java.time.Duration maxRpcTimeout = + java.time.Duration.ofMinutes(DEADLINE_IN_MINUTES); + private static final java.time.Duration initialRpcTimeout = + java.time.Duration.ofSeconds(DEADLINE_IN_SECONDS); private static GrpcCallContext defaultCallContext; @Mock private Marshaller stringMarshaller; @@ -96,15 +98,15 @@ public static void setUp() throws IOException { void testNonRetryUnarySettings() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) - .setInitialRpcTimeout(initialRpcTimeout) + .setInitialRpcTimeoutDuration(initialRpcTimeout) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(maxRpcTimeout) + .setMaxRpcTimeoutDuration(maxRpcTimeout) .build(); CallOptions callOptionsUsed = setupUnaryCallable(retrySettings, emptyRetryCodes, defaultCallContext); @@ -122,22 +124,22 @@ void testNonRetryUnarySettings() { void testNonRetryUnarySettingsContextWithRetry() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) - .setInitialRpcTimeout(initialRpcTimeout) + .setInitialRpcTimeoutDuration(initialRpcTimeout) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(maxRpcTimeout) + .setMaxRpcTimeoutDuration(maxRpcTimeout) .build(); - Duration newTimeout = Duration.ofSeconds(5); + java.time.Duration newTimeout = java.time.Duration.ofSeconds(5); RetrySettings contextRetrySettings = retrySettings .toBuilder() - .setInitialRpcTimeout(newTimeout) - .setMaxRpcTimeout(newTimeout) + .setInitialRpcTimeoutDuration(newTimeout) + .setMaxRpcTimeoutDuration(newTimeout) .setMaxAttempts(3) .build(); GrpcCallContext retryingContext = @@ -162,14 +164,14 @@ void testNonRetryUnarySettingsContextWithRetry() { void testNonRetryUnarySettingsWithoutInitialRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(maxRpcTimeout) + .setMaxRpcTimeoutDuration(maxRpcTimeout) .build(); CallOptions callOptionsUsed = setupUnaryCallable(retrySettings, emptyRetryCodes, defaultCallContext); @@ -187,10 +189,10 @@ void testNonRetryUnarySettingsWithoutInitialRpcTimeout() { void testNonRetryUnarySettingsWithoutIndividualRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) @@ -211,15 +213,15 @@ void testNonRetryUnarySettingsWithoutIndividualRpcTimeout() { void testNonRetryServerStreamingSettings() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) - .setInitialRpcTimeout(initialRpcTimeout) + .setInitialRpcTimeoutDuration(initialRpcTimeout) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(maxRpcTimeout) + .setMaxRpcTimeoutDuration(maxRpcTimeout) .build(); CallOptions callOptionsUsed = setupServerStreamingCallable(retrySettings, emptyRetryCodes, defaultCallContext); @@ -237,22 +239,22 @@ void testNonRetryServerStreamingSettings() { void testNonRetryServerStreamingSettingsContextWithRetry() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) - .setInitialRpcTimeout(initialRpcTimeout) + .setInitialRpcTimeoutDuration(initialRpcTimeout) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(maxRpcTimeout) + .setMaxRpcTimeoutDuration(maxRpcTimeout) .build(); - Duration newTimeout = Duration.ofSeconds(5); + java.time.Duration newTimeout = java.time.Duration.ofSeconds(5); RetrySettings contextRetrySettings = retrySettings .toBuilder() - .setInitialRpcTimeout(newTimeout) - .setMaxRpcTimeout(newTimeout) + .setInitialRpcTimeoutDuration(newTimeout) + .setMaxRpcTimeoutDuration(newTimeout) .setMaxAttempts(3) .build(); GrpcCallContext retryingContext = @@ -277,14 +279,14 @@ void testNonRetryServerStreamingSettingsContextWithRetry() { void testNonRetryServerStreamingSettingsWithoutInitialRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(maxRpcTimeout) + .setMaxRpcTimeoutDuration(maxRpcTimeout) .build(); CallOptions callOptionsUsed = setupServerStreamingCallable(retrySettings, emptyRetryCodes, defaultCallContext); @@ -302,10 +304,10 @@ void testNonRetryServerStreamingSettingsWithoutInitialRpcTimeout() { void testNonRetryServerStreamingSettingsWithoutIndividualRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(totalTimeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) @@ -449,7 +451,7 @@ private CallOptions setupServerStreamingCallable( * codebase must continue to support Java 7 and up, in alignment with client libraries that depend * on gax-java. */ - private int toSecondsPart(Duration duration) { + private int toSecondsPart(java.time.Duration duration) { return (int) (duration.getSeconds() - TimeUnit.MINUTES.toSeconds(1) diff --git a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallContext.java b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallContext.java index bde0c432a8..2b2d675a2a 100644 --- a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallContext.java +++ b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallContext.java @@ -29,8 +29,12 @@ */ package com.google.api.gax.httpjson; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiExceptionFactory; @@ -53,8 +57,6 @@ import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; -import org.threeten.bp.Instant; /** * HttpJsonCallContext encapsulates context data used to make an http-json call. @@ -69,9 +71,9 @@ public final class HttpJsonCallContext implements ApiCallContext { HttpJsonStatusCode.of(StatusCode.Code.UNAUTHENTICATED); private final HttpJsonChannel channel; private final HttpJsonCallOptions callOptions; - @Nullable private final Duration timeout; - @Nullable private final Duration streamWaitTimeout; - @Nullable private final Duration streamIdleTimeout; + @Nullable private final java.time.Duration timeout; + @Nullable private final java.time.Duration streamWaitTimeout; + @Nullable private final java.time.Duration streamIdleTimeout; private final ImmutableMap> extraHeaders; private final ApiCallContextOptions options; private final ApiTracer tracer; @@ -113,9 +115,9 @@ public static HttpJsonCallContext of(HttpJsonChannel channel, HttpJsonCallOption private HttpJsonCallContext( HttpJsonChannel channel, HttpJsonCallOptions callOptions, - Duration timeout, - Duration streamWaitTimeout, - Duration streamIdleTimeout, + java.time.Duration timeout, + java.time.Duration streamWaitTimeout, + java.time.Duration streamIdleTimeout, ImmutableMap> extraHeaders, ApiCallContextOptions options, ApiTracer tracer, @@ -181,17 +183,17 @@ public HttpJsonCallContext merge(ApiCallContext inputCallContext) { // Do deep merge of callOptions HttpJsonCallOptions newCallOptions = callOptions.merge(httpJsonCallContext.callOptions); - Duration newTimeout = httpJsonCallContext.timeout; + java.time.Duration newTimeout = httpJsonCallContext.timeout; if (newTimeout == null) { newTimeout = this.timeout; } - Duration newStreamWaitTimeout = httpJsonCallContext.streamWaitTimeout; + java.time.Duration newStreamWaitTimeout = httpJsonCallContext.streamWaitTimeout; if (newStreamWaitTimeout == null) { newStreamWaitTimeout = streamWaitTimeout; } - Duration newStreamIdleTimeout = httpJsonCallContext.streamIdleTimeout; + java.time.Duration newStreamIdleTimeout = httpJsonCallContext.streamIdleTimeout; if (newStreamIdleTimeout == null) { newStreamIdleTimeout = streamIdleTimeout; } @@ -250,6 +252,13 @@ public HttpJsonCallContext withTransportChannel(TransportChannel inputChannel) { return withChannel(transportChannel.getChannel()); } + /** This method is obsolete. Use {@link #withTimeoutDuration(java.time.Duration)} instead. */ + @Override + @ObsoleteApi("Use withTimeoutDuration(java.time.Duration) instead") + public HttpJsonCallContext withTimeout(org.threeten.bp.Duration timeout) { + return withTimeoutDuration(toJavaTimeDuration(timeout)); + } + @Override public HttpJsonCallContext withEndpointContext(EndpointContext endpointContext) { Preconditions.checkNotNull(endpointContext); @@ -268,7 +277,7 @@ public HttpJsonCallContext withEndpointContext(EndpointContext endpointContext) } @Override - public HttpJsonCallContext withTimeout(Duration timeout) { + public HttpJsonCallContext withTimeoutDuration(java.time.Duration timeout) { // Default RetrySettings use 0 for RPC timeout. Treat that as disabled timeouts. if (timeout != null && (timeout.isZero() || timeout.isNegative())) { timeout = null; @@ -293,17 +302,37 @@ public HttpJsonCallContext withTimeout(Duration timeout) { this.endpointContext); } + /** This method is obsolete. Use {@link #getTimeoutDuration()} instead. */ @Nullable @Override - public Duration getTimeout() { + @ObsoleteApi("Use getTimeoutDuration instead") + public org.threeten.bp.Duration getTimeout() { + return toThreetenDuration(getTimeoutDuration()); + } + + @Nullable + @Override + public java.time.Duration getTimeoutDuration() { return timeout; } + /** + * This method is obsolete. Use {@link #withStreamWaitTimeoutDuration(java.time.Duration)} + * instead. + */ + @Override + @ObsoleteApi("Use withStreamWaitTimeoutDuration(java.time.Duration) instead") + public HttpJsonCallContext withStreamWaitTimeout( + @Nullable org.threeten.bp.Duration streamWaitTimeout) { + return withStreamWaitTimeoutDuration(toJavaTimeDuration(streamWaitTimeout)); + } + @Override - public HttpJsonCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeout) { + public HttpJsonCallContext withStreamWaitTimeoutDuration( + @Nullable java.time.Duration streamWaitTimeout) { if (streamWaitTimeout != null) { Preconditions.checkArgument( - streamWaitTimeout.compareTo(Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); + streamWaitTimeout.compareTo(java.time.Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); } return new HttpJsonCallContext( @@ -320,22 +349,42 @@ public HttpJsonCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTi this.endpointContext); } + /** This method is obsolete. Use {@link #getStreamWaitTimeoutDuration()} instead. */ + @Override + @Nullable + @ObsoleteApi("Use getStreamWaitTimeoutDuration() instead") + public org.threeten.bp.Duration getStreamWaitTimeout() { + return toThreetenDuration(getStreamWaitTimeoutDuration()); + } + /** * The stream wait timeout set for this context. * - * @see ApiCallContext#withStreamWaitTimeout(Duration) + * @see ApiCallContext#withStreamWaitTimeoutDuration(java.time.Duration) */ @Override @Nullable - public Duration getStreamWaitTimeout() { + public java.time.Duration getStreamWaitTimeoutDuration() { return streamWaitTimeout; } + /** + * This method is obsolete. Use {@link #withStreamIdleTimeoutDuration(java.time.Duration)} + * instead. + */ @Override - public HttpJsonCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTimeout) { + @ObsoleteApi("Use withStreamIdleTimeoutDuration(java.time.Duration) instead") + public HttpJsonCallContext withStreamIdleTimeout( + @Nullable org.threeten.bp.Duration streamIdleTimeout) { + return withStreamIdleTimeoutDuration(toJavaTimeDuration(streamIdleTimeout)); + } + + @Override + public HttpJsonCallContext withStreamIdleTimeoutDuration( + @Nullable java.time.Duration streamIdleTimeout) { if (streamIdleTimeout != null) { Preconditions.checkArgument( - streamIdleTimeout.compareTo(Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); + streamIdleTimeout.compareTo(java.time.Duration.ZERO) >= 0, "Invalid timeout: < 0 s"); } return new HttpJsonCallContext( @@ -352,14 +401,22 @@ public HttpJsonCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTi this.endpointContext); } + /** This method is obsolete. Use {@link #getStreamIdleTimeoutDuration()} instead. */ + @Override + @Nullable + @ObsoleteApi("Use getStreamIdleTimeoutDuration() instead") + public org.threeten.bp.Duration getStreamIdleTimeout() { + return toThreetenDuration(getStreamIdleTimeoutDuration()); + } + /** * The stream idle timeout set for this context. * - * @see ApiCallContext#withStreamIdleTimeout(Duration) + * @see ApiCallContext#withStreamIdleTimeoutDuration(java.time.Duration) */ @Override @Nullable - public Duration getStreamIdleTimeout() { + public java.time.Duration getStreamIdleTimeoutDuration() { return streamIdleTimeout; } @@ -448,7 +505,7 @@ public HttpJsonCallOptions getCallOptions() { @Deprecated @Nullable - public Instant getDeadline() { + public org.threeten.bp.Instant getDeadline() { return getCallOptions() != null ? getCallOptions().getDeadline() : null; } @@ -531,7 +588,7 @@ public HttpJsonCallContext withCallOptions(HttpJsonCallOptions newCallOptions) { } @Deprecated - public HttpJsonCallContext withDeadline(Instant newDeadline) { + public HttpJsonCallContext withDeadline(org.threeten.bp.Instant newDeadline) { HttpJsonCallOptions.Builder builder = callOptions != null ? callOptions.toBuilder() : HttpJsonCallOptions.newBuilder(); return withCallOptions(builder.setDeadline(newDeadline).build()); diff --git a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallOptions.java b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallOptions.java index df2ca03edc..4c2d8ae55e 100644 --- a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallOptions.java +++ b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonCallOptions.java @@ -29,23 +29,41 @@ */ package com.google.api.gax.httpjson; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeInstant; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenInstant; + +import com.google.api.core.ObsoleteApi; import com.google.auth.Credentials; import com.google.auto.value.AutoValue; import com.google.protobuf.TypeRegistry; -import java.time.Duration; import javax.annotation.Nullable; -import org.threeten.bp.Instant; /** Options for an http-json call, including deadline and credentials. */ @AutoValue public abstract class HttpJsonCallOptions { public static final HttpJsonCallOptions DEFAULT = newBuilder().build(); + /** This method is obsolete. Use {@link #getTimeoutDuration()} instead. */ + @Nullable + @ObsoleteApi("Use getTimeoutDuration() instead") + public final org.threeten.bp.Duration getTimeout() { + return toThreetenDuration(getTimeoutDuration()); + } + @Nullable - public abstract Duration getTimeout(); + public abstract java.time.Duration getTimeoutDuration(); + /** This method is obsolete. Use {@link #getDeadlineInstant()} instead. */ @Nullable - public abstract Instant getDeadline(); + @ObsoleteApi("Use getDeadlineInstant() instead") + public final org.threeten.bp.Instant getDeadline() { + return toThreetenInstant(getDeadlineInstant()); + } + + @Nullable + public abstract java.time.Instant getDeadlineInstant(); @Nullable public abstract Credentials getCredentials(); @@ -66,15 +84,15 @@ public HttpJsonCallOptions merge(HttpJsonCallOptions inputOptions) { Builder builder = this.toBuilder(); - Instant newDeadline = inputOptions.getDeadline(); + java.time.Instant newDeadline = inputOptions.getDeadlineInstant(); if (newDeadline != null) { - builder.setDeadline(newDeadline); + builder.setDeadlineInstant(newDeadline); } if (inputOptions.getTimeout() != null) { - Duration newTimeout = java.time.Duration.ofMillis(inputOptions.getTimeout().toMillis()); + java.time.Duration newTimeout = inputOptions.getTimeoutDuration(); if (newTimeout != null) { - builder.setTimeout(newTimeout); + builder.setTimeoutDuration(newTimeout); } } @@ -93,9 +111,21 @@ public HttpJsonCallOptions merge(HttpJsonCallOptions inputOptions) { @AutoValue.Builder public abstract static class Builder { - public abstract Builder setTimeout(java.time.Duration value); + /** This method is obsolete. Use {@link #setTimeoutDuration(java.time.Duration)} instead. */ + @ObsoleteApi("Use setTimeoutDuration(java.time.Duration) instead") + public final Builder setTimeout(org.threeten.bp.Duration value) { + return setTimeoutDuration(toJavaTimeDuration(value)); + } + + public abstract Builder setTimeoutDuration(java.time.Duration value); + + /** This method is obsolete. Use {@link #setDeadlineInstant(java.time.Instant)} instead. */ + @ObsoleteApi("Use setDeadlineInstant(java.time.Instant) instead") + public final Builder setDeadline(org.threeten.bp.Instant value) { + return setDeadlineInstant(toJavaTimeInstant(value)); + } - public abstract Builder setDeadline(Instant value); + public abstract Builder setDeadlineInstant(java.time.Instant value); public abstract Builder setCredentials(Credentials value); diff --git a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCallImpl.java b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCallImpl.java index 4ec7572216..df9a507519 100644 --- a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCallImpl.java +++ b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCallImpl.java @@ -40,7 +40,6 @@ import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; -import java.time.Duration; import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.CancellationException; @@ -178,7 +177,7 @@ public void start(Listener responseListener, HttpJsonMetadata request // Use the timeout duration value instead of calculating the future Instant // Only schedule the deadline if the RPC timeout has been set in the RetrySettings - Duration timeout = callOptions.getTimeout(); + java.time.Duration timeout = callOptions.getTimeoutDuration(); if (timeout != null) { // The future timeout value is guaranteed to not be a negative value as the // RetryAlgorithm will not retry diff --git a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCalls.java b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCalls.java index 880a38d56a..6be4ec7ec6 100644 --- a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCalls.java +++ b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonClientCalls.java @@ -34,7 +34,6 @@ import com.google.api.gax.rpc.ApiCallContext; import java.util.logging.Level; import java.util.logging.Logger; -import org.threeten.bp.Duration; /** * {@code HttpJsonClientCalls} creates a new {@code HttpJsonClientCall} from the given call context. @@ -52,21 +51,23 @@ public static HttpJsonClientCall newC // Use the context's timeout instead of calculating a future deadline with the System clock. // The timeout value is calculated from TimedAttemptSettings which accounts for the // TotalTimeout value set in the RetrySettings. - if (httpJsonContext.getTimeout() != null) { + if (httpJsonContext.getTimeoutDuration() != null) { HttpJsonCallOptions callOptions = httpJsonContext.getCallOptions(); // HttpJsonChannel expects the HttpJsonCallOptions and we store the timeout duration // inside the HttpJsonCallOptions // Note: There is manual conversion between threetenbp's Duration and java.util.Duration // This is temporary here as we plan to migrate to java.util.Duration - if (callOptions.getTimeout() == null + if (callOptions.getTimeoutDuration() == null || httpJsonContext - .getTimeout() - .compareTo(Duration.ofMillis(callOptions.getTimeout().toMillis())) + .getTimeoutDuration() + .compareTo( + java.time.Duration.ofMillis(callOptions.getTimeoutDuration().toMillis())) < 0) { callOptions = callOptions .toBuilder() - .setTimeout(java.time.Duration.ofMillis(httpJsonContext.getTimeout().toMillis())) + .setTimeoutDuration( + java.time.Duration.ofMillis(httpJsonContext.getTimeoutDuration().toMillis())) .build(); } httpJsonContext = httpJsonContext.withCallOptions(callOptions); diff --git a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java index b5597099d2..2738844bd0 100644 --- a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java +++ b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java @@ -52,7 +52,6 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -234,7 +233,7 @@ private HttpRequest buildRequest( httpRequest.getHeaders(), "X-HTTP-Method-Override", originalHttpMethod); } - Duration timeout = httpJsonCallOptions.getTimeout(); + java.time.Duration timeout = httpJsonCallOptions.getTimeoutDuration(); if (timeout != null) { long timeoutMs = timeout.toMillis(); diff --git a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java index 5f327a1091..b1664088a5 100644 --- a/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java +++ b/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java @@ -65,7 +65,6 @@ import com.google.protobuf.Empty; import java.io.IOException; import java.util.List; -import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** @@ -293,13 +292,13 @@ public static class Builder extends StubSettings.Builder defaultContext.withStreamIdleTimeoutDuration(jt), + tt -> defaultContext.withStreamIdleTimeout(tt), + c -> c.getStreamIdleTimeoutDuration(), + c -> c.getStreamIdleTimeout()); + } + + @Test + public void testStreamWaitTimeout() { + final long millis = 3; + final HttpJsonCallContext defaultContext = HttpJsonCallContext.createDefault(); + testDurationMethod( + millis, + jt -> defaultContext.withStreamWaitTimeoutDuration(jt), + tt -> defaultContext.withStreamWaitTimeout(tt), + c -> c.getStreamWaitTimeoutDuration(), + c -> c.getStreamWaitTimeout()); + } + + @Test + public void testTimeout() { + final long millis = 3; + final HttpJsonCallContext defaultContext = HttpJsonCallContext.createDefault(); + testDurationMethod( + millis, + jt -> defaultContext.withTimeoutDuration(jt), + tt -> defaultContext.withTimeout(tt), + c -> c.getTimeoutDuration(), + c -> c.getTimeout()); + } + + @Test + public void testNullTimeout() { + final HttpJsonCallContext defaultContext = HttpJsonCallContext.createDefault(); + testDurationMethod( + null, + jt -> defaultContext.withTimeoutDuration(jt), + tt -> defaultContext.withTimeout(tt), + c -> c.getTimeoutDuration(), + c -> c.getTimeout()); } @Test void testWithNegativeTimeout() { assertNull( - HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(-1L)).getTimeout()); + HttpJsonCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(-1L)) + .getTimeoutDuration()); } @Test void testWithZeroTimeout() { assertNull( - HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(0L)).getTimeout()); + HttpJsonCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(0L)) + .getTimeoutDuration()); } @Test void testWithShorterTimeout() { HttpJsonCallContext ctxWithLongTimeout = - HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(10)); + HttpJsonCallContext.createDefault().withTimeoutDuration(java.time.Duration.ofSeconds(10)); // Sanity check - Truth.assertThat(ctxWithLongTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(10)); + Truth.assertThat(ctxWithLongTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(10)); // Shorten the timeout and make sure it changed HttpJsonCallContext ctxWithShorterTimeout = - ctxWithLongTimeout.withTimeout(Duration.ofSeconds(5)); - Truth.assertThat(ctxWithShorterTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(5)); + ctxWithLongTimeout.withTimeoutDuration(java.time.Duration.ofSeconds(5)); + Truth.assertThat(ctxWithShorterTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(5)); } @Test void testWithLongerTimeout() { HttpJsonCallContext ctxWithShortTimeout = - HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(5)); + HttpJsonCallContext.createDefault().withTimeoutDuration(java.time.Duration.ofSeconds(5)); // Sanity check - Truth.assertThat(ctxWithShortTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(5)); + Truth.assertThat(ctxWithShortTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(5)); // Try to extend the timeout and verify that it was ignored HttpJsonCallContext ctxWithUnchangedTimeout = - ctxWithShortTimeout.withTimeout(Duration.ofSeconds(10)); - Truth.assertThat(ctxWithUnchangedTimeout.getTimeout()).isEqualTo(Duration.ofSeconds(5)); + ctxWithShortTimeout.withTimeoutDuration(java.time.Duration.ofSeconds(10)); + Truth.assertThat(ctxWithUnchangedTimeout.getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(5)); } @Test void testMergeWithNullTimeout() { - Duration timeout = Duration.ofSeconds(10); - HttpJsonCallContext baseContext = HttpJsonCallContext.createDefault().withTimeout(timeout); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); + HttpJsonCallContext baseContext = + HttpJsonCallContext.createDefault().withTimeoutDuration(timeout); HttpJsonCallContext defaultOverlay = HttpJsonCallContext.createDefault(); - Truth.assertThat(baseContext.merge(defaultOverlay).getTimeout()).isEqualTo(timeout); + Truth.assertThat(baseContext.merge(defaultOverlay).getTimeoutDuration()).isEqualTo(timeout); - HttpJsonCallContext explicitNullOverlay = HttpJsonCallContext.createDefault().withTimeout(null); - Truth.assertThat(baseContext.merge(explicitNullOverlay).getTimeout()).isEqualTo(timeout); + java.time.Duration callContextTimeout = null; + HttpJsonCallContext explicitNullOverlay = + HttpJsonCallContext.createDefault().withTimeoutDuration(callContextTimeout); + Truth.assertThat(baseContext.merge(explicitNullOverlay).getTimeoutDuration()) + .isEqualTo(timeout); } @Test void testMergeWithTimeout() { - Duration timeout = Duration.ofSeconds(19); + java.time.Duration timeout = java.time.Duration.ofSeconds(19); HttpJsonCallContext ctx1 = HttpJsonCallContext.createDefault(); - HttpJsonCallContext ctx2 = HttpJsonCallContext.createDefault().withTimeout(timeout); + HttpJsonCallContext ctx2 = HttpJsonCallContext.createDefault().withTimeoutDuration(timeout); - Truth.assertThat(ctx1.merge(ctx2).getTimeout()).isEqualTo(timeout); + Truth.assertThat(ctx1.merge(ctx2).getTimeoutDuration()).isEqualTo(timeout); } @Test diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallOptionsTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallOptionsTest.java new file mode 100644 index 0000000000..c6aa69d4d8 --- /dev/null +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallOptionsTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.httpjson; + +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; +import static com.google.api.gax.util.TimeConversionTestUtils.testInstantMethod; + +import org.junit.jupiter.api.Test; + +public class HttpJsonCallOptionsTest { + private final HttpJsonCallOptions.Builder OPTIONS_BUILDER = HttpJsonCallOptions.newBuilder(); + + @Test + public void testDeadline() { + final long millis = 3; + testInstantMethod( + millis, + jt -> OPTIONS_BUILDER.setDeadlineInstant(jt), + tt -> OPTIONS_BUILDER.setDeadline(tt), + c -> c.build().getDeadlineInstant(), + c -> c.build().getDeadline()); + } + + @Test + public void testTimeout() { + final long millis = 3; + testDurationMethod( + millis, + jt -> OPTIONS_BUILDER.setTimeoutDuration(jt), + tt -> OPTIONS_BUILDER.setTimeout(tt), + c -> c.build().getTimeoutDuration(), + c -> c.build().getTimeout()); + } +} diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java index e65c9d9758..2853e79ad5 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java @@ -35,7 +35,6 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; -import java.time.Duration; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -59,7 +58,7 @@ class HttpJsonClientCallImplTest { void responseReceived_noCancellationTask() { ScheduledThreadPoolExecutor deadlineSchedulerExecutor = new ScheduledThreadPoolExecutor(1); // Null timeout means no timeout task created - Mockito.when(httpJsonCallOptions.getTimeout()).thenReturn(null); + Mockito.when(httpJsonCallOptions.getTimeoutDuration()).thenReturn(null); HttpJsonClientCallImpl httpJsonClientCall = new HttpJsonClientCallImpl<>( @@ -93,7 +92,8 @@ void responseReceived_cancellationTaskExists_isCancelledProperly() throws Interr deadlineSchedulerExecutor.setRemoveOnCancelPolicy(true); // Setting a timeout for this call will enqueue a timeout task - Mockito.when(httpJsonCallOptions.getTimeout()).thenReturn(Duration.ofMinutes(10)); + Mockito.when(httpJsonCallOptions.getTimeoutDuration()) + .thenReturn(java.time.Duration.ofMinutes(10)); String response = "Content"; InputStream inputStream = new ByteArrayInputStream(response.getBytes()); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java index dc5844616d..85146ceb07 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java @@ -52,7 +52,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class HttpJsonClientInterceptorTest { @@ -191,7 +190,7 @@ void testCustomInterceptor() throws ExecutionException, InterruptedException, IO HttpJsonCallContext callContext = HttpJsonCallContext.createDefault() .withChannel(channel) - .withTimeout(Duration.ofSeconds(30)) + .withTimeoutDuration(java.time.Duration.ofSeconds(30)) .withEndpointContext(endpointContext); Field request; diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java index 0c14779bc8..447a8354f1 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java @@ -55,7 +55,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class HttpJsonDirectCallableTest { @@ -126,7 +125,7 @@ public static void initialize() throws IOException { defaultCallContext = HttpJsonCallContext.createDefault() .withChannel(channel) - .withTimeout(Duration.ofSeconds(30)) + .withTimeoutDuration(java.time.Duration.ofSeconds(30)) .withEndpointContext(endpointContext); } @@ -331,7 +330,8 @@ void testDeadlineExceededResponse() throws InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); - HttpJsonCallContext callContext = defaultCallContext.withTimeout(Duration.ofSeconds(3)); + HttpJsonCallContext callContext = + defaultCallContext.withTimeoutDuration(java.time.Duration.ofSeconds(3)); Field response = createTestMessage(10); MOCK_SERVICE.addResponse(response, java.time.Duration.ofSeconds(5)); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java index 5cae0fda31..f0ff2b4dc2 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java @@ -66,7 +66,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class HttpJsonDirectServerStreamingCallableTest { private static final Color DEFAULT_REQUEST = Color.newBuilder().setRed(0.5f).build(); @@ -88,10 +87,10 @@ class HttpJsonDirectServerStreamingCallableTest { @BeforeEach void initialize() throws IOException { - initialize(Duration.ofSeconds(30)); + initialize(java.time.Duration.ofSeconds(30)); } - void initialize(Duration timeout) throws IOException { + void initialize(java.time.Duration timeout) throws IOException { this.methodServerStreamingRecognize = ApiMethodDescriptor.newBuilder() .setFullMethodName("google.cloud.v1.Fake/ServerStreamingRecognize") @@ -147,7 +146,7 @@ void initialize(Duration timeout) throws IOException { .setTransportChannel(HttpJsonTransportChannel.create(channel)) .setDefaultCallContext( HttpJsonCallContext.of(channel, HttpJsonCallOptions.DEFAULT) - .withTimeout(timeout) + .withTimeoutDuration(timeout) .withEndpointContext(endpointContext)) .build(); @@ -332,7 +331,7 @@ void testBlockingServerStreaming() { @Test void testDeadlineExceededServerStreaming() throws InterruptedException, IOException { // set a low timeout to trigger deadline-exceeded sooner - initialize(Duration.ofSeconds(1)); + initialize(java.time.Duration.ofSeconds(1)); mockService.addResponse( new Money[] {DEFAULT_RESPONSE, DEFAULTER_RESPONSE}, java.time.Duration.ofSeconds(30)); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpRequestRunnableTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpRequestRunnableTest.java index 209b511388..27c7c3e470 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpRequestRunnableTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpRequestRunnableTest.java @@ -259,7 +259,9 @@ void testUpdateRunnableTimeout_shouldNotUpdate() throws IOException { requestMessage, methodDescriptor, "www.googleapis.com/animals/v1/projects", - HttpJsonCallOptions.newBuilder().setTimeout(java.time.Duration.ofMillis(5000L)).build(), + HttpJsonCallOptions.newBuilder() + .setTimeoutDuration(java.time.Duration.ofMillis(5000L)) + .build(), new MockHttpTransport(), HttpJsonMetadata.newBuilder().build(), (result) -> {}); @@ -285,7 +287,7 @@ void testUpdateRunnableTimeout_shouldUpdate() throws IOException { methodDescriptor, "www.googleapis.com/animals/v1/projects", HttpJsonCallOptions.newBuilder() - .setTimeout(java.time.Duration.ofMillis(30000L)) + .setTimeoutDuration(java.time.Duration.ofMillis(30000L)) .build(), new MockHttpTransport(), HttpJsonMetadata.newBuilder().build(), diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java index c70e2d5bf0..892fc9b8f8 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java @@ -64,7 +64,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; class RetryingTest { @@ -103,13 +102,13 @@ class RetryingTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(2L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(2L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(2L)) - .setInitialRpcTimeout(Duration.ofMillis(2L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(2L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(2L)) - .setTotalTimeout(Duration.ofMillis(10L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(10L)) .build(); @BeforeEach @@ -173,8 +172,8 @@ void retryTotalTimeoutExceeded() { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) - .setMaxRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) .build(); UnaryCallSettings callSettings = createSettings(retryable, retrySettings); UnaryCallable callable = diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java index 86cc78fd7d..931041201d 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java @@ -43,7 +43,6 @@ import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; -import java.time.Duration; import java.util.LinkedList; import java.util.List; import java.util.Queue; @@ -88,7 +87,7 @@ public synchronized void addResponse(Object response) { responseHandlers.add(new MessageResponseFactory(endpoint, serviceMethodDescriptors, response)); } - public synchronized void addResponse(Object response, Duration delay) { + public synchronized void addResponse(Object response, java.time.Duration delay) { responseHandlers.add( new MessageResponseFactory(endpoint, serviceMethodDescriptors, response, delay)); } @@ -188,18 +187,18 @@ private static class MessageResponseFactory implements HttpResponseFactory { private final List serviceMethodDescriptors; private final Object response; private final String endpoint; - private final Duration delay; + private final java.time.Duration delay; public MessageResponseFactory( String endpoint, List serviceMethodDescriptors, Object response) { - this(endpoint, serviceMethodDescriptors, response, Duration.ofNanos(0)); + this(endpoint, serviceMethodDescriptors, response, java.time.Duration.ofNanos(0)); } public MessageResponseFactory( String endpoint, List serviceMethodDescriptors, Object response, - Duration delay) { + java.time.Duration delay) { this.endpoint = endpoint; this.serviceMethodDescriptors = ImmutableList.copyOf(serviceMethodDescriptors); this.response = response; diff --git a/gax-java/gax/clirr-ignored-differences.xml b/gax-java/gax/clirr-ignored-differences.xml index b58200572e..cab9fe4f8a 100644 --- a/gax-java/gax/clirr-ignored-differences.xml +++ b/gax-java/gax/clirr-ignored-differences.xml @@ -19,6 +19,58 @@ *setWaitTimeout* com.google.api.gax.rpc.ServerStreamingCallSettings$Builder + + 7014 + com/google/api/gax/*/* + org.threeten.bp.Duration *(*) + + + 7014 + com/google/api/gax/*/* + * *(org.threeten.bp.Duration) + + + 7013 + com/google/api/gax/*/* + java.time.Duration *Duration(*) + + + 7013 + com/google/api/gax/*/* + * set*Duration(*) + + + + 7005 + com/google/api/gax/retrying/DirectRetryingExecutor + * sleep(*org.threeten.bp.Duration*) + * + + + 7012 + com/google/api/gax/*/* + * get*Duration() + + + 7012 + com/google/api/gax/*/* + * *(java.time.Duration) + + + 7012 + com/google/api/gax/tracing/* + * attemptFailedDuration(java.lang.Throwable, java.time.Duration) + + + 7002 + com/google/api/gax/*/* + *org.threeten.bp.Duration *() + + + 7002 + com/google/api/gax/grpc/InstantiatingGrpcChannelProvider$Builder + * * + 7012 diff --git a/gax-java/gax/pom.xml b/gax-java/gax/pom.xml index defb4d62b8..911e24a203 100644 --- a/gax-java/gax/pom.xml +++ b/gax-java/gax/pom.xml @@ -103,7 +103,7 @@ org.apache.maven.plugins maven-surefire-plugin - -Djava.util.logging.SimpleFormatter.format="%1$tY %1$tl:%1$tM:%1$tS.%1$tL %2$s %4$s: %5$s%6$s%n" + @{argLine} -Djava.util.logging.SimpleFormatter.format="%1$tY %1$tl:%1$tM:%1$tS.%1$tL %2$s %4$s: %5$s%6$s%n" !EndpointContextTest#endpointContextBuild_universeDomainEnvVarSet+endpointContextBuild_multipleUniverseDomainConfigurations_clientSettingsHasPriority diff --git a/gax-java/gax/src/main/java/com/google/api/gax/batching/BatcherImpl.java b/gax-java/gax/src/main/java/com/google/api/gax/batching/BatcherImpl.java index 415e43610a..8cb437a5e2 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/batching/BatcherImpl.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/batching/BatcherImpl.java @@ -198,8 +198,8 @@ public BatcherImpl( } this.flowController = flowController; currentOpenBatch = new Batch<>(prototype, batchingDescriptor, batcherStats); - if (batchingSettings.getDelayThreshold() != null) { - long delay = batchingSettings.getDelayThreshold().toMillis(); + if (batchingSettings.getDelayThresholdDuration() != null) { + long delay = batchingSettings.getDelayThresholdDuration().toMillis(); PushCurrentBatchRunnable runnable = new PushCurrentBatchRunnable<>(this); scheduledFuture = diff --git a/gax-java/gax/src/main/java/com/google/api/gax/batching/BatchingSettings.java b/gax-java/gax/src/main/java/com/google/api/gax/batching/BatchingSettings.java index 8982c46ffa..7507f6c284 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/batching/BatchingSettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/batching/BatchingSettings.java @@ -29,11 +29,15 @@ */ package com.google.api.gax.batching; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + +import com.google.api.core.ObsoleteApi; import com.google.api.gax.batching.FlowController.LimitExceededBehavior; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; +import java.time.Duration; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * Represents the batching settings to use for an API method that is capable of batching. @@ -98,9 +102,16 @@ public abstract class BatchingSettings { @Nullable public abstract Long getRequestByteThreshold(); + /** This method is obsolete. Use {@link #getDelayThresholdDuration() } instead */ + @Nullable + @ObsoleteApi("Use getDelayThresholdDuration() instead") + public org.threeten.bp.Duration getDelayThreshold() { + return toThreetenDuration(getDelayThresholdDuration()); + } + /** Get the delay threshold to use for batching. */ @Nullable - public abstract Duration getDelayThreshold(); + public abstract java.time.Duration getDelayThresholdDuration(); /** Returns the Boolean object to indicate if the batching is enabled. Default to true */ public abstract Boolean getIsEnabled(); @@ -114,7 +125,7 @@ public static Builder newBuilder() { .setIsEnabled(true) .setElementCountThreshold(1L) .setRequestByteThreshold(1L) - .setDelayThreshold(Duration.ofMillis(1)) + .setDelayThresholdDuration(java.time.Duration.ofMillis(1)) .setFlowControlSettings( FlowControlSettings.newBuilder() .setLimitExceededBehavior(LimitExceededBehavior.Ignore) @@ -142,13 +153,19 @@ public abstract static class Builder { */ public abstract Builder setRequestByteThreshold(Long requestByteThreshold); + /** This method is obsolete. Use {@link #setDelayThresholdDuration(Duration)} instead */ + @ObsoleteApi("Use setDelayThresholdDuration(java.time.Duration) instead") + public final Builder setDelayThreshold(org.threeten.bp.Duration delayThreshold) { + return setDelayThresholdDuration(toJavaTimeDuration(delayThreshold)); + } + /** * Set the delay threshold to use for batching. After this amount of time has elapsed (counting * from the first element added), the elements will be wrapped up in a batch and sent. This * value should not be set too high, usually on the order of milliseconds. Otherwise, calls * might appear to never complete. */ - public abstract Builder setDelayThreshold(Duration delayThreshold); + public abstract Builder setDelayThresholdDuration(java.time.Duration delayThreshold); /** * Set if the batch should be enabled. If set to false, the batch logic will be disabled and the @@ -171,8 +188,8 @@ public BatchingSettings build() { settings.getRequestByteThreshold() == null || settings.getRequestByteThreshold() > 0, "requestByteThreshold must be either unset or positive"); Preconditions.checkArgument( - settings.getDelayThreshold() == null - || settings.getDelayThreshold().compareTo(Duration.ZERO) > 0, + settings.getDelayThresholdDuration() == null + || settings.getDelayThresholdDuration().compareTo(java.time.Duration.ZERO) > 0, "delayThreshold must be either unset or positive"); return settings; } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/batching/ThresholdBatcher.java b/gax-java/gax/src/main/java/com/google/api/gax/batching/ThresholdBatcher.java index 75d93ec148..0afc3018bd 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/batching/ThresholdBatcher.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/batching/ThresholdBatcher.java @@ -29,23 +29,25 @@ */ package com.google.api.gax.batching; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutureCallback; import com.google.api.core.ApiFutures; +import com.google.api.core.ObsoleteApi; import com.google.api.core.SettableApiFuture; import com.google.api.gax.batching.FlowController.FlowControlException; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; -import org.threeten.bp.Duration; /** * Queues up elements until either a duration of time has passed or any threshold in a given set of @@ -77,7 +79,7 @@ public void run() { private final ArrayList> thresholds; private final ScheduledExecutorService executor; - private final Duration maxDelay; + private final java.time.Duration maxDelay; private final ThresholdBatchReceiver receiver; private final BatchingFlowController flowController; private final BatchMerger batchMerger; @@ -104,7 +106,7 @@ private ThresholdBatcher(Builder builder) { public static class Builder { private Collection> thresholds; private ScheduledExecutorService executor; - private Duration maxDelay; + private java.time.Duration maxDelay; private ThresholdBatchReceiver receiver; private BatchingFlowController flowController; private BatchMerger batchMerger; @@ -118,11 +120,17 @@ public Builder setExecutor(ScheduledExecutorService executor) { } /** Set the max delay for a batch. This is counted from the first item added to a batch. */ - public Builder setMaxDelay(Duration maxDelay) { + public Builder setMaxDelayDuration(java.time.Duration maxDelay) { this.maxDelay = maxDelay; return this; } + /** This method is obsolete. Use {@link #setMaxDelayDuration(Duration)} instead */ + @ObsoleteApi("Use setMaxDelayDuration(java.time.Duration) instead") + public Builder setMaxDelay(org.threeten.bp.Duration maxDelay) { + return setMaxDelayDuration(toJavaTimeDuration(maxDelay)); + } + /** Set the thresholds for the ThresholdBatcher. */ public Builder setThresholds(Collection> thresholds) { this.thresholds = thresholds; @@ -134,7 +142,6 @@ public Builder setReceiver(ThresholdBatchReceiver receiver) { this.receiver = receiver; return this; } - /** Set the flow controller for the ThresholdBatcher. */ public Builder setFlowController(BatchingFlowController flowController) { this.flowController = flowController; diff --git a/gax-java/gax/src/main/java/com/google/api/gax/retrying/BasicRetryingFuture.java b/gax-java/gax/src/main/java/com/google/api/gax/retrying/BasicRetryingFuture.java index de7b5b5acb..c1a7ad8898 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/retrying/BasicRetryingFuture.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/retrying/BasicRetryingFuture.java @@ -183,11 +183,12 @@ void handleAttempt(Throwable throwable, ResponseT response) { ? callable.getClass().getEnclosingMethod().getName() : ""), "attemptCount: " + attemptSettings.getAttemptCount(), - "delay: " + attemptSettings.getRetryDelay(), + "delay: " + attemptSettings.getRetryDelayDuration(), "retriableException: " + throwable }); } - tracer.attemptFailed(throwable, nextAttemptSettings.getRandomizedRetryDelay()); + tracer.attemptFailedDuration( + throwable, nextAttemptSettings.getRandomizedRetryDelayDuration()); attemptSettings = nextAttemptSettings; setAttemptResult(throwable, response, true); // a new attempt will be (must be) scheduled by an external executor diff --git a/gax-java/gax/src/main/java/com/google/api/gax/retrying/DirectRetryingExecutor.java b/gax-java/gax/src/main/java/com/google/api/gax/retrying/DirectRetryingExecutor.java index 54b7750ca0..4ad2d27daa 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/retrying/DirectRetryingExecutor.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/retrying/DirectRetryingExecutor.java @@ -36,7 +36,6 @@ import java.io.InterruptedIOException; import java.nio.channels.ClosedByInterruptException; import java.util.concurrent.Callable; -import org.threeten.bp.Duration; /** * The retry executor which executes attempts in the current thread, potentially causing the current @@ -99,7 +98,7 @@ public RetryingFuture createFuture( public ApiFuture submit(RetryingFuture retryingFuture) { while (!retryingFuture.isDone()) { try { - sleep(retryingFuture.getAttemptSettings().getRandomizedRetryDelay()); + sleep(retryingFuture.getAttemptSettings().getRandomizedRetryDelayDuration()); ResponseT response = retryingFuture.getCallable().call(); retryingFuture.setAttemptFuture(ApiFutures.immediateFuture(response)); } catch (InterruptedException | InterruptedIOException | ClosedByInterruptException e) { @@ -118,8 +117,8 @@ public ApiFuture submit(RetryingFuture retryingFuture) { * @param delay time to sleep * @throws InterruptedException if any thread has interrupted the current thread */ - protected void sleep(Duration delay) throws InterruptedException { - if (Duration.ZERO.compareTo(delay) < 0) { + protected void sleep(java.time.Duration delay) throws InterruptedException { + if (java.time.Duration.ZERO.compareTo(delay) < 0) { Thread.sleep(delay.toMillis()); } } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/retrying/ExponentialRetryAlgorithm.java b/gax-java/gax/src/main/java/com/google/api/gax/retrying/ExponentialRetryAlgorithm.java index 96aba4a1ec..6a4a892bd2 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/retrying/ExponentialRetryAlgorithm.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/retrying/ExponentialRetryAlgorithm.java @@ -34,7 +34,6 @@ import com.google.api.core.ApiClock; import com.google.api.core.InternalApi; import java.util.concurrent.ThreadLocalRandom; -import org.threeten.bp.Duration; /** * The timed retry algorithm which uses jittered exponential backoff factor for calculating the next @@ -69,9 +68,9 @@ public ExponentialRetryAlgorithm(RetrySettings globalSettings, ApiClock clock) { public TimedAttemptSettings createFirstAttempt() { return TimedAttemptSettings.newBuilder() .setGlobalSettings(globalSettings) - .setRetryDelay(Duration.ZERO) - .setRpcTimeout(getInitialTimeout(globalSettings)) - .setRandomizedRetryDelay(Duration.ZERO) + .setRetryDelayDuration(java.time.Duration.ZERO) + .setRpcTimeoutDuration(getInitialTimeout(globalSettings)) + .setRandomizedRetryDelayDuration(java.time.Duration.ZERO) .setAttemptCount(0) .setOverallAttemptCount(0) .setFirstAttemptStartTimeNanos(clock.nanoTime()) @@ -99,9 +98,9 @@ public TimedAttemptSettings createFirstAttempt(RetryingContext context) { // Attempts created using the TimedAttemptSettings built here will use these // retrySettings, but a new call will not (unless overridden again). .setGlobalSettings(retrySettings) - .setRpcTimeout(getInitialTimeout(retrySettings)) - .setRetryDelay(Duration.ZERO) - .setRandomizedRetryDelay(Duration.ZERO) + .setRpcTimeoutDuration(getInitialTimeout(retrySettings)) + .setRetryDelayDuration(java.time.Duration.ZERO) + .setRandomizedRetryDelayDuration(java.time.Duration.ZERO) .setAttemptCount(0) .setOverallAttemptCount(0) .setFirstAttemptStartTimeNanos(clock.nanoTime()) @@ -125,30 +124,35 @@ public TimedAttemptSettings createNextAttempt(TimedAttemptSettings previousSetti // attempt #1 - use initialRetryDelay; // attempt #2+ - use the calculated value (i.e. the following if statement is true only // if we are about to calculate the value for the upcoming 2nd+ attempt). - long newRetryDelay = settings.getInitialRetryDelay().toMillis(); + long newRetryDelay = settings.getInitialRetryDelayDuration().toMillis(); if (previousSettings.getAttemptCount() > 0) { newRetryDelay = - (long) (settings.getRetryDelayMultiplier() * previousSettings.getRetryDelay().toMillis()); - newRetryDelay = Math.min(newRetryDelay, settings.getMaxRetryDelay().toMillis()); + (long) + (settings.getRetryDelayMultiplier() + * previousSettings.getRetryDelayDuration().toMillis()); + newRetryDelay = Math.min(newRetryDelay, settings.getMaxRetryDelayDuration().toMillis()); } - Duration randomDelay = Duration.ofMillis(nextRandomLong(newRetryDelay)); + java.time.Duration randomDelay = java.time.Duration.ofMillis(nextRandomLong(newRetryDelay)); // The rpc timeout is determined as follows: // attempt #0 - use the initialRpcTimeout; // attempt #1+ - use the calculated value, or the time remaining in totalTimeout if the // calculated value would exceed the totalTimeout. long newRpcTimeout = - (long) (settings.getRpcTimeoutMultiplier() * previousSettings.getRpcTimeout().toMillis()); - newRpcTimeout = Math.min(newRpcTimeout, settings.getMaxRpcTimeout().toMillis()); + (long) + (settings.getRpcTimeoutMultiplier() + * previousSettings.getRpcTimeoutDuration().toMillis()); + newRpcTimeout = Math.min(newRpcTimeout, settings.getMaxRpcTimeoutDuration().toMillis()); // The totalTimeout could be zero if a callable is only using maxAttempts to limit retries. // If set, calculate time remaining in the totalTimeout since the start, taking into account the // next attempt's delay, in order to truncate the RPC timeout should it exceed the totalTimeout. - if (!settings.getTotalTimeout().isZero()) { - Duration timeElapsed = - Duration.ofNanos(clock.nanoTime()) - .minus(Duration.ofNanos(previousSettings.getFirstAttemptStartTimeNanos())); - Duration timeLeft = settings.getTotalTimeout().minus(timeElapsed).minus(randomDelay); + if (!settings.getTotalTimeoutDuration().isZero()) { + java.time.Duration timeElapsed = + java.time.Duration.ofNanos(clock.nanoTime()) + .minus(java.time.Duration.ofNanos(previousSettings.getFirstAttemptStartTimeNanos())); + java.time.Duration timeLeft = + settings.getTotalTimeoutDuration().minus(timeElapsed).minus(randomDelay); // If timeLeft at this point is < 0, the shouldRetry logic will prevent // the attempt from being made as it would exceed the totalTimeout. A negative RPC timeout @@ -159,9 +163,9 @@ public TimedAttemptSettings createNextAttempt(TimedAttemptSettings previousSetti return TimedAttemptSettings.newBuilder() .setGlobalSettings(previousSettings.getGlobalSettings()) - .setRetryDelay(Duration.ofMillis(newRetryDelay)) - .setRpcTimeout(Duration.ofMillis(newRpcTimeout)) - .setRandomizedRetryDelay(randomDelay) + .setRetryDelayDuration(java.time.Duration.ofMillis(newRetryDelay)) + .setRpcTimeoutDuration(java.time.Duration.ofMillis(newRpcTimeout)) + .setRandomizedRetryDelayDuration(randomDelay) .setAttemptCount(previousSettings.getAttemptCount() + 1) .setOverallAttemptCount(previousSettings.getOverallAttemptCount() + 1) .setFirstAttemptStartTimeNanos(previousSettings.getFirstAttemptStartTimeNanos()) @@ -199,7 +203,7 @@ public boolean shouldRetry(TimedAttemptSettings nextAttemptSettings) { RetrySettings globalSettings = nextAttemptSettings.getGlobalSettings(); int maxAttempts = globalSettings.getMaxAttempts(); - Duration totalTimeout = globalSettings.getTotalTimeout(); + java.time.Duration totalTimeout = globalSettings.getTotalTimeoutDuration(); // If total timeout and maxAttempts is not set then do not attempt retry. if (totalTimeout.isZero() && maxAttempts == 0) { @@ -209,9 +213,10 @@ public boolean shouldRetry(TimedAttemptSettings nextAttemptSettings) { long totalTimeSpentNanos = clock.nanoTime() - nextAttemptSettings.getFirstAttemptStartTimeNanos() - + nextAttemptSettings.getRandomizedRetryDelay().toNanos(); + + nextAttemptSettings.getRandomizedRetryDelayDuration().toNanos(); - Duration timeLeft = totalTimeout.minus(Duration.ofNanos(totalTimeSpentNanos)); + java.time.Duration timeLeft = + totalTimeout.minus(java.time.Duration.ofNanos(totalTimeSpentNanos)); // Convert time spent to milliseconds to standardize the units being used for // retries. Otherwise, we would be using nanoseconds to determine if retries // should be attempted and milliseconds for retry delays and rpc timeouts @@ -267,13 +272,13 @@ protected long nextRandomLong(long bound) { * Returns the timeout of the first attempt. The initial timeout will be min(initialRpcTimeout, * totalTimeout) if totalTimeout is set. */ - private Duration getInitialTimeout(RetrySettings retrySettings) { + private java.time.Duration getInitialTimeout(RetrySettings retrySettings) { // If the totalTimeout is zero (not set), then retries are capped by the max attempt // number. The first attempt will use the initialRpcTimeout value for RPC timeout. long totalTimeout = retrySettings.getTotalTimeout().toMillis(); return totalTimeout == 0 - ? retrySettings.getInitialRpcTimeout() - : Duration.ofMillis( + ? retrySettings.getInitialRpcTimeoutDuration() + : java.time.Duration.ofMillis( Math.min(retrySettings.getInitialRpcTimeout().toMillis(), totalTimeout)); } } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/retrying/RetrySettings.java b/gax-java/gax/src/main/java/com/google/api/gax/retrying/RetrySettings.java index 12774a81b0..b9c284d70e 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/retrying/RetrySettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/retrying/RetrySettings.java @@ -29,11 +29,14 @@ */ package com.google.api.gax.retrying; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.BetaApi; +import com.google.api.core.ObsoleteApi; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; -import org.threeten.bp.Duration; /** * Holds the parameters for retry or poll logic with jitter, timeout and exponential @@ -65,7 +68,7 @@ * *

Server streaming RPCs interpret RPC timeouts a bit differently. For server streaming RPCs, the * RPC timeout gets converted into a wait timeout {@link - * com.google.api.gax.rpc.ApiCallContext#withStreamWaitTimeout(Duration)}. + * com.google.api.gax.rpc.ApiCallContext#withStreamWaitTimeoutDuration(java.time.Duration)}. * *

In Cloud Client Libraries, Retry and LRO Retry Settings may be configured for each RPC in a * service. These values are chosen by the service teams and may be found by looking at the @@ -78,6 +81,12 @@ public abstract class RetrySettings implements Serializable { private static final long serialVersionUID = 8258475264439710899L; + /** This method is obsolete. Use {@link #getTotalTimeoutDuration()} instead */ + @ObsoleteApi("Use getTotalTimeoutDuration() instead") + public org.threeten.bp.Duration getTotalTimeout() { + return toThreetenDuration(getTotalTimeoutDuration()); + }; + /** * TotalTimeout has ultimate control over how long the logic should keep trying the remote call * until it gives up completely. The higher the total timeout, the more retries and polls can be @@ -91,7 +100,13 @@ public abstract class RetrySettings implements Serializable { * Duration.ZERO} and LROs have a default total timeout value of {@code Duration.ofMillis(300000)} * (5 minutes). */ - public abstract Duration getTotalTimeout(); + public abstract java.time.Duration getTotalTimeoutDuration(); + + /** This method is obsolete. Use {@link #getInitialRetryDelayDuration()} instead */ + @ObsoleteApi("Use getInitialRetryDelayDuration() instead") + public org.threeten.bp.Duration getInitialRetryDelay() { + return toThreetenDuration(getInitialRetryDelayDuration()); + } /** * InitialRetryDelay controls the delay before the first retry/ poll. Subsequent retries and polls @@ -101,7 +116,7 @@ public abstract class RetrySettings implements Serializable { * Duration.ZERO} and LROs have a default initial poll delay value of {@code * Duration.ofMillis(5000)} (5 seconds). */ - public abstract Duration getInitialRetryDelay(); + public abstract java.time.Duration getInitialRetryDelayDuration(); /** * RetryDelayMultiplier controls the change in delay before the next retry or poll. The retry @@ -113,6 +128,12 @@ public abstract class RetrySettings implements Serializable { */ public abstract double getRetryDelayMultiplier(); + /** This method is obsolete. Use {@link #getMaxRetryDelayDuration()} instead */ + @ObsoleteApi("Use getMaxRetryDelayDuration()") + public org.threeten.bp.Duration getMaxRetryDelay() { + return toThreetenDuration(getMaxRetryDelayDuration()); + } + /** * MaxRetryDelay puts a limit on the value of the retry delay, so that the RetryDelayMultiplier * can't increase the retry delay higher than this amount. @@ -121,7 +142,7 @@ public abstract class RetrySettings implements Serializable { * Duration.ZERO} and LROs have a default max poll retry delay value of {@code * Duration.ofMillis(45000)} (45 seconds). */ - public abstract Duration getMaxRetryDelay(); + public abstract java.time.Duration getMaxRetryDelayDuration(); /** * MaxAttempts defines the maximum number of retry attempts to perform. If this value is set to 0, @@ -152,6 +173,12 @@ public abstract class RetrySettings implements Serializable { @VisibleForTesting public abstract boolean isJittered(); + /** This method is obsolete. Use {@link #getInitialRpcTimeoutDuration()} instead */ + @ObsoleteApi("Use getInitialRpcTimeoutDuration() instead") + public final org.threeten.bp.Duration getInitialRpcTimeout() { + return toThreetenDuration(getInitialRpcTimeoutDuration()); + } + /** * InitialRpcTimeout controls the timeout for the initial RPC. Subsequent calls will use this * value adjusted according to the RpcTimeoutMultiplier. RPC Timeout value of {@code @@ -165,7 +192,7 @@ public abstract class RetrySettings implements Serializable { *

If there are no configurations, Retries have the default initial RPC timeout value of {@code * Duration.ZERO}. LRO polling does not use the Initial RPC Timeout value. */ - public abstract Duration getInitialRpcTimeout(); + public abstract java.time.Duration getInitialRpcTimeoutDuration(); /** * RpcTimeoutMultiplier controls the change in RPC timeout. The timeout of the previous call is @@ -176,6 +203,12 @@ public abstract class RetrySettings implements Serializable { */ public abstract double getRpcTimeoutMultiplier(); + /** This method is obsolete. Use {@link #getMaxRpcTimeoutDuration()} instead */ + @ObsoleteApi("Use getMaxRpcTimeoutDuration() instead") + public final org.threeten.bp.Duration getMaxRpcTimeout() { + return toThreetenDuration(getMaxRpcTimeoutDuration()); + } + /** * MaxRpcTimeout puts a limit on the value of the RPC timeout, so that the RpcTimeoutMultiplier * can't increase the RPC timeout higher than this amount. @@ -183,19 +216,19 @@ public abstract class RetrySettings implements Serializable { *

If there are no configurations, Retries have the default Max RPC Timeout value of {@code * Duration.ZERO}. LRO polling does not use the Max RPC Timeout value. */ - public abstract Duration getMaxRpcTimeout(); + public abstract java.time.Duration getMaxRpcTimeoutDuration(); public static Builder newBuilder() { return new AutoValue_RetrySettings.Builder() - .setTotalTimeout(Duration.ZERO) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(java.time.Duration.ZERO) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) .setMaxAttempts(0) .setJittered(true) - .setInitialRpcTimeout(Duration.ZERO) + .setInitialRpcTimeoutDuration(java.time.Duration.ZERO) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(Duration.ZERO); + .setMaxRpcTimeoutDuration(java.time.Duration.ZERO); } public abstract Builder toBuilder(); @@ -207,6 +240,12 @@ public static Builder newBuilder() { @AutoValue.Builder public abstract static class Builder { + /** This method is obsolete. Use {@link #setTotalTimeoutDuration(java.time.Duration)} instead */ + @ObsoleteApi("Use setTotalTimeoutDuration(java.time.Duration) instead") + public final Builder setTotalTimeout(org.threeten.bp.Duration totalTimeout) { + return setTotalTimeoutDuration(toJavaTimeDuration(totalTimeout)); + } + /** * TotalTimeout has ultimate control over how long the logic should keep trying the remote call * until it gives up completely. The higher the total timeout, the more retries and polls can be @@ -220,7 +259,16 @@ public abstract static class Builder { * Duration.ZERO} and LROs have a default total timeout value of {@code * Duration.ofMillis(300000)} (5 minutes). */ - public abstract Builder setTotalTimeout(Duration totalTimeout); + public abstract Builder setTotalTimeoutDuration(java.time.Duration totalTimeout); + + /** + * This method is obsolete. Use {@link #setInitialRetryDelayDuration(java.time.Duration)} + * instead + */ + @ObsoleteApi("Use setInitialRetryDelayDuration(java.time.Duration) instead") + public final Builder setInitialRetryDelay(org.threeten.bp.Duration initialDelay) { + return setInitialRetryDelayDuration(toJavaTimeDuration(initialDelay)); + } /** * InitialRetryDelay controls the delay before the first retry/ poll. Subsequent retries and @@ -230,7 +278,7 @@ public abstract static class Builder { * {@code Duration.ZERO} and LROs have a default initial poll delay value of {@code * Duration.ofMillis(5000)} (5 seconds). */ - public abstract Builder setInitialRetryDelay(Duration initialDelay); + public abstract Builder setInitialRetryDelayDuration(java.time.Duration initialDelay); /** * RetryDelayMultiplier controls the change in delay before the next retry or poll. The retry @@ -242,6 +290,14 @@ public abstract static class Builder { */ public abstract Builder setRetryDelayMultiplier(double multiplier); + /** + * This method is obsolete. Use {@link #setMaxRetryDelayDuration(java.time.Duration)} instead + */ + @ObsoleteApi("Use setMaxRetryDelayDuration(java.time.Duration) instead") + public final Builder setMaxRetryDelay(org.threeten.bp.Duration maxDelay) { + return setMaxRetryDelayDuration(toJavaTimeDuration(maxDelay)); + } + /** * MaxRetryDelay puts a limit on the value of the retry delay, so that the RetryDelayMultiplier * can't increase the retry delay higher than this amount. @@ -250,7 +306,7 @@ public abstract static class Builder { * Duration.ZERO} and LROs have a default max poll retry delay value of {@code * Duration.ofMillis(45000)} (45 seconds). */ - public abstract Builder setMaxRetryDelay(Duration maxDelay); + public abstract Builder setMaxRetryDelayDuration(java.time.Duration maxDelay); /** * MaxAttempts defines the maximum number of retry attempts to perform. If this value is set to @@ -281,6 +337,15 @@ public abstract static class Builder { @VisibleForTesting public abstract Builder setJittered(boolean jittered); + /** + * This method is obsolete. Use {@link #setInitialRpcTimeoutDuration(java.time.Duration)} + * instead + */ + @ObsoleteApi("Use setInitialRpcTimeoutDuration(java.time.Duration) instead") + public final Builder setInitialRpcTimeout(org.threeten.bp.Duration initialTimeout) { + return setInitialRpcTimeoutDuration(toJavaTimeDuration(initialTimeout)); + } + /** * InitialRpcTimeout controls the timeout for the initial RPC. Subsequent calls will use this * value adjusted according to the RpcTimeoutMultiplier. RPC Timeout value of {@code @@ -294,7 +359,7 @@ public abstract static class Builder { *

If there are no configurations, Retries have the default initial RPC timeout value of * {@code Duration.ZERO}. LRO polling does not use the Initial RPC Timeout value. */ - public abstract Builder setInitialRpcTimeout(Duration initialTimeout); + public abstract Builder setInitialRpcTimeoutDuration(java.time.Duration initialTimeout); /** * RpcTimeoutMultiplier controls the change in RPC timeout. The timeout of the previous call is @@ -305,6 +370,14 @@ public abstract static class Builder { */ public abstract Builder setRpcTimeoutMultiplier(double multiplier); + /** + * This method is obsolete. Use {@link #setMaxRpcTimeoutDuration(java.time.Duration)} instead + */ + @ObsoleteApi("Use setMaxRpcTimeoutDuration(java.time.Duration) instead") + public final Builder setMaxRpcTimeout(org.threeten.bp.Duration maxTimeout) { + return setMaxRpcTimeoutDuration(toJavaTimeDuration(maxTimeout)); + } + /** * MaxRpcTimeout puts a limit on the value of the RPC timeout, so that the RpcTimeoutMultiplier * can't increase the RPC timeout higher than this amount. @@ -312,7 +385,13 @@ public abstract static class Builder { *

If there are no configurations, Retries have the default Max RPC Timeout value of {@code * Duration.ZERO}. LRO polling does not use the Max RPC Timeout value. */ - public abstract Builder setMaxRpcTimeout(Duration maxTimeout); + public abstract Builder setMaxRpcTimeoutDuration(java.time.Duration maxTimeout); + + /** This method is obsolete. Use {@link #getTotalTimeoutDuration()} instead */ + @ObsoleteApi("Use getTotalTimeoutDuration() instead") + public final org.threeten.bp.Duration getTotalTimeout() { + return toThreetenDuration(getTotalTimeoutDuration()); + } /** * TotalTimeout has ultimate control over how long the logic should keep trying the remote call @@ -327,7 +406,13 @@ public abstract static class Builder { * Duration.ZERO} and LROs have a default total timeout value of {@code * Duration.ofMillis(300000)} (5 minutes). */ - public abstract Duration getTotalTimeout(); + public abstract java.time.Duration getTotalTimeoutDuration(); + + /** This method is obsolete. Use {@link #getInitialRetryDelayDuration()} instead */ + @ObsoleteApi("Use getInitialRetryDelayDuration() instead") + public final org.threeten.bp.Duration getInitialRetryDelay() { + return toThreetenDuration(getInitialRetryDelayDuration()); + } /** * InitialRetryDelay controls the delay before the first retry/ poll. Subsequent retries and @@ -337,7 +422,7 @@ public abstract static class Builder { * {@code Duration.ZERO} and LROs have a default initial poll delay value of {@code * Duration.ofMillis(5000)} (5 seconds). */ - public abstract Duration getInitialRetryDelay(); + public abstract java.time.Duration getInitialRetryDelayDuration(); /** * RetryDelayMultiplier controls the change in delay before the next retry or poll. The retry @@ -374,6 +459,12 @@ public abstract static class Builder { */ public abstract boolean isJittered(); + /** This method is obsolete. Use {@link #getMaxRetryDelayDuration()} instead */ + @ObsoleteApi("Use getMaxRetryDelayDuration() instead") + public final org.threeten.bp.Duration getMaxRetryDelay() { + return toThreetenDuration(getMaxRetryDelayDuration()); + } + /** * MaxRetryDelay puts a limit on the value of the retry delay, so that the RetryDelayMultiplier * can't increase the retry delay higher than this amount. @@ -382,7 +473,13 @@ public abstract static class Builder { * Duration.ZERO} and LROs have a default max poll retry delay value of {@code * Duration.ofMillis(45000)} (45 seconds). */ - public abstract Duration getMaxRetryDelay(); + public abstract java.time.Duration getMaxRetryDelayDuration(); + + /** This method is obsolete. Use {@link #getInitialRpcTimeoutDuration()} instead */ + @ObsoleteApi("Use getInitialRpcTimeoutDuration() instead") + public final org.threeten.bp.Duration getInitialRpcTimeout() { + return toThreetenDuration(getInitialRpcTimeoutDuration()); + } /** * InitialRpcTimeout controls the timeout for the initial RPC. Subsequent calls will use this @@ -397,7 +494,7 @@ public abstract static class Builder { *

If there are no configurations, Retries have the default initial RPC timeout value of * {@code Duration.ZERO}. LRO polling does not use the Initial RPC Timeout value. */ - public abstract Duration getInitialRpcTimeout(); + public abstract java.time.Duration getInitialRpcTimeoutDuration(); /** * RpcTimeoutMultiplier controls the change in RPC timeout. The timeout of the previous call is @@ -408,6 +505,12 @@ public abstract static class Builder { */ public abstract double getRpcTimeoutMultiplier(); + /** This method is obsolete. Use {@link #getMaxRpcTimeoutDuration()} instead */ + @ObsoleteApi("Use getMaxRpcTimeoutDuration() instead") + public final org.threeten.bp.Duration getMaxRpcTimeout() { + return toThreetenDuration(getMaxRpcTimeoutDuration()); + } + /** * MaxRpcTimeout puts a limit on the value of the RPC timeout, so that the RpcTimeoutMultiplier * can't increase the RPC timeout higher than this amount. @@ -415,7 +518,14 @@ public abstract static class Builder { *

If there are no configurations, Retries have the default Max RPC Timeout value of {@code * Duration.ZERO}. LRO polling does not use the Max RPC Timeout value. */ - public abstract Duration getMaxRpcTimeout(); + public abstract java.time.Duration getMaxRpcTimeoutDuration(); + + /** This method is obsolete. Use {@link #setLogicalTimeout(java.time.Duration)} instead. */ + @BetaApi + @ObsoleteApi("Use setLogicalTimeout(java.time.Duration) instead") + public Builder setLogicalTimeout(org.threeten.bp.Duration timeout) { + return setLogicalTimeout(toJavaTimeDuration(timeout)); + } /** * Configures the timeout settings with the given timeout such that the logical call will take @@ -427,36 +537,36 @@ public abstract static class Builder { * setter is respected. */ @BetaApi - public Builder setLogicalTimeout(Duration timeout) { + public Builder setLogicalTimeout(java.time.Duration timeout) { return setRpcTimeoutMultiplier(1) - .setInitialRpcTimeout(timeout) - .setMaxRpcTimeout(timeout) - .setTotalTimeout(timeout); + .setInitialRpcTimeoutDuration(timeout) + .setMaxRpcTimeoutDuration(timeout) + .setTotalTimeoutDuration(timeout); } abstract RetrySettings autoBuild(); public RetrySettings build() { RetrySettings params = autoBuild(); - if (params.getTotalTimeout().toMillis() < 0) { + if (params.getTotalTimeoutDuration().toMillis() < 0) { throw new IllegalStateException("total timeout must not be negative"); } - if (params.getInitialRetryDelay().toMillis() < 0) { + if (params.getInitialRetryDelayDuration().toMillis() < 0) { throw new IllegalStateException("initial retry delay must not be negative"); } if (params.getRetryDelayMultiplier() < 1.0) { throw new IllegalStateException("retry delay multiplier must be at least 1"); } - if (params.getMaxRetryDelay().compareTo(params.getInitialRetryDelay()) < 0) { + if (params.getMaxRetryDelayDuration().compareTo(params.getInitialRetryDelayDuration()) < 0) { throw new IllegalStateException("max retry delay must not be shorter than initial delay"); } if (params.getMaxAttempts() < 0) { throw new IllegalStateException("max attempts must be non-negative"); } - if (params.getInitialRpcTimeout().toMillis() < 0) { + if (params.getInitialRpcTimeoutDuration().toMillis() < 0) { throw new IllegalStateException("initial rpc timeout must not be negative"); } - if (params.getMaxRpcTimeout().compareTo(params.getInitialRpcTimeout()) < 0) { + if (params.getMaxRpcTimeoutDuration().compareTo(params.getInitialRpcTimeoutDuration()) < 0) { throw new IllegalStateException("max rpc timeout must not be shorter than initial timeout"); } if (params.getRpcTimeoutMultiplier() < 1.0) { @@ -466,28 +576,28 @@ public RetrySettings build() { } public RetrySettings.Builder merge(RetrySettings.Builder newSettings) { - if (newSettings.getTotalTimeout() != null) { - setTotalTimeout(newSettings.getTotalTimeout()); + if (newSettings.getTotalTimeoutDuration() != null) { + setTotalTimeoutDuration(newSettings.getTotalTimeoutDuration()); } - if (newSettings.getInitialRetryDelay() != null) { - setInitialRetryDelay(newSettings.getInitialRetryDelay()); + if (newSettings.getInitialRetryDelayDuration() != null) { + setInitialRetryDelayDuration(newSettings.getInitialRetryDelayDuration()); } if (newSettings.getRetryDelayMultiplier() >= 1) { setRetryDelayMultiplier(newSettings.getRetryDelayMultiplier()); } - if (newSettings.getMaxRetryDelay() != null) { - setMaxRetryDelay(newSettings.getMaxRetryDelay()); + if (newSettings.getMaxRetryDelayDuration() != null) { + setMaxRetryDelayDuration(newSettings.getMaxRetryDelayDuration()); } setMaxAttempts(newSettings.getMaxAttempts()); setJittered(newSettings.isJittered()); - if (newSettings.getInitialRpcTimeout() != null) { - setInitialRpcTimeout(newSettings.getInitialRpcTimeout()); + if (newSettings.getInitialRpcTimeoutDuration() != null) { + setInitialRpcTimeoutDuration(newSettings.getInitialRpcTimeoutDuration()); } if (newSettings.getRpcTimeoutMultiplier() >= 1) { setRpcTimeoutMultiplier(newSettings.getRpcTimeoutMultiplier()); } - if (newSettings.getMaxRpcTimeout() != null) { - setMaxRpcTimeout(newSettings.getMaxRpcTimeout()); + if (newSettings.getMaxRpcTimeoutDuration() != null) { + setMaxRpcTimeoutDuration(newSettings.getMaxRpcTimeoutDuration()); } return this; } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/retrying/ScheduledRetryingExecutor.java b/gax-java/gax/src/main/java/com/google/api/gax/retrying/ScheduledRetryingExecutor.java index b6ee0a0c19..c796ebd090 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/retrying/ScheduledRetryingExecutor.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/retrying/ScheduledRetryingExecutor.java @@ -115,7 +115,7 @@ public ApiFuture submit(RetryingFuture retryingFuture) { ListenableFuture attemptFuture = scheduler.schedule( retryingFuture.getCallable(), - retryingFuture.getAttemptSettings().getRandomizedRetryDelay().toMillis(), + retryingFuture.getAttemptSettings().getRandomizedRetryDelayDuration().toMillis(), TimeUnit.MILLISECONDS); return new ListenableFutureToApiFuture<>(attemptFuture); } catch (RejectedExecutionException e) { diff --git a/gax-java/gax/src/main/java/com/google/api/gax/retrying/TimedAttemptSettings.java b/gax-java/gax/src/main/java/com/google/api/gax/retrying/TimedAttemptSettings.java index 2f9028a2ef..7b6a09b685 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/retrying/TimedAttemptSettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/retrying/TimedAttemptSettings.java @@ -29,9 +29,12 @@ */ package com.google.api.gax.retrying; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.ApiClock; +import com.google.api.core.ObsoleteApi; import com.google.auto.value.AutoValue; -import org.threeten.bp.Duration; /** Timed attempt execution settings. Defines time-specific properties of a retry attempt. */ @AutoValue @@ -40,20 +43,38 @@ public abstract class TimedAttemptSettings { /** Returns global (attempt-independent) retry settings. */ public abstract RetrySettings getGlobalSettings(); + /** This method is obsolete. Use {@link #getRetryDelayDuration()} instead */ + @ObsoleteApi("Use getRetryDelayDuration() instead") + public final org.threeten.bp.Duration getRetryDelay() { + return toThreetenDuration(getRetryDelayDuration()); + } + /** * Returns the calculated retry delay. Note that the actual delay used for retry scheduling may be * different (randomized, based on this value). */ - public abstract Duration getRetryDelay(); + public abstract java.time.Duration getRetryDelayDuration(); + + /** This method is obsolete. Use {@link #getRpcTimeoutDuration()} instead */ + @ObsoleteApi("Use getRpcTimeoutDuration() instead") + public final org.threeten.bp.Duration getRpcTimeout() { + return toThreetenDuration(getRpcTimeoutDuration()); + } /** Returns rpc timeout used for this attempt. */ - public abstract Duration getRpcTimeout(); + public abstract java.time.Duration getRpcTimeoutDuration(); + + /** This method is obsolete. Use {@link #getRandomizedRetryDelayDuration()} instead */ + @ObsoleteApi("Use getRandomizedRetryDelayDuration() instead") + public final org.threeten.bp.Duration getRandomizedRetryDelay() { + return toThreetenDuration(getRandomizedRetryDelayDuration()); + } /** * Returns randomized attempt delay. By default this value is calculated based on the {@code * retryDelay} value, and is used as the actual attempt execution delay. */ - public abstract Duration getRandomizedRetryDelay(); + public abstract java.time.Duration getRandomizedRetryDelayDuration(); /** * The attempt count. It is a zero-based value (first attempt will have this value set to 0). For @@ -85,20 +106,41 @@ public abstract static class Builder { /** Sets global (attempt-independent) retry settings. */ public abstract Builder setGlobalSettings(RetrySettings value); + /** This method is obsolete. Use {@link #setRetryDelayDuration(java.time.Duration)} instead. */ + @ObsoleteApi("Use setRetryDelayDuration(java.time.Duration) instead") + public final Builder setRetryDelay(org.threeten.bp.Duration value) { + return setRetryDelayDuration(toJavaTimeDuration(value)); + } + /** * Sets the calculated retry delay. Note that the actual delay used for retry scheduling may be * different (randomized, based on this value). */ - public abstract Builder setRetryDelay(Duration value); + public abstract Builder setRetryDelayDuration(java.time.Duration value); + + /** This method is obsolete. Use {@link #setRpcTimeoutDuration(java.time.Duration)} instead. */ + @ObsoleteApi("Use setRpcTimeoutDuration(java.time.Duration) instead") + public final Builder setRpcTimeout(org.threeten.bp.Duration value) { + return setRpcTimeoutDuration(toJavaTimeDuration(value)); + } /** Sets rpc timeout used for this attempt. */ - public abstract Builder setRpcTimeout(Duration value); + public abstract Builder setRpcTimeoutDuration(java.time.Duration value); + + /** + * This method is obsolete. Use {@link #setRandomizedRetryDelayDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use setRandomizedRetryDelayDuration(java.time.Duration) instead") + public final Builder setRandomizedRetryDelay(org.threeten.bp.Duration value) { + return setRandomizedRetryDelayDuration(toJavaTimeDuration(value)); + } /** - * Sets randomized attempt delay. By default this value is calculated based on the {@code + * Sets randomized attempt delay. By default, this value is calculated based on the {@code * retryDelay} value, and is used as the actual attempt execution delay. */ - public abstract Builder setRandomizedRetryDelay(Duration value); + public abstract Builder setRandomizedRetryDelayDuration(java.time.Duration value); /** * Set the attempt count. It is a zero-based value (first attempt will have this value set to diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiCallContext.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiCallContext.java index e650564826..4ad517f4b3 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiCallContext.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiCallContext.java @@ -31,6 +31,7 @@ import com.google.api.core.BetaApi; import com.google.api.core.InternalExtensionOnly; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.retrying.RetryingContext; import com.google.api.gax.rpc.StatusCode.Code; @@ -42,7 +43,6 @@ import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * Context for an API call. @@ -66,6 +66,10 @@ public interface ApiCallContext extends RetryingContext { /** Returns a new ApiCallContext with the given Endpoint Context. */ ApiCallContext withEndpointContext(EndpointContext endpointContext); + /** This method is obsolete. Use {@link #withTimeoutDuration(java.time.Duration)} instead. */ + @ObsoleteApi("Use withTimeoutDuration(java.time.Duration) instead") + ApiCallContext withTimeout(@Nullable org.threeten.bp.Duration timeout); + /** * Returns a new ApiCallContext with the given timeout set. * @@ -78,11 +82,23 @@ public interface ApiCallContext extends RetryingContext { *

If a method has default {@link com.google.api.gax.retrying.RetrySettings}, the max attempts * and/or total timeout is still respected when scheduling each RPC attempt. */ - ApiCallContext withTimeout(@Nullable Duration timeout); + ApiCallContext withTimeoutDuration(@Nullable java.time.Duration timeout); + + /** This method is obsolete. Use {@link #getTimeoutDuration()} instead. */ + @Nullable + @ObsoleteApi("Use getTimeoutDuration() instead") + org.threeten.bp.Duration getTimeout(); /** Returns the configured per-RPC timeout. */ @Nullable - Duration getTimeout(); + java.time.Duration getTimeoutDuration(); + + /** + * This method is obsolete. Use {@link #withStreamWaitTimeoutDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use withStreamWaitTimeoutDuration(java.time.Duration) instead") + ApiCallContext withStreamWaitTimeout(@Nullable org.threeten.bp.Duration streamWaitTimeout); /** * Returns a new ApiCallContext with the given stream timeout set. @@ -95,21 +111,33 @@ public interface ApiCallContext extends RetryingContext { * server or connection stalls. When the timeout has been reached, the stream will be closed with * a retryable {@link WatchdogTimeoutException} and a status of {@link StatusCode.Code#ABORTED}. * - *

A value of {@link Duration#ZERO}, disables the streaming wait timeout and a null value will - * use the default in the callable. + *

A value of {@link java.time.Duration#ZERO}, disables the streaming wait timeout and a null + * value will use the default in the callable. * *

Please note that this timeout is best effort and the maximum resolution is configured in - * {@link StubSettings#getStreamWatchdogCheckInterval()}. + * {@link StubSettings#getStreamWatchdogCheckIntervalDuration()}. */ - ApiCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeout); + ApiCallContext withStreamWaitTimeoutDuration(@Nullable java.time.Duration streamWaitTimeout); + + /** This method is obsolete. Use {@link #getStreamWaitTimeoutDuration()} instead. */ + @Nullable + @ObsoleteApi("Use getStreamWaitTimeoutDuration() instead") + org.threeten.bp.Duration getStreamWaitTimeout(); /** * Return the stream wait timeout set for this context. * - * @see #withStreamWaitTimeout(Duration) + * @see #withStreamWaitTimeoutDuration(java.time.Duration) */ @Nullable - Duration getStreamWaitTimeout(); + java.time.Duration getStreamWaitTimeoutDuration(); + + /** + * This method is obsolete. Use {@link #withStreamIdleTimeoutDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use withStreamIdleTimeoutDuration(java.time.Duration) instead") + ApiCallContext withStreamIdleTimeout(@Nullable org.threeten.bp.Duration streamIdleTimeout); /** * Returns a new ApiCallContext with the given stream idle timeout set. @@ -118,27 +146,31 @@ public interface ApiCallContext extends RetryingContext { * amount of timeout that can pass between a message being received by {@link * ResponseObserver#onResponse(Object)} and demand being signaled via {@link * StreamController#request(int)}. Please note that this timeout is best effort and the maximum - * resolution configured in {@link StubSettings#getStreamWatchdogCheckInterval()}. This is useful - * to clean up streams that were partially read but never closed. When the timeout has been + * resolution configured in {@link StubSettings#getStreamWatchdogCheckIntervalDuration()}. This is + * useful to clean up streams that were partially read but never closed. When the timeout has been * reached, the stream will be closed with a nonretryable {@link WatchdogTimeoutException} and a * status of {@link StatusCode.Code#ABORTED}. * - *

A value of {@link Duration#ZERO}, disables the streaming idle timeout and a null value will - * use the default in the callable. + *

A value of {@link java.time.Duration#ZERO}, disables the streaming idle timeout and a null + * value will use the default in the callable. * *

Please note that this timeout is best effort and the maximum resolution is configured in - * {@link StubSettings#getStreamWatchdogCheckInterval()}. + * {@link StubSettings#getStreamWatchdogCheckIntervalDuration()}. */ - ApiCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTimeout); + ApiCallContext withStreamIdleTimeoutDuration(@Nullable java.time.Duration streamIdleTimeout); + + /** This method is obsolete. Use {@link #getStreamIdleTimeoutDuration()} instead. */ + @Nullable + @ObsoleteApi("Use getStreamIdleTimeoutDuration() instead") + org.threeten.bp.Duration getStreamIdleTimeout(); /** * The stream idle timeout set for this context. * - * @see #withStreamIdleTimeout(Duration) + * @see #withStreamIdleTimeoutDuration(java.time.Duration) */ @Nullable - Duration getStreamIdleTimeout(); - + java.time.Duration getStreamIdleTimeoutDuration(); /** * The {@link ApiTracer} that was previously set for this context. * @@ -193,7 +225,7 @@ public interface ApiCallContext extends RetryingContext { * } * * Setting a logical call timeout for the context can be done similarly with {@link - * RetrySettings.Builder#setLogicalTimeout(Duration timeout)}. + * RetrySettings.Builder#setLogicalTimeout(java.time.Duration timeout)}. * *

Example usage: * diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/AttemptCallable.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/AttemptCallable.java index 6b419f1d49..1fb461c5bb 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/AttemptCallable.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/AttemptCallable.java @@ -35,7 +35,6 @@ import com.google.api.gax.retrying.RetryingFuture; import com.google.common.base.Preconditions; import java.util.concurrent.Callable; -import org.threeten.bp.Duration; /** * A callable representing an attempt to make an RPC call. This class is used from {@link @@ -70,9 +69,9 @@ public ResponseT call() { try { // Set the RPC timeout if the caller did not provide their own. - Duration rpcTimeout = externalFuture.getAttemptSettings().getRpcTimeout(); - if (!rpcTimeout.isZero() && callContext.getTimeout() == null) { - callContext = callContext.withTimeout(rpcTimeout); + java.time.Duration rpcTimeout = externalFuture.getAttemptSettings().getRpcTimeoutDuration(); + if (!rpcTimeout.isZero() && callContext.getTimeoutDuration() == null) { + callContext = callContext.withTimeoutDuration(rpcTimeout); } externalFuture.setAttemptFuture(new NonCancellableFuture()); diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/BatcherFactory.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/BatcherFactory.java index 8ac8093998..e324a21760 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/BatcherFactory.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/BatcherFactory.java @@ -113,7 +113,7 @@ private ThresholdBatcher> createBatcher(PartitionKey return ThresholdBatcher.>newBuilder() .setThresholds(getThresholds(batchingSettings)) .setExecutor(executor) - .setMaxDelay(batchingSettings.getDelayThreshold()) + .setMaxDelayDuration(batchingSettings.getDelayThresholdDuration()) .setReceiver(processor) .setFlowController(batchingFlowController) .setBatchMerger(new BatchMergerImpl()) diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/Callables.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/Callables.java index b1f4b51d6a..aad0d894ca 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/Callables.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/Callables.java @@ -105,7 +105,8 @@ private static ScheduledRetryingExecutor getRetryingExecu settings = settings .toBuilder() - .setSimpleTimeoutNoRetries(settings.getRetrySettings().getTotalTimeout()) + .setSimpleTimeoutNoRetriesDuration( + settings.getRetrySettings().getTotalTimeoutDuration()) .build(); } @@ -129,7 +130,8 @@ public static ServerStreamingCallable settings = settings .toBuilder() - .setSimpleTimeoutNoRetries(settings.getRetrySettings().getTotalTimeout()) + .setSimpleTimeoutNoRetriesDuration( + settings.getRetrySettings().getTotalTimeoutDuration()) .build(); } @@ -156,8 +158,8 @@ public static ServerStreamingCallable callable.withDefaultCallContext( clientContext .getDefaultCallContext() - .withStreamIdleTimeout(callSettings.getIdleTimeout()) - .withStreamWaitTimeout(callSettings.getWaitTimeout())); + .withStreamIdleTimeoutDuration(callSettings.getIdleTimeoutDuration()) + .withStreamWaitTimeoutDuration(callSettings.getWaitTimeoutDuration())); return callable; } @@ -272,6 +274,7 @@ private static boolean areRetriesDisabled( Collection retryableCodes, RetrySettings retrySettings) { return retrySettings.getMaxAttempts() == 1 || retryableCodes.isEmpty() - || (retrySettings.getMaxAttempts() == 0 && retrySettings.getTotalTimeout().isZero()); + || (retrySettings.getMaxAttempts() == 0 + && retrySettings.getTotalTimeoutDuration().isZero()); } } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/CheckingAttemptCallable.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/CheckingAttemptCallable.java index 17670a5e7a..6e307d1f81 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/CheckingAttemptCallable.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/CheckingAttemptCallable.java @@ -35,7 +35,6 @@ import com.google.api.gax.retrying.RetryingFuture; import com.google.common.base.Preconditions; import java.util.concurrent.Callable; -import org.threeten.bp.Duration; /** * A callable representing an attempt to check the status of something by issuing a call to a @@ -66,9 +65,9 @@ public ResponseT call() { ApiCallContext callContext = originalCallContext; try { - Duration rpcTimeout = externalFuture.getAttemptSettings().getRpcTimeout(); + java.time.Duration rpcTimeout = externalFuture.getAttemptSettings().getRpcTimeoutDuration(); if (!rpcTimeout.isZero()) { - callContext = callContext.withTimeout(rpcTimeout); + callContext = callContext.withTimeoutDuration(rpcTimeout); } externalFuture.setAttemptFuture(new NonCancellableFuture()); diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java index 26cf63eb85..09c05b7838 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java @@ -29,10 +29,14 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.client.util.Strings; import com.google.api.core.ApiClock; import com.google.api.core.BetaApi; import com.google.api.core.NanoClock; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.ExecutorAsBackgroundResource; import com.google.api.gax.core.ExecutorProvider; @@ -56,7 +60,6 @@ import java.util.concurrent.ScheduledExecutorService; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * Encapsulates client state, including executor, credentials, and transport channel. @@ -97,8 +100,15 @@ public abstract class ClientContext { @Nullable public abstract Watchdog getStreamWatchdog(); + /** This method is obsolete. Use {@link #getStreamWatchdogCheckIntervalDuration()} instead. */ + @Nonnull + @ObsoleteApi("Use getStreamWatchdogCheckIntervalDuration() instead") + public final org.threeten.bp.Duration getStreamWatchdogCheckInterval() { + return toThreetenDuration(getStreamWatchdogCheckIntervalDuration()); + } + @Nonnull - public abstract Duration getStreamWatchdogCheckInterval(); + public abstract java.time.Duration getStreamWatchdogCheckIntervalDuration(); @Nullable public abstract String getUniverseDomain(); @@ -133,7 +143,7 @@ public static Builder newBuilder() { .setInternalHeaders(Collections.emptyMap()) .setClock(NanoClock.getDefaultClock()) .setStreamWatchdog(null) - .setStreamWatchdogCheckInterval(Duration.ZERO) + .setStreamWatchdogCheckIntervalDuration(java.time.Duration.ZERO) .setTracerFactory(BaseApiTracerFactory.getInstance()) .setQuotaProjectId(null) .setGdchApiAudience(null) @@ -238,7 +248,8 @@ public static ClientContext create(StubSettings settings) throws IOException { if (watchdogProvider != null) { if (watchdogProvider.needsCheckInterval()) { watchdogProvider = - watchdogProvider.withCheckInterval(settings.getStreamWatchdogCheckInterval()); + watchdogProvider.withCheckIntervalDuration( + settings.getStreamWatchdogCheckIntervalDuration()); } if (watchdogProvider.needsClock()) { watchdogProvider = watchdogProvider.withClock(clock); @@ -274,7 +285,7 @@ public static ClientContext create(StubSettings settings) throws IOException { .setEndpoint(settings.getEndpoint()) .setQuotaProjectId(settings.getQuotaProjectId()) .setStreamWatchdog(watchdog) - .setStreamWatchdogCheckInterval(settings.getStreamWatchdogCheckInterval()) + .setStreamWatchdogCheckIntervalDuration(settings.getStreamWatchdogCheckIntervalDuration()) .setTracerFactory(settings.getTracerFactory()) .setEndpointContext(endpointContext) .build(); @@ -345,7 +356,16 @@ public abstract static class Builder { public abstract Builder setStreamWatchdog(Watchdog watchdog); - public abstract Builder setStreamWatchdogCheckInterval(Duration duration); + /** + * This method is obsolete. Use {@link + * #setStreamWatchdogCheckIntervalDuration(java.time.Duration)} instead. + */ + @ObsoleteApi("Use setStreamWatchdogCheckIntervalDuration(java.time.Duration) instead") + public final Builder setStreamWatchdogCheckInterval(org.threeten.bp.Duration duration) { + return setStreamWatchdogCheckIntervalDuration(toJavaTimeDuration(duration)); + } + + public abstract Builder setStreamWatchdogCheckIntervalDuration(java.time.Duration duration); /** * Set the {@link ApiTracerFactory} that will be used to generate traces for operations. diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java index 25929756f5..b5e54484dd 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java @@ -29,8 +29,11 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + import com.google.api.core.ApiClock; import com.google.api.core.ApiFunction; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.CredentialsProvider; import com.google.api.gax.core.ExecutorProvider; import com.google.common.base.MoreObjects; @@ -38,7 +41,6 @@ import java.util.concurrent.Executor; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * A base settings class to configure a client class. @@ -110,11 +112,18 @@ public final WatchdogProvider getWatchdogProvider() { return stubSettings.getStreamWatchdogProvider(); } + /** This method is obsolete. Use {@link #getWatchdogCheckIntervalDuration()} instead. */ @Nonnull - public final Duration getWatchdogCheckInterval() { + @ObsoleteApi("Use getWatchdogCheckIntervalDuration() instead") + public final org.threeten.bp.Duration getWatchdogCheckInterval() { return stubSettings.getStreamWatchdogCheckInterval(); } + @Nonnull + public final java.time.Duration getWatchdogCheckIntervalDuration() { + return stubSettings.getStreamWatchdogCheckIntervalDuration(); + } + /** Gets the GDCH API audience that was previously set in this Builder */ public final String getGdchApiAudience() { return stubSettings.getGdchApiAudience(); @@ -267,8 +276,17 @@ public B setWatchdogProvider(@Nullable WatchdogProvider watchdogProvider) { return self(); } - public B setWatchdogCheckInterval(@Nullable Duration checkInterval) { - stubSettings.setStreamWatchdogCheckInterval(checkInterval); + /** + * This method is obsolete. Use {@link #setWatchdogCheckIntervalDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use setWatchdogCheckIntervalDuration(java.time.Duration) instead") + public B setWatchdogCheckInterval(@Nullable org.threeten.bp.Duration checkInterval) { + return setWatchdogCheckIntervalDuration(toJavaTimeDuration(checkInterval)); + } + + public B setWatchdogCheckIntervalDuration(@Nullable java.time.Duration checkInterval) { + stubSettings.setStreamWatchdogCheckIntervalDuration(checkInterval); return self(); } @@ -346,11 +364,18 @@ public WatchdogProvider getWatchdogProvider() { return stubSettings.getStreamWatchdogProvider(); } + /** This method is obsolete. Use {@link #getWatchdogCheckIntervalDuration()} instead */ @Nullable - public Duration getWatchdogCheckInterval() { + @ObsoleteApi("Use getWatchdogCheckIntervalDuration() instead") + public org.threeten.bp.Duration getWatchdogCheckInterval() { return stubSettings.getStreamWatchdogCheckInterval(); } + @Nullable + public java.time.Duration getWatchdogCheckIntervalDuration() { + return stubSettings.getStreamWatchdogCheckIntervalDuration(); + } + /** Gets the GDCH API audience that was previously set in this Builder */ @Nullable public String getGdchApiAudience() { @@ -378,7 +403,7 @@ public String toString() { .add("endpoint", getEndpoint()) .add("quotaProjectId", getQuotaProjectId()) .add("watchdogProvider", getWatchdogProvider()) - .add("watchdogCheckInterval", getWatchdogCheckInterval()) + .add("watchdogCheckInterval", getWatchdogCheckIntervalDuration()) .add("gdchApiAudience", getGdchApiAudience()) .toString(); } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/FixedWatchdogProvider.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/FixedWatchdogProvider.java index a1fd245b5f..170e820c03 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/FixedWatchdogProvider.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/FixedWatchdogProvider.java @@ -31,10 +31,11 @@ import com.google.api.core.ApiClock; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; +import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * A watchdog provider which always returns the same watchdog instance provided to the provider @@ -70,8 +71,15 @@ public boolean needsCheckInterval() { return false; } + /** This method is obsolete. Use {@link #withCheckIntervalDuration(Duration)} instead. */ @Override - public WatchdogProvider withCheckInterval(Duration checkInterval) { + @ObsoleteApi("Use withCheckIntervalDuration(java.time.Duration) instead") + public WatchdogProvider withCheckInterval(org.threeten.bp.Duration checkInterval) { + throw new UnsupportedOperationException("FixedWatchdogProvider doesn't need a checkInterval"); + } + + @Override + public WatchdogProvider withCheckIntervalDuration(java.time.Duration checkInterval) { throw new UnsupportedOperationException("FixedWatchdogProvider doesn't need a checkInterval"); } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/InstantiatingWatchdogProvider.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/InstantiatingWatchdogProvider.java index a069c49c84..5b06f882a3 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/InstantiatingWatchdogProvider.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/InstantiatingWatchdogProvider.java @@ -29,13 +29,15 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + import com.google.api.core.ApiClock; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import com.google.common.base.Preconditions; import java.util.concurrent.ScheduledExecutorService; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * A watchdog provider which instantiates a new provider on every request. @@ -47,7 +49,7 @@ public final class InstantiatingWatchdogProvider implements WatchdogProvider { @Nullable private final ApiClock clock; @Nullable private final ScheduledExecutorService executor; - @Nullable private final Duration checkInterval; + @Nullable private final java.time.Duration checkInterval; public static WatchdogProvider create() { return new InstantiatingWatchdogProvider(null, null, null); @@ -56,7 +58,7 @@ public static WatchdogProvider create() { private InstantiatingWatchdogProvider( @Nullable ApiClock clock, @Nullable ScheduledExecutorService executor, - @Nullable Duration checkInterval) { + @Nullable java.time.Duration checkInterval) { this.clock = clock; this.executor = executor; this.checkInterval = checkInterval; @@ -78,8 +80,17 @@ public boolean needsCheckInterval() { return checkInterval == null; } + /** + * This method is obsolete. Use {@link #withCheckIntervalDuration(java.time.Duration)} instead. + */ + @Override + @ObsoleteApi("Use withCheckIntervalDuration(java.time.Duration) instead") + public WatchdogProvider withCheckInterval(@Nonnull org.threeten.bp.Duration checkInterval) { + return withCheckIntervalDuration(toJavaTimeDuration(checkInterval)); + } + @Override - public WatchdogProvider withCheckInterval(@Nonnull Duration checkInterval) { + public WatchdogProvider withCheckIntervalDuration(@Nonnull java.time.Duration checkInterval) { return new InstantiatingWatchdogProvider( clock, executor, Preconditions.checkNotNull(checkInterval)); } @@ -108,7 +119,7 @@ public Watchdog getWatchdog() { return null; } - return Watchdog.create(clock, checkInterval, executor); + return Watchdog.createDuration(clock, checkInterval, executor); } @Override diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingAttemptCallable.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingAttemptCallable.java index da4b7a75d1..da0c8de632 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingAttemptCallable.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingAttemptCallable.java @@ -208,10 +208,11 @@ public Void call() { ApiCallContext attemptContext = context; - if (!outerRetryingFuture.getAttemptSettings().getRpcTimeout().isZero() - && attemptContext.getTimeout() == null) { + if (!outerRetryingFuture.getAttemptSettings().getRpcTimeoutDuration().isZero() + && attemptContext.getTimeoutDuration() == null) { attemptContext = - attemptContext.withTimeout(outerRetryingFuture.getAttemptSettings().getRpcTimeout()); + attemptContext.withTimeoutDuration( + outerRetryingFuture.getAttemptSettings().getRpcTimeoutDuration()); } attemptContext diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingCallSettings.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingCallSettings.java index 48e5242b80..cbba46485f 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingCallSettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ServerStreamingCallSettings.java @@ -29,6 +29,10 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + +import com.google.api.core.ObsoleteApi; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.retrying.SimpleStreamResumptionStrategy; import com.google.api.gax.retrying.StreamResumptionStrategy; @@ -37,9 +41,9 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; +import java.time.Duration; import java.util.Set; import javax.annotation.Nonnull; -import org.threeten.bp.Duration; /** * A settings class to configure a {@link ServerStreamingCallable}. @@ -51,7 +55,7 @@ * will terminate any stream that has not has seen any demand (via {@link * StreamController#request(int)}) in the configured interval or has not seen a message from the * server in {@code waitTimeout}. To turn off idle checks, set the interval to {@link - * Duration#ZERO}. + * java.time.Duration#ZERO}. * *

Retry configuration allows for the stream to be restarted and resumed. It is composed of 3 * parts: the retryable codes, the retry settings and the stream resumption strategy. The retryable @@ -67,7 +71,7 @@ *

  • RPC timeouts apply to the time interval between caller demanding more responses via {@link * StreamController#request(int)} and the {@link ResponseObserver} receiving the message. *
  • RPC timeouts are best effort and are checked once every {@link - * StubSettings#getStreamWatchdogCheckInterval()}. + * StubSettings#getStreamWatchdogCheckIntervalDuration()}. *
  • Attempt counts are reset as soon as a response is received. This means that max attempts is * the maximum number of failures in a row. *
  • totalTimeout still applies to the entire stream. @@ -80,8 +84,8 @@ public final class ServerStreamingCallSettings @Nonnull private final RetrySettings retrySettings; @Nonnull private final StreamResumptionStrategy resumptionStrategy; - @Nonnull private final Duration idleTimeout; - @Nonnull private final Duration waitTimeout; + @Nonnull private final java.time.Duration idleTimeout; + @Nonnull private final java.time.Duration waitTimeout; private ServerStreamingCallSettings(Builder builder) { this.retryableCodes = ImmutableSet.copyOf(builder.retryableCodes); @@ -118,21 +122,35 @@ public StreamResumptionStrategy getResumptionStrategy() { return resumptionStrategy; } + /** This method is obsolete. Use {@link #getIdleTimeoutDuration()} instead. */ + @Nonnull + @ObsoleteApi("Use getIdleTimeoutDuration() instead") + public org.threeten.bp.Duration getIdleTimeout() { + return toThreetenDuration(getIdleTimeoutDuration()); + } + /** * See the class documentation of {@link ServerStreamingCallSettings} for a description of what * the {@link #idleTimeout} does. */ @Nonnull - public Duration getIdleTimeout() { + public java.time.Duration getIdleTimeoutDuration() { return idleTimeout; } + /** This method is obsolete. Use {@link #getWaitTimeoutDuration()} instead. */ + @Nonnull + @ObsoleteApi("Use getWaitTimeoutDuration() instead") + public org.threeten.bp.Duration getWaitTimeout() { + return toThreetenDuration(getWaitTimeoutDuration()); + } + /** * See the class documentation of {@link ServerStreamingCallSettings} for a description of what * the {@link #waitTimeout} does. */ @Nonnull - public Duration getWaitTimeout() { + public java.time.Duration getWaitTimeoutDuration() { return waitTimeout; } @@ -160,9 +178,9 @@ public static class Builder @Nonnull private RetrySettings.Builder retrySettingsBuilder; @Nonnull private StreamResumptionStrategy resumptionStrategy; - @Nonnull private Duration idleTimeout; + @Nonnull private java.time.Duration idleTimeout; - @Nonnull private Duration waitTimeout; + @Nonnull private java.time.Duration waitTimeout; /** Initialize the builder with default settings */ private Builder() { @@ -170,8 +188,8 @@ private Builder() { this.retrySettingsBuilder = RetrySettings.newBuilder(); this.resumptionStrategy = new SimpleStreamResumptionStrategy<>(); - this.idleTimeout = Duration.ZERO; - this.waitTimeout = Duration.ZERO; + this.idleTimeout = java.time.Duration.ZERO; + this.waitTimeout = java.time.Duration.ZERO; } private Builder(ServerStreamingCallSettings settings) { @@ -242,18 +260,29 @@ public RetrySettings getRetrySettings() { return retrySettingsBuilder.build(); } + /** + * This method is obsolete. Use {@link #setSimpleTimeoutNoRetriesDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use setSimpleTimeoutNoRetriesDuration(java.time.Duration) instead") + public Builder setSimpleTimeoutNoRetries( + @Nonnull org.threeten.bp.Duration timeout) { + return setSimpleTimeoutNoRetriesDuration(toJavaTimeDuration(timeout)); + } + /** Disables retries and sets the overall timeout. */ - public Builder setSimpleTimeoutNoRetries(@Nonnull Duration timeout) { + public Builder setSimpleTimeoutNoRetriesDuration( + @Nonnull java.time.Duration timeout) { setRetryableCodes(); setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(timeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(timeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ZERO) - .setInitialRpcTimeout(timeout) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) + .setInitialRpcTimeoutDuration(timeout) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(timeout) + .setMaxRpcTimeoutDuration(timeout) .setMaxAttempts(1) .build()); @@ -276,30 +305,60 @@ public StreamResumptionStrategy getResumptionStrategy() { return resumptionStrategy; } + /** This method is obsolete. Use {@link #getIdleTimeoutDuration()} instead. */ @Nonnull - public Duration getIdleTimeout() { + @ObsoleteApi("Use getIdleTimeoutDuration() instead") + public org.threeten.bp.Duration getIdleTimeout() { + return toThreetenDuration(getIdleTimeoutDuration()); + } + + @Nonnull + public java.time.Duration getIdleTimeoutDuration() { return idleTimeout; } + /** This method is obsolete. Use {@link #setIdleTimeoutDuration(Duration)} instead. */ + @ObsoleteApi("Use setIdleTimeoutDuration(java.time.Duration) instead") + public Builder setIdleTimeout( + @Nonnull org.threeten.bp.Duration idleTimeout) { + return setIdleTimeoutDuration(toJavaTimeDuration(idleTimeout)); + } + /** * Set how long to wait before considering the stream orphaned by the user and closing it. - * {@link Duration#ZERO} disables the check for abandoned streams. + * {@link java.time.Duration#ZERO} disables the check for abandoned streams. */ - public Builder setIdleTimeout(@Nonnull Duration idleTimeout) { + public Builder setIdleTimeoutDuration( + @Nonnull java.time.Duration idleTimeout) { this.idleTimeout = Preconditions.checkNotNull(idleTimeout); return this; } + /** This method is obsolete. Use {@link #getWaitTimeoutDuration()} instead. */ @Nonnull - public Duration getWaitTimeout() { + @ObsoleteApi("Use getWaitTimeoutDuration() instead") + public org.threeten.bp.Duration getWaitTimeout() { + return toThreetenDuration(getWaitTimeoutDuration()); + } + + @Nonnull + public java.time.Duration getWaitTimeoutDuration() { return waitTimeout; } + /** This method is obsolete. Use {@link #setWaitTimeoutDuration(java.time.Duration)} instead. */ + @ObsoleteApi("Use setWaitTimeoutDuration(java.time.Duration) instead") + public Builder setWaitTimeout( + @Nonnull org.threeten.bp.Duration waitTimeout) { + return setWaitTimeoutDuration(toJavaTimeDuration(waitTimeout)); + } + /** * Set the maximum amount of time to wait for the next message from the server. {@link - * Duration#ZERO} disables the check for abandoned streams. + * java.time.Duration#ZERO} disables the check for abandoned streams. */ - public Builder setWaitTimeout(@Nonnull Duration waitTimeout) { + public Builder setWaitTimeoutDuration( + @Nonnull java.time.Duration waitTimeout) { this.waitTimeout = waitTimeout; return this; } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java index 4dc67c9a2d..daeda4c445 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java @@ -29,11 +29,15 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.ApiClock; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; import com.google.api.core.NanoClock; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.CredentialsProvider; import com.google.api.gax.core.ExecutorProvider; import com.google.api.gax.core.FixedCredentialsProvider; @@ -49,7 +53,6 @@ import java.util.concurrent.Executor; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * A base settings class to configure a client stub class. @@ -74,7 +77,7 @@ public abstract class StubSettings> { private final String quotaProjectId; @Nullable private final String gdchApiAudience; @Nullable private final WatchdogProvider streamWatchdogProvider; - @Nonnull private final Duration streamWatchdogCheckInterval; + @Nonnull private final java.time.Duration streamWatchdogCheckInterval; @Nonnull private final ApiTracerFactory tracerFactory; // Track if deprecated setExecutorProvider is called private boolean deprecatedExecutorProviderSet; @@ -203,8 +206,15 @@ public final WatchdogProvider getStreamWatchdogProvider() { return streamWatchdogProvider; } + /** This method is obsolete. Use {@link #getStreamWatchdogCheckIntervalDuration()} instead. */ @Nonnull - public final Duration getStreamWatchdogCheckInterval() { + @ObsoleteApi("Use getStreamWatchdogCheckIntervalDuration() instead") + public final org.threeten.bp.Duration getStreamWatchdogCheckInterval() { + return toThreetenDuration(getStreamWatchdogCheckIntervalDuration()); + } + + @Nonnull + public final java.time.Duration getStreamWatchdogCheckIntervalDuration() { return streamWatchdogCheckInterval; } @@ -262,7 +272,7 @@ public abstract static class Builder< private String quotaProjectId; @Nullable private String gdchApiAudience; @Nullable private WatchdogProvider streamWatchdogProvider; - @Nonnull private Duration streamWatchdogCheckInterval; + @Nonnull private java.time.Duration streamWatchdogCheckInterval; @Nonnull private ApiTracerFactory tracerFactory; private boolean deprecatedExecutorProviderSet; private String universeDomain; @@ -333,7 +343,7 @@ protected Builder(ClientContext clientContext) { this.clock = NanoClock.getDefaultClock(); this.quotaProjectId = null; this.streamWatchdogProvider = InstantiatingWatchdogProvider.create(); - this.streamWatchdogCheckInterval = Duration.ofSeconds(10); + this.streamWatchdogCheckInterval = java.time.Duration.ofSeconds(10); this.tracerFactory = BaseApiTracerFactory.getInstance(); this.deprecatedExecutorProviderSet = false; this.gdchApiAudience = null; @@ -361,7 +371,7 @@ protected Builder(ClientContext clientContext) { this.clock = clientContext.getClock(); this.streamWatchdogProvider = FixedWatchdogProvider.create(clientContext.getStreamWatchdog()); - this.streamWatchdogCheckInterval = clientContext.getStreamWatchdogCheckInterval(); + this.streamWatchdogCheckInterval = clientContext.getStreamWatchdogCheckIntervalDuration(); this.tracerFactory = clientContext.getTracerFactory(); this.quotaProjectId = getQuotaProjectIdFromClientContext(clientContext); this.gdchApiAudience = clientContext.getGdchApiAudience(); @@ -521,11 +531,20 @@ public B setQuotaProjectId(String quotaProjectId) { return self(); } + /** + * This method is obsolete. Use {@link + * #setStreamWatchdogCheckIntervalDuration(java.time.Duration)} instead. + */ + @ObsoleteApi("Use setStreamWatchdogCheckIntervalDuration(java.time.Duration) instead") + public B setStreamWatchdogCheckInterval(@Nonnull org.threeten.bp.Duration checkInterval) { + return setStreamWatchdogCheckIntervalDuration(toJavaTimeDuration(checkInterval)); + } + /** * Sets how often the {@link Watchdog} will check ongoing streaming RPCs. Defaults to 10 secs. - * Use {@link Duration#ZERO} to disable. + * Use {@link java.time.Duration#ZERO} to disable. */ - public B setStreamWatchdogCheckInterval(@Nonnull Duration checkInterval) { + public B setStreamWatchdogCheckIntervalDuration(@Nonnull java.time.Duration checkInterval) { Preconditions.checkNotNull(checkInterval); this.streamWatchdogCheckInterval = checkInterval; return self(); @@ -621,9 +640,15 @@ public String getQuotaProjectId() { return quotaProjectId; } + /** This method is obsolete. Use {@link #getStreamWatchdogCheckIntervalDuration()} instead */ + @ObsoleteApi("Use getStreamWatchdogCheckIntervalDuration() instead") + public org.threeten.bp.Duration getStreamWatchdogCheckInterval() { + return toThreetenDuration(getStreamWatchdogCheckIntervalDuration()); + } + @Nonnull - public Duration getStreamWatchdogCheckInterval() { - return streamWatchdogCheckInterval; + public java.time.Duration getStreamWatchdogCheckIntervalDuration() { + return Preconditions.checkNotNull(streamWatchdogCheckInterval); } @BetaApi("The surface for tracing is not stable yet and may change in the future.") diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/UnaryCallSettings.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/UnaryCallSettings.java index c8f2811449..f985650a59 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/UnaryCallSettings.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/UnaryCallSettings.java @@ -29,13 +29,15 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + import com.google.api.core.InternalExtensionOnly; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.retrying.RetrySettings; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Set; -import org.threeten.bp.Duration; /** * A base settings class to configure a UnaryCallable. An instance of UnaryCallSettings is not @@ -194,19 +196,29 @@ public UnaryCallSettings.Builder setRetrySettings( return this; } - /** Disables retries and sets the RPC timeout. */ + /** + * This method is obsolete. Use {@link #setSimpleTimeoutNoRetriesDuration(java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use setSimpleTimeoutNoRetriesDuration(java.time.Duration) instead") public UnaryCallSettings.Builder setSimpleTimeoutNoRetries( - Duration timeout) { + org.threeten.bp.Duration timeout) { + return setSimpleTimeoutNoRetriesDuration(toJavaTimeDuration(timeout)); + } + + /** Disables retries and sets the RPC timeout. */ + public UnaryCallSettings.Builder setSimpleTimeoutNoRetriesDuration( + java.time.Duration timeout) { setRetryableCodes(); setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(timeout) - .setInitialRetryDelay(Duration.ZERO) + .setTotalTimeoutDuration(timeout) + .setInitialRetryDelayDuration(java.time.Duration.ZERO) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ZERO) - .setInitialRpcTimeout(timeout) + .setMaxRetryDelayDuration(java.time.Duration.ZERO) + .setInitialRpcTimeoutDuration(timeout) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(timeout) + .setMaxRpcTimeoutDuration(timeout) .setMaxAttempts(1) .build()); return this; diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/Watchdog.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/Watchdog.java index f28bb19dee..69ca5d1eca 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/Watchdog.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/Watchdog.java @@ -29,8 +29,13 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.ApiClock; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.BackgroundResource; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.errorprone.annotations.concurrent.GuardedBy; import java.util.Iterator; @@ -45,7 +50,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; -import org.threeten.bp.Duration; /** * Prevents the streams from hanging indefinitely. This middleware garbage collects idle streams in @@ -71,19 +75,32 @@ public final class Watchdog implements Runnable, BackgroundResource { private final ConcurrentHashMap openStreams = new ConcurrentHashMap<>(); private final ApiClock clock; - private final Duration scheduleInterval; + private final java.time.Duration scheduleInterval; private final ScheduledExecutorService executor; private ScheduledFuture future; - /** returns a Watchdog which is scheduled at the provided interval. */ + /** + * This method is obsolete. Use {@link #createDuration(ApiClock, java.time.Duration, + * ScheduledExecutorService)} instead. + */ + @ObsoleteApi("Use create(ApiClock, java.time.Duration, ScheduledExecutorService) instead") public static Watchdog create( - ApiClock clock, Duration scheduleInterval, ScheduledExecutorService executor) { + ApiClock clock, + org.threeten.bp.Duration scheduleInterval, + ScheduledExecutorService executor) { + return createDuration(clock, toJavaTimeDuration(scheduleInterval), executor); + } + + /** returns a Watchdog which is scheduled at the provided interval. */ + public static Watchdog createDuration( + ApiClock clock, java.time.Duration scheduleInterval, ScheduledExecutorService executor) { Watchdog watchdog = new Watchdog(clock, scheduleInterval, executor); watchdog.start(); return watchdog; } - private Watchdog(ApiClock clock, Duration scheduleInterval, ScheduledExecutorService executor) { + private Watchdog( + ApiClock clock, java.time.Duration scheduleInterval, ScheduledExecutorService executor) { this.clock = Preconditions.checkNotNull(clock, "clock can't be null"); this.scheduleInterval = scheduleInterval; this.executor = executor; @@ -95,11 +112,24 @@ private void start() { this, scheduleInterval.toMillis(), scheduleInterval.toMillis(), TimeUnit.MILLISECONDS); } - /** Wraps the target observer with timing constraints. */ + /** + * This method is obsolete. Use {@link #watchDuration(ResponseObserver, java.time.Duration, + * java.time.Duration)} instead. + */ + @ObsoleteApi( + "Use watchDuration(ResponseObserver, java.time.Duration, java.time.Duration) instead") public ResponseObserver watch( ResponseObserver innerObserver, - @Nonnull Duration waitTimeout, - @Nonnull Duration idleTimeout) { + @Nonnull org.threeten.bp.Duration waitTimeout, + @Nonnull org.threeten.bp.Duration idleTimeout) { + return watchDuration( + innerObserver, toJavaTimeDuration(waitTimeout), toJavaTimeDuration(idleTimeout)); + } + /** Wraps the target observer with timing constraints. */ + public ResponseObserver watchDuration( + ResponseObserver innerObserver, + @Nonnull java.time.Duration waitTimeout, + @Nonnull java.time.Duration idleTimeout) { Preconditions.checkNotNull(innerObserver, "innerObserver can't be null"); Preconditions.checkNotNull(waitTimeout, "waitTimeout can't be null"); Preconditions.checkNotNull(idleTimeout, "idleTimeout can't be null"); @@ -171,6 +201,16 @@ public void close() { shutdown(); } + @VisibleForTesting + java.time.Duration getScheduleIntervalDuration() { + return this.scheduleInterval; + } + + @VisibleForTesting + org.threeten.bp.Duration getScheduleInterval() { + return toThreetenDuration(this.scheduleInterval); + } + enum State { /** Stream has been started, but doesn't have any outstanding requests. */ IDLE, @@ -185,8 +225,8 @@ enum State { class WatchdogStream extends StateCheckingResponseObserver { private final Object lock = new Object(); - private final Duration waitTimeout; - private final Duration idleTimeout; + private final java.time.Duration waitTimeout; + private final java.time.Duration idleTimeout; private boolean hasStarted; private boolean autoAutoFlowControl = true; @@ -208,7 +248,9 @@ class WatchdogStream extends StateCheckingResponseObserver private volatile Throwable error; WatchdogStream( - ResponseObserver responseObserver, Duration waitTimeout, Duration idleTimeout) { + ResponseObserver responseObserver, + java.time.Duration waitTimeout, + java.time.Duration idleTimeout) { this.waitTimeout = waitTimeout; this.idleTimeout = idleTimeout; this.outerResponseObserver = responseObserver; diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogProvider.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogProvider.java index db3fb20bb7..a31fc7b6f4 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogProvider.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogProvider.java @@ -29,10 +29,12 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.ApiClock; +import com.google.api.core.ObsoleteApi; import java.util.concurrent.ScheduledExecutorService; import javax.annotation.Nonnull; -import org.threeten.bp.Duration; public interface WatchdogProvider { boolean needsClock(); @@ -41,7 +43,15 @@ public interface WatchdogProvider { boolean needsCheckInterval(); - WatchdogProvider withCheckInterval(Duration checkInterval); + /** + * This method is obsolete. Use {@link #withCheckIntervalDuration(java.time.Duration)} instead. + */ + @ObsoleteApi("Use withCheckIntervalDuration(java.time.Duration) instead") + WatchdogProvider withCheckInterval(org.threeten.bp.Duration checkInterval); + + default WatchdogProvider withCheckIntervalDuration(java.time.Duration checkInterval) { + return withCheckInterval(toThreetenDuration(checkInterval)); + } boolean needsExecutor(); diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogServerStreamingCallable.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogServerStreamingCallable.java index cc3dfec829..443bf11dd5 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogServerStreamingCallable.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/WatchdogServerStreamingCallable.java @@ -31,7 +31,6 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import org.threeten.bp.Duration; /** * A callable that uses a {@link Watchdog} to monitor streams. @@ -62,10 +61,12 @@ public void call( RequestT request, ResponseObserver responseObserver, ApiCallContext context) { // If the caller never configured the timeouts, disable them - Duration waitTimeout = MoreObjects.firstNonNull(context.getStreamWaitTimeout(), Duration.ZERO); - Duration idleTimeout = MoreObjects.firstNonNull(context.getStreamIdleTimeout(), Duration.ZERO); + java.time.Duration waitTimeout = + MoreObjects.firstNonNull(context.getStreamWaitTimeoutDuration(), java.time.Duration.ZERO); + java.time.Duration idleTimeout = + MoreObjects.firstNonNull(context.getStreamIdleTimeoutDuration(), java.time.Duration.ZERO); - responseObserver = watchdog.watch(responseObserver, waitTimeout, idleTimeout); + responseObserver = watchdog.watchDuration(responseObserver, waitTimeout, idleTimeout); inner.call(request, responseObserver, context); } } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/tracing/ApiTracer.java b/gax-java/gax/src/main/java/com/google/api/gax/tracing/ApiTracer.java index 6143772bac..4407f79a85 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/tracing/ApiTracer.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/tracing/ApiTracer.java @@ -30,7 +30,7 @@ package com.google.api.gax.tracing; import com.google.api.core.InternalApi; -import org.threeten.bp.Duration; +import com.google.api.core.ObsoleteApi; /** * Implementations of this class trace the logical flow of a google cloud client. @@ -108,13 +108,20 @@ default Scope inScope() { /** Add an annotation that the attempt was cancelled by the user. */ default void attemptCancelled() {}; + /** + * This method is obsolete. Use {@link #attemptFailedDuration(Throwable, java.time.Duration)} + * instead. + */ + @ObsoleteApi("Use attemptFailedDuration(Throwable, java.time.Duration) instead") + default void attemptFailed(Throwable error, org.threeten.bp.Duration delay) {}; + /** * Adds an annotation that the attempt failed, but another attempt will be made after the delay. * * @param error the transient error that caused the attempt to fail. * @param delay the amount of time to wait before the next attempt will start. */ - default void attemptFailed(Throwable error, Duration delay) {}; + default void attemptFailedDuration(Throwable error, java.time.Duration delay) {}; /** * Adds an annotation that the attempt failed and that no further attempts will be made because diff --git a/gax-java/gax/src/main/java/com/google/api/gax/tracing/BaseApiTracer.java b/gax-java/gax/src/main/java/com/google/api/gax/tracing/BaseApiTracer.java index 1e542f124d..73ead433ec 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/tracing/BaseApiTracer.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/tracing/BaseApiTracer.java @@ -30,7 +30,7 @@ package com.google.api.gax.tracing; import com.google.api.core.InternalApi; -import org.threeten.bp.Duration; +import com.google.api.core.ObsoleteApi; /** * A base implementation of {@link ApiTracer} that does nothing. With the deprecation of Java 7 @@ -104,7 +104,17 @@ public void attemptCancelled() { } @Override - public void attemptFailed(Throwable error, Duration delay) { + public void attemptFailedDuration(Throwable error, java.time.Duration delay) { + // noop + } + + /** + * This method is obsolete. Use {@link #attemptFailedDuration(Throwable, java.time.Duration)} + * instead. + */ + @Override + @ObsoleteApi("Use attemptFailed(Throwable, java.time.Duration) instead") + public void attemptFailed(Throwable error, org.threeten.bp.Duration delay) { // noop } diff --git a/gax-java/gax/src/main/java/com/google/api/gax/tracing/MetricsTracer.java b/gax-java/gax/src/main/java/com/google/api/gax/tracing/MetricsTracer.java index 237e686896..3de156a562 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/tracing/MetricsTracer.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/tracing/MetricsTracer.java @@ -30,8 +30,11 @@ package com.google.api.gax.tracing; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.rpc.ApiException; import com.google.api.gax.rpc.StatusCode; import com.google.common.annotations.VisibleForTesting; @@ -42,7 +45,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * This class computes generic metrics that can be observed in the lifecycle of an RPC operation. @@ -172,12 +174,22 @@ public void attemptCancelled() { * key. */ @Override - public void attemptFailed(Throwable error, Duration delay) { + public void attemptFailedDuration(Throwable error, java.time.Duration delay) { attributes.put(STATUS_ATTRIBUTE, extractStatus(error)); metricsRecorder.recordAttemptLatency(attemptTimer.elapsed(TimeUnit.MILLISECONDS), attributes); metricsRecorder.recordAttemptCount(1, attributes); } + /** + * This method is obsolete. Use {@link #attemptFailedDuration(Throwable, java.time.Duration)} + * instead. + */ + @Override + @ObsoleteApi("Use attemptFailedDuration(Throwable, java.time.Duration) instead") + public void attemptFailed(Throwable error, org.threeten.bp.Duration delay) { + attemptFailedDuration(error, toJavaTimeDuration(delay)); + } + /** * Adds an annotation that the attempt failed and that no further attempts will be made because * retry limits have been reached. This extracts the error from the throwable and adds it to the diff --git a/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpencensusTracer.java b/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpencensusTracer.java index ea4c5f9039..c9f6b7cfc7 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpencensusTracer.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpencensusTracer.java @@ -29,8 +29,11 @@ */ package com.google.api.gax.tracing; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.rpc.ApiException; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StatusCode.Code; @@ -47,7 +50,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nonnull; -import org.threeten.bp.Duration; /** * Implementation of {@link ApiTracer} that uses OpenCensus. @@ -342,7 +344,7 @@ public void attemptCancelled() { /** {@inheritDoc} */ @Override - public void attemptFailed(Throwable error, Duration delay) { + public void attemptFailedDuration(Throwable error, java.time.Duration delay) { Map attributes = baseAttemptAttributes(); attributes.put("delay ms", AttributeValue.longAttributeValue(delay.toMillis())); populateError(attributes, error); @@ -357,6 +359,16 @@ public void attemptFailed(Throwable error, Duration delay) { lastConnectionId = null; } + /** + * This method is obsolete. Use {@link #attemptFailedDuration(Throwable, java.time.Duration)} + * instead. + */ + @Override + @ObsoleteApi("Use attemptFailedDuration(Throwable, java.time.Duration) instead") + public void attemptFailed(Throwable error, org.threeten.bp.Duration delay) { + attemptFailedDuration(error, toJavaTimeDuration(delay)); + } + /** {@inheritDoc} */ @Override public void attemptFailedRetriesExhausted(Throwable error) { diff --git a/gax-java/gax/src/main/java/com/google/api/gax/util/TimeConversionUtils.java b/gax-java/gax/src/main/java/com/google/api/gax/util/TimeConversionUtils.java new file mode 100644 index 0000000000..d19fa39fc2 --- /dev/null +++ b/gax-java/gax/src/main/java/com/google/api/gax/util/TimeConversionUtils.java @@ -0,0 +1,61 @@ +/* + * Copyright 2023 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.google.api.gax.util; + +public class TimeConversionUtils { + public static java.time.Duration toJavaTimeDuration(org.threeten.bp.Duration source) { + if (source == null) { + return null; + } + return java.time.Duration.ofNanos(source.toNanos()); + } + + public static org.threeten.bp.Duration toThreetenDuration(java.time.Duration source) { + if (source == null) { + return null; + } + return org.threeten.bp.Duration.ofNanos(source.toNanos()); + } + + public static java.time.Instant toJavaTimeInstant(org.threeten.bp.Instant source) { + if (source == null) { + return null; + } + return java.time.Instant.ofEpochMilli(source.toEpochMilli()); + } + + public static org.threeten.bp.Instant toThreetenInstant(java.time.Instant source) { + if (source == null) { + return null; + } + return org.threeten.bp.Instant.ofEpochMilli(source.toEpochMilli()); + } +} diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPolling.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPolling.java index d02ed235da..4bd2b8e5b2 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPolling.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPolling.java @@ -32,7 +32,6 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.google.common.base.Stopwatch; -import java.time.Duration; import java.util.Objects; /** @@ -40,12 +39,12 @@ * timeout is exceeded. Expected usage: * *
    {@code
    - * assertByPolling(Duration.ofSeconds(2), () -> assertThat(...));
    + * assertByPolling(java.time.Duration.ofSeconds(2), () -> assertThat(...));
      * }
    */ class AssertByPolling { - public static void assertByPolling(Duration timeout, Runnable assertion) + public static void assertByPolling(java.time.Duration timeout, Runnable assertion) throws InterruptedException { Objects.requireNonNull(timeout, "Timeout must not be null"); Stopwatch stopwatch = Stopwatch.createStarted(); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPollingTest.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPollingTest.java index 96a7efea66..6a71efceac 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPollingTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/AssertByPollingTest.java @@ -32,7 +32,6 @@ import static com.google.api.gax.batching.AssertByPolling.assertByPolling; import com.google.common.truth.Truth; -import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; @@ -45,7 +44,9 @@ void testFailsWhenTimeoutExceeded() { AssertionError error = Assertions.assertThrows( AssertionError.class, - () -> assertByPolling(Duration.ofNanos(2), () -> Truth.assertThat(1).isAtLeast(2))); + () -> + assertByPolling( + java.time.Duration.ofNanos(2), () -> Truth.assertThat(1).isAtLeast(2))); Throwable cause = error.getCause(); Truth.assertThat(cause).isInstanceOf(AssertionError.class); @@ -63,7 +64,7 @@ void testImmediateSuccessSucceedsRegardlessOfTimeout() throws InterruptedExcepti throw new RuntimeException(ex); } }; - Duration timeout = Duration.ofNanos(0); + java.time.Duration timeout = java.time.Duration.ofNanos(0); assertByPolling(timeout, succeedsAfter1ms); } @@ -79,7 +80,7 @@ void testSucceedsAfterInitialFailure() throws InterruptedException { } }; - Duration timeout = Duration.ofMillis(300); + java.time.Duration timeout = java.time.Duration.ofMillis(300); assertByPolling(timeout, succeedsSecondTime); Truth.assertThat(numFailures.get()).isEqualTo(1); } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/BatcherImplTest.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/BatcherImplTest.java index 6be2f38c3c..3ebcc2c5d0 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/batching/BatcherImplTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/BatcherImplTest.java @@ -34,6 +34,10 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.api.core.ApiFuture; @@ -78,7 +82,6 @@ import org.junit.jupiter.api.Timeout; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; class BatcherImplTest { @@ -93,7 +96,7 @@ class BatcherImplTest { BatchingSettings.newBuilder() .setElementCountThreshold(1000L) .setRequestByteThreshold(1000L) - .setDelayThreshold(Duration.ofSeconds(1000)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1000)) .build(); @AfterEach @@ -130,6 +133,20 @@ void testResultsAreResolvedAfterFlush() throws Exception { @Test void testSendOutstanding() { final AtomicInteger callableCounter = new AtomicInteger(); + ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); + BatchingSettings mockBatchingSettings = mock(BatchingSettings.class); + java.time.Duration mockDelayThresholdDuration = java.time.Duration.ofSeconds(1000L); + when(mockBatchingSettings.getDelayThresholdDuration()).thenReturn(mockDelayThresholdDuration); + when(mockBatchingSettings.getRequestByteThreshold()).thenReturn(1000L); + when(mockBatchingSettings.getElementCountThreshold()).thenReturn(1000L); + when(mockBatchingSettings.getFlowControlSettings()) + .thenReturn(batchingSettings.getFlowControlSettings()); + when(mockExecutor.scheduleWithFixedDelay( + any(Runnable.class), + eq(mockDelayThresholdDuration.toMillis()), + eq(mockDelayThresholdDuration.toMillis()), + any(TimeUnit.class))) + .thenReturn(mock(ScheduledFuture.class)); underTest = new BatcherImpl<>( @@ -143,8 +160,8 @@ public ApiFuture> futureCall( } }, labeledIntList, - batchingSettings, - EXECUTOR); + mockBatchingSettings, + mockExecutor); // Empty Batcher underTest.sendOutstanding(); @@ -155,6 +172,12 @@ public ApiFuture> futureCall( underTest.add(4); underTest.sendOutstanding(); assertThat(callableCounter.get()).isEqualTo(1); + verify(mockExecutor) + .scheduleWithFixedDelay( + any(Runnable.class), + eq(mockDelayThresholdDuration.toMillis()), + eq(mockDelayThresholdDuration.toMillis()), + any(TimeUnit.class)); } /** Element results are resolved after batch is closed. */ @@ -364,7 +387,7 @@ void testWhenThresholdIsDisabled() throws Exception { BatchingSettings.newBuilder() .setElementCountThreshold(null) .setRequestByteThreshold(null) - .setDelayThreshold(null) + .setDelayThresholdDuration(null) .build(); underTest = createDefaultBatcherImpl(settings, null); Future result = underTest.add(2); @@ -376,7 +399,10 @@ void testWhenThresholdIsDisabled() throws Exception { @Test void testWhenDelayThresholdExceeds() throws Exception { BatchingSettings settings = - batchingSettings.toBuilder().setDelayThreshold(Duration.ofMillis(100)).build(); + batchingSettings + .toBuilder() + .setDelayThresholdDuration(java.time.Duration.ofMillis(100)) + .build(); underTest = createDefaultBatcherImpl(settings, null); Future result = underTest.add(6); assertThat(result.isDone()).isFalse(); @@ -408,7 +434,10 @@ public ApiFuture> futureCall( } }; BatchingSettings settings = - batchingSettings.toBuilder().setDelayThreshold(Duration.ofMillis(50)).build(); + batchingSettings + .toBuilder() + .setDelayThresholdDuration(java.time.Duration.ofMillis(50)) + .build(); try (final BatcherImpl> batcherTest = new BatcherImpl<>(SQUARER_BATCHING_DESC_V2, callable, labeledIntList, settings, EXECUTOR)) { @@ -446,7 +475,10 @@ public ApiFuture> futureCall( void testPushCurrentBatchRunnable() throws Exception { long DELAY_TIME = 50L; BatchingSettings settings = - batchingSettings.toBuilder().setDelayThreshold(Duration.ofMillis(DELAY_TIME)).build(); + batchingSettings + .toBuilder() + .setDelayThresholdDuration(java.time.Duration.ofMillis(DELAY_TIME)) + .build(); BatcherImpl> batcher = createDefaultBatcherImpl(settings, null); @@ -824,7 +856,7 @@ void testThrottlingBlocking() throws Exception { .build()); ExecutorService executor = Executors.newFixedThreadPool(2); - ApiCallContext callContext = Mockito.mock(ApiCallContext.class); + ApiCallContext callContext = mock(ApiCallContext.class); ArgumentCaptor> key = ArgumentCaptor.forClass(ApiCallContext.Key.class); ArgumentCaptor value = ArgumentCaptor.forClass(Long.class); @@ -998,7 +1030,7 @@ public ApiFuture futureCall(Object o, ApiCallContext apiCallContext) { Object prototype = new Object(); BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(100L) .setRequestByteThreshold(100L) .setFlowControlSettings(FlowControlSettings.getDefaultInstance()) diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingCallSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingCallSettingsTest.java index 581f35ff6f..2b1e66ad60 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingCallSettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingCallSettingsTest.java @@ -39,7 +39,6 @@ import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class BatchingCallSettingsTest { @@ -47,7 +46,7 @@ class BatchingCallSettingsTest { BatchingSettings.newBuilder() .setElementCountThreshold(10L) .setRequestByteThreshold(20L) - .setDelayThreshold(Duration.ofMillis(5)) + .setDelayThresholdDuration(java.time.Duration.ofMillis(5)) .setFlowControlSettings( FlowControlSettings.newBuilder() .setMaxOutstandingElementCount(100L) @@ -88,7 +87,7 @@ void testBuilderFromSettings() { BatchingCallSettings.Builder> builder = BatchingCallSettings.newBuilder(SQUARER_BATCHING_DESC_V2); RetrySettings retrySettings = - RetrySettings.newBuilder().setTotalTimeout(Duration.ofMinutes(1)).build(); + RetrySettings.newBuilder().setTotalTimeoutDuration(java.time.Duration.ofMinutes(1)).build(); builder .setBatchingSettings(BATCHING_SETTINGS) .setRetryableCodes(StatusCode.Code.UNAVAILABLE, StatusCode.Code.UNAUTHENTICATED) diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingSettingsTest.java new file mode 100644 index 0000000000..69dadb5397 --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/BatchingSettingsTest.java @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.batching; + +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; + +import org.junit.jupiter.api.Test; + +public class BatchingSettingsTest { + + private static final BatchingSettings.Builder SETTINGS_BUILDER = BatchingSettings.newBuilder(); + + @Test + public void testDelayThreshold() { + testDurationMethod( + 123l, + jt -> SETTINGS_BUILDER.setDelayThresholdDuration(jt).build(), + tt -> SETTINGS_BUILDER.setDelayThreshold(tt).build(), + o -> o.getDelayThresholdDuration(), + o -> o.getDelayThreshold()); + } +} diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/FlowControllerTest.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/FlowControllerTest.java index c34a10a5d0..c91b5b17ae 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/batching/FlowControllerTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/FlowControllerTest.java @@ -42,7 +42,6 @@ import com.google.api.gax.batching.FlowController.LimitExceededBehavior; import com.google.common.util.concurrent.SettableFuture; import java.lang.Thread.State; -import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -603,7 +602,8 @@ void testNumberOfBytesOutOfBoundaryWontDeadlock() throws Exception { t.start(); // wait for thread to start, and check it should be blocked - assertByPolling(Duration.ofMillis(200), () -> assertEquals(State.WAITING, t.getState())); + assertByPolling( + java.time.Duration.ofMillis(200), () -> assertEquals(State.WAITING, t.getState())); // increase and decrease should not be blocked int increase = 5, decrease = 20; @@ -648,7 +648,8 @@ void testElementCountsOutOfBoundaryWontDeadlock() throws Exception { t.start(); // wait for thread to start, and check it should be blocked - assertByPolling(Duration.ofMillis(200), () -> assertEquals(State.WAITING, t.getState())); + assertByPolling( + java.time.Duration.ofMillis(200), () -> assertEquals(State.WAITING, t.getState())); // increase and decrease should not be blocked int increase = 5, decrease = 20; diff --git a/gax-java/gax/src/test/java/com/google/api/gax/batching/ThresholdBatcherTest.java b/gax-java/gax/src/test/java/com/google/api/gax/batching/ThresholdBatcherTest.java index 244fc57850..f87b772d3b 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/batching/ThresholdBatcherTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/batching/ThresholdBatcherTest.java @@ -32,18 +32,27 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.google.api.core.ApiFutures; import com.google.api.gax.batching.FlowController.FlowControlException; import com.google.api.gax.batching.FlowController.LimitExceededBehavior; +import com.google.common.collect.ImmutableList; +import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class ThresholdBatcherTest { @@ -124,6 +133,7 @@ private List getIntegers() { } private static class SimpleBatchMerger implements BatchMerger { + @Override public void merge(SimpleBatch batch, SimpleBatch newBatch) { batch.merge(newBatch); @@ -135,12 +145,28 @@ private static ThresholdBatcher.Builder createSimpleBatcherBuidler( return ThresholdBatcher.newBuilder() .setThresholds(BatchingThresholds.create(100)) .setExecutor(EXECUTOR) - .setMaxDelay(Duration.ofMillis(10000)) + .setMaxDelayDuration(java.time.Duration.ofMillis(10000)) .setReceiver(receiver) .setFlowController(ThresholdBatcherTest.getDisabledBatchingFlowController()) .setBatchMerger(new SimpleBatchMerger()); } + private static SimpleEntry + createSimpleBatcherBuilderWithMockExecutor(long customThreshold) { + AccumulatingBatchReceiver receiver = + new AccumulatingBatchReceiver<>(ApiFutures.immediateFuture(null)); + ScheduledExecutorService executor = mock(ScheduledThreadPoolExecutor.class); + when(executor.schedule((Runnable) any(), anyLong(), any())) + .thenReturn(mock(ScheduledFuture.class)); + BatchingThreshold threshold = new NumericThreshold<>(customThreshold, e -> 1); + + ThresholdBatcher.Builder builder = + createSimpleBatcherBuidler(receiver) + .setExecutor(executor) + .setThresholds(ImmutableList.of(threshold)); + return new SimpleEntry<>(builder, executor); + } + @Test void testAdd() throws Exception { AccumulatingBatchReceiver receiver = @@ -195,7 +221,9 @@ void testBatchingWithDelay() throws Exception { AccumulatingBatchReceiver receiver = new AccumulatingBatchReceiver<>(ApiFutures.immediateFuture(null)); ThresholdBatcher batcher = - createSimpleBatcherBuidler(receiver).setMaxDelay(Duration.ofMillis(100)).build(); + createSimpleBatcherBuidler(receiver) + .setMaxDelayDuration(java.time.Duration.ofMillis(100)) + .build(); batcher.add(SimpleBatch.fromInteger(3)); batcher.add(SimpleBatch.fromInteger(5)); @@ -223,7 +251,7 @@ void testExceptionWithNullFlowController() { ThresholdBatcher.newBuilder() .setThresholds(BatchingThresholds.create(100)) .setExecutor(EXECUTOR) - .setMaxDelay(Duration.ofMillis(10000)) + .setMaxDelayDuration(java.time.Duration.ofMillis(10000)) .setReceiver( new AccumulatingBatchReceiver( ApiFutures.immediateFuture(null))) @@ -353,4 +381,28 @@ void testBatchingFailedRPC() throws Exception { assertThat(trackedFlowController.getBytesReserved()) .isEqualTo(trackedFlowController.getBytesReleased()); } + + @Test + public void testMaxDelay() throws FlowControlException { + + final long MILLIS = 123l; + final SimpleBatch TEST_BATCH = SimpleBatch.fromInteger(1); + java.time.Duration javaTimeDuration = java.time.Duration.ofMillis(MILLIS); + org.threeten.bp.Duration threetenDuration = org.threeten.bp.Duration.ofMillis(MILLIS); + + SimpleEntry container = + createSimpleBatcherBuilderWithMockExecutor(1000l); + ThresholdBatcher.Builder builder = container.getKey(); + ScheduledExecutorService executor = container.getValue(); + + builder.setMaxDelayDuration(javaTimeDuration).build().add(TEST_BATCH); + verify(executor, times(1)).schedule((Runnable) any(), eq(MILLIS), any()); + + container = createSimpleBatcherBuilderWithMockExecutor(1000l); + builder = container.getKey(); + executor = container.getValue(); + + builder.setMaxDelay(threetenDuration).build().add(TEST_BATCH); + verify(executor, times(1)).schedule((Runnable) any(), eq(MILLIS), any()); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/core/RecordingScheduler.java b/gax-java/gax/src/test/java/com/google/api/gax/core/RecordingScheduler.java index 6d8cf9119b..d495cf0d63 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/core/RecordingScheduler.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/core/RecordingScheduler.java @@ -43,11 +43,10 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.threeten.bp.Duration; public abstract class RecordingScheduler implements ScheduledExecutorService { - public abstract List getSleepDurations(); + public abstract List getSleepDurations(); public abstract int getIterationsCount(); @@ -56,7 +55,7 @@ public static RecordingScheduler create(final FakeApiClock clock) { // mock class fields: final ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); - final List sleepDurations = new ArrayList<>(); + final List sleepDurations = new ArrayList<>(); final AtomicInteger iterationsCount = new AtomicInteger(0); // mock class methods: @@ -71,7 +70,8 @@ public ScheduledFuture answer(InvocationOnMock invocation) throws Throwable { Long delay = (Long) args[1]; TimeUnit unit = (TimeUnit) args[2]; iterationsCount.incrementAndGet(); - sleepDurations.add(Duration.ofMillis(TimeUnit.MILLISECONDS.convert(delay, unit))); + sleepDurations.add( + java.time.Duration.ofMillis(TimeUnit.MILLISECONDS.convert(delay, unit))); clock.incrementNanoTime(TimeUnit.NANOSECONDS.convert(delay, unit)); return executor.schedule(runnable, 0, TimeUnit.NANOSECONDS); } @@ -87,7 +87,7 @@ public List answer(InvocationOnMock invocation) throws Throwable { } }); - // List getSleepDurations() + // List getSleepDurations() when(mock.getSleepDurations()).thenReturn(sleepDurations); // int getIterationsCount() diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/AbstractRetryingExecutorTest.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/AbstractRetryingExecutorTest.java index 15b5a5ee8a..5b8599e1e8 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/retrying/AbstractRetryingExecutorTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/AbstractRetryingExecutorTest.java @@ -62,7 +62,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) public abstract class AbstractRetryingExecutorTest { @@ -80,7 +79,7 @@ protected abstract RetryingExecutorWithContext getExecutor( protected abstract RetryAlgorithm getAlgorithm( RetrySettings retrySettings, int apocalypseCountDown, RuntimeException apocalypseException); - protected void busyWaitForInitialResult(RetryingFuture future, Duration timeout) + protected void busyWaitForInitialResult(RetryingFuture future, java.time.Duration timeout) throws TimeoutException { Stopwatch watch = Stopwatch.createStarted(); while (future.peekAttemptResult() == null) { @@ -137,7 +136,8 @@ void testSuccessWithFailures(boolean withCustomRetrySettings) throws Exception { assertEquals(5, future.getAttemptSettings().getAttemptCount()); verify(tracer, times(6)).attemptStarted(eq("request"), anyInt()); - verify(tracer, times(5)).attemptFailed(any(Throwable.class), any(Duration.class)); + verify(tracer, times(5)) + .attemptFailedDuration(any(Throwable.class), any(java.time.Duration.class)); verify(tracer, times(1)).attemptSucceeded(); verifyNoMoreInteractions(tracer); } @@ -190,7 +190,8 @@ void testMaxRetriesExceeded(boolean withCustomRetrySettings) throws Exception { assertEquals(5, future.getAttemptSettings().getAttemptCount()); verify(tracer, times(6)).attemptStarted(eq("request"), anyInt()); - verify(tracer, times(5)).attemptFailed(any(Throwable.class), any(Duration.class)); + verify(tracer, times(5)) + .attemptFailedDuration(any(Throwable.class), any(java.time.Duration.class)); verify(tracer, times(1)).attemptFailedRetriesExhausted(any(Throwable.class)); verifyNoMoreInteractions(tracer); } @@ -202,8 +203,8 @@ void testTotalTimeoutExceeded(boolean withCustomRetrySettings) throws Exception RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) - .setMaxRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) .build(); boolean useContextRetrySettings = retryingContext.getRetrySettings() != null; RetryingExecutorWithContext executor = @@ -242,9 +243,9 @@ void testCancelOuterFutureBeforeStart(boolean withCustomRetrySettings) { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(1_000L)) - .setMaxRetryDelay(Duration.ofMillis(1_000L)) - .setTotalTimeout(Duration.ofMillis(10_000L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1_000L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1_000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(10_000L)) .build(); RetryingExecutorWithContext executor = getExecutor(getAlgorithm(retrySettings, 0, null)); @@ -282,7 +283,8 @@ void testCancelByRetryingAlgorithm(boolean withCustomRetrySettings) throws Excep verify(tracer, times(5)).attemptStarted(eq("request"), anyInt()); // Pre-apocalypse failures - verify(tracer, times(4)).attemptFailed(any(Throwable.class), any(Duration.class)); + verify(tracer, times(4)) + .attemptFailedDuration(any(Throwable.class), any(java.time.Duration.class)); // Apocalypse failure verify(tracer, times(1)).attemptFailedRetriesExhausted(any(CancellationException.class)); verifyNoMoreInteractions(tracer); @@ -308,7 +310,8 @@ void testUnexpectedExceptionFromRetryAlgorithm(boolean withCustomRetrySettings) verify(tracer, times(5)).attemptStarted(eq("request"), anyInt()); // Pre-apocalypse failures - verify(tracer, times(4)).attemptFailed(any(Throwable.class), any(Duration.class)); + verify(tracer, times(4)) + .attemptFailedDuration(any(Throwable.class), any(java.time.Duration.class)); // Apocalypse failure verify(tracer, times(1)).attemptPermanentFailure(any(RuntimeException.class)); verifyNoMoreInteractions(tracer); @@ -321,8 +324,8 @@ void testPollExceptionByPollAlgorithm(boolean withCustomRetrySettings) throws Ex RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) - .setMaxRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) .build(); boolean useContextRetrySettings = retryingContext.getRetrySettings() != null; diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/BasicRetryingFutureTest.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/BasicRetryingFutureTest.java index 7d1a0f5ada..5342f02965 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/retrying/BasicRetryingFutureTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/BasicRetryingFutureTest.java @@ -30,6 +30,7 @@ package com.google.api.gax.retrying; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import com.google.api.gax.tracing.ApiTracer; import java.lang.reflect.Field; @@ -41,7 +42,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import org.threeten.bp.Duration; class BasicRetryingFutureTest { private Level logLevel; @@ -65,6 +65,9 @@ void testHandleAttemptDoesNotThrowNPEWhenLogLevelLowerThanFiner() throws Excepti RetryingContext retryingContext = mock(RetryingContext.class); ApiTracer tracer = mock(ApiTracer.class); TimedAttemptSettings timedAttemptSettings = mock(TimedAttemptSettings.class); + java.time.Duration testDuration = java.time.Duration.ofMillis(123); + Mockito.when(timedAttemptSettings.getRandomizedRetryDelayDuration()).thenReturn(testDuration); + Mockito.when(timedAttemptSettings.getRetryDelayDuration()).thenReturn(testDuration); Mockito.when(retryingContext.getTracer()).thenReturn(tracer); @@ -93,7 +96,12 @@ void testHandleAttemptDoesNotThrowNPEWhenLogLevelLowerThanFiner() throws Excepti future.handleAttempt(null, null); Mockito.verify(tracer) - .attemptFailed(ArgumentMatchers.any(), ArgumentMatchers.any()); + .attemptFailedDuration(ArgumentMatchers.isNull(), ArgumentMatchers.eq(testDuration)); + Mockito.verify(timedAttemptSettings, times(1)).getRetryDelayDuration(); + + Mockito.verify(tracer) + .attemptFailedDuration( + ArgumentMatchers.any(), ArgumentMatchers.any()); Mockito.verifyNoMoreInteractions(tracer); } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/ExponentialRetryAlgorithmTest.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/ExponentialRetryAlgorithmTest.java index 468da7fc6f..7d9c1dbb02 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/retrying/ExponentialRetryAlgorithmTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/ExponentialRetryAlgorithmTest.java @@ -37,33 +37,32 @@ import com.google.api.gax.core.FakeApiClock; import com.google.api.gax.rpc.testing.FakeCallContext; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class ExponentialRetryAlgorithmTest { private final FakeApiClock clock = new FakeApiClock(0L); private final RetrySettings retrySettings = RetrySettings.newBuilder() .setMaxAttempts(6) - .setInitialRetryDelay(Duration.ofMillis(1L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1L)) .setRetryDelayMultiplier(2.0) - .setMaxRetryDelay(Duration.ofMillis(8L)) - .setInitialRpcTimeout(Duration.ofMillis(1L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(8L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(1L)) .setRpcTimeoutMultiplier(2.0) - .setMaxRpcTimeout(Duration.ofMillis(8L)) - .setTotalTimeout(Duration.ofMillis(200L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(8L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(200L)) .build(); private final ExponentialRetryAlgorithm algorithm = new ExponentialRetryAlgorithm(retrySettings, clock); private final RetrySettings retrySettingsOverride = RetrySettings.newBuilder() .setMaxAttempts(3) - .setInitialRetryDelay(Duration.ofMillis(2L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(2L)) .setRetryDelayMultiplier(3.0) - .setMaxRetryDelay(Duration.ofMillis(18L)) - .setInitialRpcTimeout(Duration.ofMillis(2L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(18L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) .setRpcTimeoutMultiplier(3.0) - .setMaxRpcTimeout(Duration.ofMillis(18L)) - .setTotalTimeout(Duration.ofMillis(300L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(18L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(300L)) .build(); private final RetryingContext retryingContext = FakeCallContext.createDefault().withRetrySettings(retrySettingsOverride); @@ -75,10 +74,10 @@ void testCreateFirstAttempt() { // Checking only the most core values, to not make this test too implementation specific. assertEquals(0, attempt.getAttemptCount()); assertEquals(0, attempt.getOverallAttemptCount()); - assertEquals(Duration.ZERO, attempt.getRetryDelay()); - assertEquals(Duration.ZERO, attempt.getRandomizedRetryDelay()); - assertEquals(Duration.ofMillis(1L), attempt.getRpcTimeout()); - assertEquals(Duration.ZERO, attempt.getRetryDelay()); + assertEquals(java.time.Duration.ZERO, attempt.getRetryDelayDuration()); + assertEquals(java.time.Duration.ZERO, attempt.getRandomizedRetryDelayDuration()); + assertEquals(java.time.Duration.ofMillis(1L), attempt.getRpcTimeoutDuration()); + assertEquals(java.time.Duration.ZERO, attempt.getRetryDelayDuration()); } @Test @@ -88,10 +87,11 @@ void testCreateFirstAttemptOverride() { // Checking only the most core values, to not make this test too implementation specific. assertEquals(0, attempt.getAttemptCount()); assertEquals(0, attempt.getOverallAttemptCount()); - assertEquals(Duration.ZERO, attempt.getRetryDelay()); - assertEquals(Duration.ZERO, attempt.getRandomizedRetryDelay()); - assertEquals(retrySettingsOverride.getInitialRpcTimeout(), attempt.getRpcTimeout()); - assertEquals(Duration.ZERO, attempt.getRetryDelay()); + assertEquals(java.time.Duration.ZERO, attempt.getRetryDelayDuration()); + assertEquals(java.time.Duration.ZERO, attempt.getRandomizedRetryDelayDuration()); + assertEquals( + retrySettingsOverride.getInitialRpcTimeoutDuration(), attempt.getRpcTimeoutDuration()); + assertEquals(java.time.Duration.ZERO, attempt.getRetryDelayDuration()); } @Test @@ -101,35 +101,37 @@ void testCreateFirstAttemptHasCorrectTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setMaxAttempts(6) - .setInitialRetryDelay(Duration.ofMillis(1L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1L)) .setRetryDelayMultiplier(2.0) - .setMaxRetryDelay(Duration.ofMillis(8L)) - .setInitialRpcTimeout(Duration.ofMillis(rpcTimeout)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(8L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(rpcTimeout)) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(Duration.ofMillis(rpcTimeout)) - .setTotalTimeout(Duration.ofMillis(totalTimeout)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(rpcTimeout)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(totalTimeout)) .build(); ExponentialRetryAlgorithm algorithm = new ExponentialRetryAlgorithm(retrySettings, clock); TimedAttemptSettings attempt = algorithm.createFirstAttempt(); - assertEquals(Duration.ofMillis(totalTimeout), attempt.getRpcTimeout()); + assertEquals(java.time.Duration.ofMillis(totalTimeout), attempt.getRpcTimeoutDuration()); long overrideRpcTimeout = 100; long overrideTotalTimeout = 20; RetrySettings retrySettingsOverride = retrySettings .toBuilder() - .setInitialRpcTimeout(Duration.ofMillis(overrideRpcTimeout)) - .setMaxRpcTimeout(Duration.ofMillis(overrideRpcTimeout)) - .setTotalTimeout(Duration.ofMillis(overrideTotalTimeout)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(overrideRpcTimeout)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(overrideRpcTimeout)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(overrideTotalTimeout)) .build(); RetryingContext retryingContext = FakeCallContext.createDefault().withRetrySettings(retrySettingsOverride); attempt = algorithm.createFirstAttempt(retryingContext); - assertEquals(Duration.ofMillis(overrideTotalTimeout), attempt.getRpcTimeout()); + assertEquals( + java.time.Duration.ofMillis(overrideTotalTimeout), attempt.getRpcTimeoutDuration()); - RetrySettings noTotalTimeout = retrySettings.toBuilder().setTotalTimeout(Duration.ZERO).build(); + RetrySettings noTotalTimeout = + retrySettings.toBuilder().setTotalTimeoutDuration(java.time.Duration.ZERO).build(); algorithm = new ExponentialRetryAlgorithm(noTotalTimeout, clock); attempt = algorithm.createFirstAttempt(); @@ -144,13 +146,13 @@ void testCreateNextAttempt() { // Checking only the most core values, to not make this test too implementation specific. assertEquals(1, secondAttempt.getAttemptCount()); assertEquals(1, secondAttempt.getOverallAttemptCount()); - assertEquals(Duration.ofMillis(1L), secondAttempt.getRetryDelay()); - assertEquals(Duration.ofMillis(2L), secondAttempt.getRpcTimeout()); + assertEquals(java.time.Duration.ofMillis(1L), secondAttempt.getRetryDelayDuration()); + assertEquals(java.time.Duration.ofMillis(2L), secondAttempt.getRpcTimeoutDuration()); TimedAttemptSettings thirdAttempt = algorithm.createNextAttempt(secondAttempt); assertEquals(2, thirdAttempt.getAttemptCount()); - assertEquals(Duration.ofMillis(2L), thirdAttempt.getRetryDelay()); - assertEquals(Duration.ofMillis(4L), thirdAttempt.getRpcTimeout()); + assertEquals(java.time.Duration.ofMillis(2L), thirdAttempt.getRetryDelayDuration()); + assertEquals(java.time.Duration.ofMillis(4L), thirdAttempt.getRpcTimeoutDuration()); } @Test @@ -161,13 +163,13 @@ void testCreateNextAttemptOverride() { // Checking only the most core values, to not make this test too implementation specific. assertEquals(1, secondAttempt.getAttemptCount()); assertEquals(1, secondAttempt.getOverallAttemptCount()); - assertEquals(Duration.ofMillis(2L), secondAttempt.getRetryDelay()); - assertEquals(Duration.ofMillis(6L), secondAttempt.getRpcTimeout()); + assertEquals(java.time.Duration.ofMillis(2L), secondAttempt.getRetryDelayDuration()); + assertEquals(java.time.Duration.ofMillis(6L), secondAttempt.getRpcTimeoutDuration()); TimedAttemptSettings thirdAttempt = algorithm.createNextAttempt(secondAttempt); assertEquals(2, thirdAttempt.getAttemptCount()); - assertEquals(Duration.ofMillis(6L), thirdAttempt.getRetryDelay()); - assertEquals(Duration.ofMillis(18L), thirdAttempt.getRpcTimeout()); + assertEquals(java.time.Duration.ofMillis(6L), thirdAttempt.getRetryDelayDuration()); + assertEquals(java.time.Duration.ofMillis(18L), thirdAttempt.getRpcTimeoutDuration()); } @Test @@ -175,19 +177,20 @@ void testTruncateToTotalTimeout() { RetrySettings timeoutSettings = retrySettings .toBuilder() - .setInitialRpcTimeout(Duration.ofSeconds(4L)) - .setMaxRpcTimeout(Duration.ofSeconds(4L)) - .setTotalTimeout(Duration.ofSeconds(4L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofSeconds(4L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofSeconds(4L)) + .setTotalTimeoutDuration(java.time.Duration.ofSeconds(4L)) .build(); ExponentialRetryAlgorithm timeoutAlg = new ExponentialRetryAlgorithm(timeoutSettings, clock); TimedAttemptSettings firstAttempt = timeoutAlg.createFirstAttempt(); TimedAttemptSettings secondAttempt = timeoutAlg.createNextAttempt(firstAttempt); - assertThat(secondAttempt.getRpcTimeout()).isAtLeast(firstAttempt.getRpcTimeout()); - assertThat(secondAttempt.getRpcTimeout()).isAtMost(Duration.ofSeconds(4L)); + assertThat(secondAttempt.getRpcTimeoutDuration()) + .isAtLeast(firstAttempt.getRpcTimeoutDuration()); + assertThat(secondAttempt.getRpcTimeoutDuration()).isAtMost(java.time.Duration.ofSeconds(4L)); TimedAttemptSettings thirdAttempt = timeoutAlg.createNextAttempt(secondAttempt); - assertThat(thirdAttempt.getRpcTimeout()).isAtMost(Duration.ofSeconds(4L)); + assertThat(thirdAttempt.getRpcTimeoutDuration()).isAtMost(java.time.Duration.ofSeconds(4L)); } @Test @@ -225,11 +228,11 @@ void testShouldRetryFalseOnMaxTimeout() { // Simulate each attempt with 60ms of clock time. // "attempt" = RPC Timeout + createNextAttempt() and shouldRetry() TimedAttemptSettings attempt = algorithm.createFirstAttempt(); - clock.incrementNanoTime(Duration.ofMillis(60L).toNanos()); + clock.incrementNanoTime(java.time.Duration.ofMillis(60L).toNanos()); for (int i = 0; i < 3; i++) { assertTrue(algorithm.shouldRetry(attempt)); attempt = algorithm.createNextAttempt(attempt); - clock.incrementNanoTime(Duration.ofMillis(60L).toNanos()); + clock.incrementNanoTime(java.time.Duration.ofMillis(60L).toNanos()); } assertFalse(algorithm.shouldRetry(attempt)); } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/FailingCallable.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/FailingCallable.java index b3dab98764..5fb8a2892b 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/retrying/FailingCallable.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/FailingCallable.java @@ -34,30 +34,29 @@ import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; -import org.threeten.bp.Duration; class FailingCallable implements Callable { static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() .setMaxAttempts(6) - .setInitialRetryDelay(Duration.ofMillis(8L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(8L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(8L)) - .setInitialRpcTimeout(Duration.ofMillis(8L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(8L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(8L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(8L)) - .setTotalTimeout(Duration.ofMillis(400L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(8L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(400L)) .build(); static final RetrySettings FAILING_RETRY_SETTINGS = RetrySettings.newBuilder() .setMaxAttempts(2) - .setInitialRetryDelay(Duration.ofNanos(1L)) + .setInitialRetryDelayDuration(java.time.Duration.ofNanos(1L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofNanos(1L)) - .setInitialRpcTimeout(Duration.ofNanos(1L)) + .setMaxRetryDelayDuration(java.time.Duration.ofNanos(1L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofNanos(1L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofNanos(1L)) - .setTotalTimeout(Duration.ofNanos(1L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofNanos(1L)) + .setTotalTimeoutDuration(java.time.Duration.ofNanos(1L)) .build(); private AtomicInteger attemptsCount = new AtomicInteger(0); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/RetrySettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/RetrySettingsTest.java index 7f51cac368..fa22880ca3 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/retrying/RetrySettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/RetrySettingsTest.java @@ -29,50 +29,110 @@ */ package com.google.api.gax.retrying; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; + import com.google.common.truth.Truth; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class RetrySettingsTest { + private static final RetrySettings.Builder DEFAULT_BUILDER = + RetrySettings.newBuilder() + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(5000l)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(5000l)); @Test void retrySettingsSetLogicalTimeout() { - Duration timeout = Duration.ofMillis(60000); + java.time.Duration timeout = java.time.Duration.ofMillis(60000); RetrySettings retrySettings = RetrySettings.newBuilder().setLogicalTimeout(timeout).build(); Truth.assertThat(retrySettings.getRpcTimeoutMultiplier()).isEqualTo(1); - Truth.assertThat(retrySettings.getInitialRpcTimeout()).isEqualTo(timeout); - Truth.assertThat(retrySettings.getMaxRpcTimeout()).isEqualTo(timeout); - Truth.assertThat(retrySettings.getTotalTimeout()).isEqualTo(timeout); + Truth.assertThat(retrySettings.getInitialRpcTimeoutDuration()).isEqualTo(timeout); + Truth.assertThat(retrySettings.getMaxRpcTimeoutDuration()).isEqualTo(timeout); + Truth.assertThat(retrySettings.getTotalTimeoutDuration()).isEqualTo(timeout); } @Test void retrySettingsMerge() { RetrySettings.Builder builder = RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofMillis(45000)) - .setInitialRpcTimeout(Duration.ofMillis(2000)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(45000)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2000)) .setRpcTimeoutMultiplier(1.5) - .setMaxRpcTimeout(Duration.ofMillis(30000)) - .setInitialRetryDelay(Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(30000)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(100)) .setRetryDelayMultiplier(1.2) - .setMaxRetryDelay(Duration.ofMillis(1000)); + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1000)); RetrySettings.Builder mergedBuilder = RetrySettings.newBuilder(); mergedBuilder.merge(builder); RetrySettings settingsA = builder.build(); RetrySettings settingsB = mergedBuilder.build(); - Truth.assertThat(settingsA.getTotalTimeout()).isEqualTo(settingsB.getTotalTimeout()); - Truth.assertThat(settingsA.getInitialRetryDelay()).isEqualTo(settingsB.getInitialRetryDelay()); + Truth.assertThat(settingsA.getTotalTimeoutDuration()) + .isEqualTo(settingsB.getTotalTimeoutDuration()); + Truth.assertThat(settingsA.getInitialRetryDelayDuration()) + .isEqualTo(settingsB.getInitialRetryDelayDuration()); Truth.assertThat(settingsA.getRpcTimeoutMultiplier()) .isWithin(0) .of(settingsB.getRpcTimeoutMultiplier()); - Truth.assertThat(settingsA.getMaxRpcTimeout()).isEqualTo(settingsB.getMaxRpcTimeout()); - Truth.assertThat(settingsA.getInitialRetryDelay()).isEqualTo(settingsB.getInitialRetryDelay()); + Truth.assertThat(settingsA.getMaxRpcTimeoutDuration()) + .isEqualTo(settingsB.getMaxRpcTimeoutDuration()); + Truth.assertThat(settingsA.getInitialRetryDelayDuration()) + .isEqualTo(settingsB.getInitialRetryDelayDuration()); Truth.assertThat(settingsA.getRetryDelayMultiplier()) .isWithin(0) .of(settingsB.getRetryDelayMultiplier()); - Truth.assertThat(settingsA.getMaxRetryDelay()).isEqualTo(settingsB.getMaxRetryDelay()); + Truth.assertThat(settingsA.getMaxRetryDelayDuration()) + .isEqualTo(settingsB.getMaxRetryDelayDuration()); + } + + @Test + public void testTotalTimeout() { + testDurationMethod( + 123l, + jt -> DEFAULT_BUILDER.setTotalTimeoutDuration(jt).build(), + tt -> DEFAULT_BUILDER.setTotalTimeout(tt).build(), + rs -> rs.getTotalTimeoutDuration(), + rs -> rs.getTotalTimeout()); + } + + @Test + public void testInitialRetryDelay() { + testDurationMethod( + 123l, + jt -> DEFAULT_BUILDER.setInitialRetryDelayDuration(jt).build(), + tt -> DEFAULT_BUILDER.setInitialRetryDelay(tt).build(), + rs -> rs.getInitialRetryDelayDuration(), + rs -> rs.getInitialRetryDelay()); + } + + @Test + public void testMaxRetryDelay() { + testDurationMethod( + 123l, + jt -> DEFAULT_BUILDER.setMaxRetryDelayDuration(jt).build(), + tt -> DEFAULT_BUILDER.setMaxRetryDelay(tt).build(), + rs -> rs.getMaxRetryDelayDuration(), + rs -> rs.getMaxRetryDelay()); + } + + @Test + public void testInitialRpcTimeout() { + testDurationMethod( + 123l, + jt -> DEFAULT_BUILDER.setInitialRpcTimeoutDuration(jt).build(), + tt -> DEFAULT_BUILDER.setInitialRpcTimeout(tt).build(), + rs -> rs.getInitialRpcTimeoutDuration(), + rs -> rs.getInitialRpcTimeout()); + } + + @Test + public void testMaxRpcTimeout() { + testDurationMethod( + 123l, + jt -> DEFAULT_BUILDER.setMaxRpcTimeoutDuration(jt).build(), + tt -> DEFAULT_BUILDER.setMaxRpcTimeout(tt).build(), + rs -> rs.getMaxRpcTimeoutDuration(), + rs -> rs.getMaxRpcTimeout()); } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java index e0ecd61ced..53c1707290 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java @@ -53,7 +53,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; -import org.threeten.bp.Duration; class ScheduledRetryingExecutorTest extends AbstractRetryingExecutorTest { private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @@ -95,7 +94,7 @@ void testSuccessWithFailuresPeekAttempt() throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(1000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) .setMaxAttempts(maxRetries) .build(); @@ -146,7 +145,7 @@ void testSuccessWithFailuresGetAttempt() throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(1000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) .setMaxAttempts(maxRetries) .build(); @@ -202,7 +201,7 @@ void testCancelGetAttempt(boolean withCustomRetrySettings) throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(1000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) .setMaxAttempts(maxRetries) .build(); @@ -262,10 +261,10 @@ void testCancelOuterFutureAfterStart() throws Exception { // once) but does not complete before it is cancelled. Assuming no computation time, // it would take 25 + 100 + 400 + 1000 = 1525ms for the future to complete, which should // be more than enough time to cancel the future. - .setInitialRetryDelay(Duration.ofMillis(25L)) - .setMaxRetryDelay(Duration.ofMillis(1000L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(25L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1000L)) .setRetryDelayMultiplier(4.0) - .setTotalTimeout(Duration.ofMillis(60000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(60000L)) // Set this test to not use jitter as the randomized retry delay (RRD) may introduce // flaky results. For example, if every RRD value is calculated to be a small value // (i.e. 2ms), four retries would result a "SUCCESS" result after 8ms, far below @@ -314,9 +313,9 @@ void testCancelProxiedFutureAfterStart() throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(1_000L)) - .setMaxRetryDelay(Duration.ofMillis(1_000L)) - .setTotalTimeout(Duration.ofMillis(10_0000L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1_000L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1_000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(10_0000L)) .build(); RetryingExecutorWithContext executor = getRetryingExecutor(getAlgorithm(retrySettings, 0, null), localExecutor); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/retrying/TimedAttemptSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/retrying/TimedAttemptSettingsTest.java new file mode 100644 index 0000000000..af0c1e1b35 --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/retrying/TimedAttemptSettingsTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.retrying; + +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; + +import org.junit.jupiter.api.Test; + +public class TimedAttemptSettingsTest { + + private static final TimedAttemptSettings.Builder SETTINGS_BUILDER = + TimedAttemptSettings.newBuilder() + .setGlobalSettings(RetrySettings.newBuilder().build()) + .setRpcTimeoutDuration(java.time.Duration.ofMillis(5000l)) + .setRandomizedRetryDelayDuration(java.time.Duration.ofMillis(5000l)) + .setAttemptCount(123) + .setFirstAttemptStartTimeNanos(123l); + + @Test + public void testRetryDelay() { + testDurationMethod( + 123l, + jt -> SETTINGS_BUILDER.setRetryDelayDuration(jt).build(), + tt -> SETTINGS_BUILDER.setRetryDelay(tt).build(), + o -> o.getRetryDelayDuration(), + o -> o.getRetryDelay()); + } + + @Test + public void testRandomizedRetryDelay() { + testDurationMethod( + 123l, + jt -> SETTINGS_BUILDER.setRandomizedRetryDelayDuration(jt).build(), + tt -> SETTINGS_BUILDER.setRandomizedRetryDelay(tt).build(), + o -> o.getRandomizedRetryDelayDuration(), + o -> o.getRandomizedRetryDelay()); + } + + @Test + public void testRpcTimeout() { + testDurationMethod( + 123l, + jt -> SETTINGS_BUILDER.setRpcTimeoutDuration(jt).build(), + tt -> SETTINGS_BUILDER.setRpcTimeout(tt).build(), + o -> o.getRpcTimeoutDuration(), + o -> o.getRpcTimeout()); + } +} diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/AttemptCallableTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/AttemptCallableTest.java index 7a84bc88d4..f06ccdf2c6 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/AttemptCallableTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/AttemptCallableTest.java @@ -30,12 +30,16 @@ package com.google.api.gax.rpc; import static com.google.common.truth.Truth.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.google.api.core.SettableApiFuture; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.retrying.RetryingFuture; import com.google.api.gax.retrying.TimedAttemptSettings; import com.google.api.gax.rpc.testing.FakeCallContext; +import com.google.api.gax.tracing.ApiTracer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -45,7 +49,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class AttemptCallableTest { @@ -57,7 +60,7 @@ class AttemptCallableTest { @BeforeEach void setUp() { capturedCallContext = ArgumentCaptor.forClass(ApiCallContext.class); - Mockito.when(mockInnerCallable.futureCall(Mockito.anyString(), capturedCallContext.capture())) + when(mockInnerCallable.futureCall(Mockito.anyString(), capturedCallContext.capture())) .thenReturn(SettableApiFuture.create()); currentAttemptSettings = @@ -66,12 +69,12 @@ void setUp() { .setAttemptCount(0) .setOverallAttemptCount(0) .setFirstAttemptStartTimeNanos(0) - .setRetryDelay(Duration.ofSeconds(1)) - .setRandomizedRetryDelay(Duration.ofSeconds(1)) - .setRpcTimeout(Duration.ZERO) + .setRetryDelayDuration(java.time.Duration.ofSeconds(1)) + .setRandomizedRetryDelayDuration(java.time.Duration.ofSeconds(1)) + .setRpcTimeoutDuration(java.time.Duration.ZERO) .build(); - Mockito.when(mockExternalFuture.getAttemptSettings()) + when(mockExternalFuture.getAttemptSettings()) .thenAnswer( new Answer() { @Override @@ -83,33 +86,40 @@ public TimedAttemptSettings answer(InvocationOnMock invocation) throws Throwable @Test void testRpcTimeout() { + FakeCallContext callContext = mock(FakeCallContext.class); + when(callContext.getTimeoutDuration()).thenReturn(null); + when(callContext.withTimeoutDuration(any(java.time.Duration.class))).thenReturn(callContext); + when(callContext.getTracer()).thenReturn(mock(ApiTracer.class)); AttemptCallable callable = - new AttemptCallable<>(mockInnerCallable, "fake-request", FakeCallContext.createDefault()); + new AttemptCallable<>(mockInnerCallable, "fake-request", callContext); callable.setExternalFuture(mockExternalFuture); // Make sure that the rpc timeout is set - Duration timeout = Duration.ofSeconds(10); - currentAttemptSettings = currentAttemptSettings.toBuilder().setRpcTimeout(timeout).build(); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); + currentAttemptSettings = + currentAttemptSettings.toBuilder().setRpcTimeoutDuration(timeout).build(); callable.call(); - assertThat(capturedCallContext.getValue().getTimeout()).isEqualTo(timeout); + Mockito.verify(callContext).withTimeoutDuration(timeout); - // Make sure that subsequent attempts can extend the time out - Duration longerTimeout = Duration.ofSeconds(20); + // Make sure that subsequent attempts can extend the timeout + java.time.Duration longerTimeout = java.time.Duration.ofSeconds(20); currentAttemptSettings = - currentAttemptSettings.toBuilder().setRpcTimeout(longerTimeout).build(); + currentAttemptSettings.toBuilder().setRpcTimeoutDuration(longerTimeout).build(); callable.call(); - assertThat(capturedCallContext.getValue().getTimeout()).isEqualTo(longerTimeout); + Mockito.verify(callContext).withTimeoutDuration(longerTimeout); } @Test void testRpcTimeoutIsNotErased() { - Duration callerTimeout = Duration.ofMillis(10); - ApiCallContext callerCallContext = FakeCallContext.createDefault().withTimeout(callerTimeout); + java.time.Duration callerTimeout = java.time.Duration.ofMillis(10); + ApiCallContext callerCallContext = + FakeCallContext.createDefault().withTimeoutDuration(callerTimeout); - Duration timeout = Duration.ofMillis(5); - currentAttemptSettings = currentAttemptSettings.toBuilder().setRpcTimeout(timeout).build(); + java.time.Duration timeout = java.time.Duration.ofMillis(5); + currentAttemptSettings = + currentAttemptSettings.toBuilder().setRpcTimeoutDuration(timeout).build(); AttemptCallable callable = new AttemptCallable<>(mockInnerCallable, "fake-request", callerCallContext); @@ -117,6 +127,6 @@ void testRpcTimeoutIsNotErased() { callable.call(); - assertThat(capturedCallContext.getValue().getTimeout()).isEqualTo(callerTimeout); + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(callerTimeout); } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatcherFactoryTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatcherFactoryTest.java index e2a783adf3..8ece5dedde 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatcherFactoryTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatcherFactoryTest.java @@ -45,7 +45,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; +import org.mockito.Mockito; class BatcherFactoryTest { private ScheduledExecutorService batchingExecutor; @@ -62,12 +62,11 @@ void tearDown() { @Test void testGetPushingBatcher() { - BatchingSettings batchingSettings = - BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) - .setElementCountThreshold(2L) - .setRequestByteThreshold(1000L) - .build(); + final java.time.Duration delayThreshold = java.time.Duration.ofSeconds(1); + BatchingSettings batchingSettings = Mockito.mock(BatchingSettings.class); + Mockito.when(batchingSettings.getDelayThresholdDuration()).thenReturn(delayThreshold); + Mockito.when(batchingSettings.getElementCountThreshold()).thenReturn(2L); + Mockito.when(batchingSettings.getRequestByteThreshold()).thenReturn(1000L); FlowControlSettings flowControlSettings = FlowControlSettings.newBuilder() .setLimitExceededBehavior(LimitExceededBehavior.Ignore) @@ -87,6 +86,8 @@ void testGetPushingBatcher() { ThresholdBatcher>> batcherBar = batcherFactory.getPushingBatcher(new PartitionKey("bar")); + Mockito.verify(batchingSettings, Mockito.times(2)).getDelayThresholdDuration(); + Truth.assertThat(batcherFoo).isSameInstanceAs(batcherFoo2); Truth.assertThat(batcherFoo).isNotSameInstanceAs(batcherBar); } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallSettingsTest.java index a187f13354..b51a39b351 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallSettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallSettingsTest.java @@ -38,7 +38,6 @@ import java.util.Set; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class BatchingCallSettingsTest { @@ -82,11 +81,11 @@ void testBuilder() { Set retryCodes = Sets.newHashSet(Code.UNAVAILABLE); RetrySettings retrySettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) @@ -126,11 +125,11 @@ void testBuilderFromSettings() throws Exception { Set retryCodes = Sets.newHashSet(Code.UNAVAILABLE); RetrySettings retrySettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallableTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallableTest.java index 6792a53eb5..f31098ef2f 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallableTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingCallableTest.java @@ -45,7 +45,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class BatchingCallableTest { private ScheduledExecutorService batchingExecutor; @@ -65,7 +64,7 @@ void testBatchedCall() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(10)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(10)) .setElementCountThreshold(2L) .setRequestByteThreshold(1000L) .build(); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingTest.java index 392df7e376..675a51d72f 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/BatchingTest.java @@ -52,7 +52,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class BatchingTest { @@ -79,7 +78,7 @@ void teardown() { void batching() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(2L) .build(); BatchingCallSettings> batchingCallSettings = @@ -99,7 +98,7 @@ void batching() throws Exception { void batchingWithFlowControl() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(4L) .setRequestByteThreshold(null) .setFlowControlSettings( @@ -177,7 +176,7 @@ void batchingDisabled() throws Exception { void batchingWithBlockingCallThreshold() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(2L) .build(); BatchingCallSettings> batchingCallSettings = @@ -206,7 +205,7 @@ public ApiFuture> futureCall(LabeledIntList request, ApiCallContex void batchingException() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(2L) .build(); BatchingCallSettings> batchingCallSettings = diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/CallableTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/CallableTest.java index fe7e9264cb..55cb2f3024 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/CallableTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/CallableTest.java @@ -32,21 +32,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.api.core.ApiClock; import com.google.api.core.ApiFuture; import com.google.api.core.SettableApiFuture; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.testing.FakeCallContext; +import java.util.concurrent.ScheduledExecutorService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class CallableTest { @@ -58,9 +62,9 @@ class CallableTest { private RetrySettings retrySettings = RetrySettings.newBuilder() - .setInitialRpcTimeout(Duration.ofMillis(5L)) - .setMaxRpcTimeout(Duration.ofMillis(5L)) - .setTotalTimeout(Duration.ofMillis(10L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(5L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(5L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(10L)) .build(); @Spy private ApiCallContext callContext = FakeCallContext.createDefault(); @@ -76,14 +80,16 @@ class CallableTest { void testNonRetriedCallable() throws Exception { innerResult = SettableApiFuture.create(); when(innerCallable.futureCall(anyString(), any(ApiCallContext.class))).thenReturn(innerResult); - Duration timeout = Duration.ofMillis(5L); + java.time.Duration timeout = java.time.Duration.ofMillis(5L); String initialRequest = "Is your refrigerator running?"; String modifiedRequest = "What about now?"; RequestMutator requestMutator = (request -> modifiedRequest); UnaryCallSettings callSettings = - UnaryCallSettings.newUnaryCallSettingsBuilder().setSimpleTimeoutNoRetries(timeout).build(); + UnaryCallSettings.newUnaryCallSettingsBuilder() + .setSimpleTimeoutNoRetriesDuration(timeout) + .build(); UnaryCallable callable = Callables.retrying(innerCallable, callSettings, clientContext, requestMutator); String expectedResponse = "No, my refrigerator is not running!"; @@ -96,8 +102,8 @@ void testNonRetriedCallable() throws Exception { String expectedRequest = "What about now?"; assertEquals(expectedRequest, argumentCaptor.getValue()); verify(callContext, atLeastOnce()).getRetrySettings(); - verify(callContext).getTimeout(); - verify(callContext).withTimeout(timeout); + verify(callContext).getTimeoutDuration(); + verify(callContext).withTimeoutDuration(timeout); assertEquals(expectedResponse, futureResponse.get()); } @@ -112,14 +118,14 @@ void testNonRetriedCallableWithRetrySettings() throws Exception { UnaryCallSettings callSettings = UnaryCallSettings.newUnaryCallSettingsBuilder() - .setSimpleTimeoutNoRetries(Duration.ofMillis(10L)) + .setSimpleTimeoutNoRetriesDuration(java.time.Duration.ofMillis(10L)) .build(); UnaryCallable callable = Callables.retrying(innerCallable, callSettings, clientContext, requestMutator); String expectedResponse = "No, my refrigerator is not running!"; innerResult.set(expectedResponse); - Duration timeout = retrySettings.getInitialRpcTimeout(); + java.time.Duration timeout = retrySettings.getInitialRpcTimeoutDuration(); ApiFuture futureResponse = callable.futureCall(initialRequest, callContextWithRetrySettings); @@ -130,41 +136,67 @@ void testNonRetriedCallableWithRetrySettings() throws Exception { assertEquals(expectedRequest, argumentCaptor.getValue()); verify(callContextWithRetrySettings, atLeastOnce()).getRetrySettings(); - verify(callContextWithRetrySettings).getTimeout(); - verify(callContextWithRetrySettings).withTimeout(timeout); + verify(callContextWithRetrySettings).getTimeoutDuration(); + verify(callContextWithRetrySettings).withTimeoutDuration(timeout); assertEquals(expectedResponse, futureResponse.get()); } @Test void testNonRetriedServerStreamingCallable() throws Exception { - Duration timeout = Duration.ofMillis(5L); + java.time.Duration timeout = java.time.Duration.ofMillis(5L); ServerStreamingCallSettings callSettings = - ServerStreamingCallSettings.newBuilder().setSimpleTimeoutNoRetries(timeout).build(); + ServerStreamingCallSettings.newBuilder().setSimpleTimeoutNoRetriesDuration(timeout).build(); ServerStreamingCallable callable = Callables.retrying(innerServerStreamingCallable, callSettings, clientContext); callable.call("Is your refrigerator running?", callContext); verify(callContext, atLeastOnce()).getRetrySettings(); - verify(callContext).getTimeout(); - verify(callContext).withTimeout(timeout); + verify(callContext).getTimeoutDuration(); + verify(callContext).withTimeoutDuration(timeout); } @Test void testNonRetriedServerStreamingCallableWithRetrySettings() throws Exception { ServerStreamingCallSettings callSettings = ServerStreamingCallSettings.newBuilder() - .setSimpleTimeoutNoRetries(Duration.ofMillis(10L)) + .setSimpleTimeoutNoRetriesDuration(java.time.Duration.ofMillis(10L)) .build(); ServerStreamingCallable callable = Callables.retrying(innerServerStreamingCallable, callSettings, clientContext); - Duration timeout = retrySettings.getInitialRpcTimeout(); + java.time.Duration timeout = retrySettings.getInitialRpcTimeoutDuration(); callable.call("Is your refrigerator running?", callContextWithRetrySettings); verify(callContextWithRetrySettings, atLeastOnce()).getRetrySettings(); - verify(callContextWithRetrySettings).getTimeout(); - verify(callContextWithRetrySettings).withTimeout(timeout); + verify(callContextWithRetrySettings).getTimeoutDuration(); + verify(callContextWithRetrySettings).withTimeoutDuration(timeout); + } + + @Test + void testWatched_usesJavaTimeMethods() { + java.time.Duration timeout = java.time.Duration.ofMillis(5L); + doReturn(callContext).when(callContext).withStreamIdleTimeoutDuration(eq(timeout)); + Watchdog watchdog = + Watchdog.createDuration( + Mockito.mock(ApiClock.class), + java.time.Duration.ZERO, + Mockito.mock(ScheduledExecutorService.class)); + ClientContext clientContext = + ClientContext.newBuilder() + .setStreamWatchdog(watchdog) + .setDefaultCallContext(callContext) + .build(); + ServerStreamingCallSettings callSettings = + ServerStreamingCallSettings.newBuilder() + .setIdleTimeoutDuration(timeout) + .setWaitTimeoutDuration(timeout) + .build(); + ServerStreamingCallable callable = + Callables.retrying(innerServerStreamingCallable, callSettings, clientContext); + Callables.watched(callable, callSettings, clientContext); + verify(callContext, atLeastOnce()).withStreamIdleTimeoutDuration(eq(timeout)); + verify(callContext, atLeastOnce()).withStreamWaitTimeoutDuration(eq(timeout)); } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/CancellationTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/CancellationTest.java index 5b7c697223..0e24287131 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/CancellationTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/CancellationTest.java @@ -51,7 +51,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class CancellationTest { @@ -60,24 +59,24 @@ class CancellationTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(2L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(2L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(2L)) - .setInitialRpcTimeout(Duration.ofMillis(2L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(2L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(2L)) - .setTotalTimeout(Duration.ofMillis(20L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(20L)) .build(); private static final RetrySettings SLOW_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(3000L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(3000L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(3000L)) - .setInitialRpcTimeout(Duration.ofMillis(3000L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(3000L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(3000L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(3000L)) - .setTotalTimeout(Duration.ofMillis(3000L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(3000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(3000L)) .build(); private FakeApiClock fakeClock; diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/CheckingAttemptCallableTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/CheckingAttemptCallableTest.java index 650abc216b..5d7e905af6 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/CheckingAttemptCallableTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/CheckingAttemptCallableTest.java @@ -30,6 +30,7 @@ package com.google.api.gax.rpc; import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.verify; import com.google.api.core.SettableApiFuture; import com.google.api.gax.retrying.RetrySettings; @@ -40,12 +41,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class CheckingAttemptCallableTest { @@ -57,8 +58,6 @@ class CheckingAttemptCallableTest { @BeforeEach void setUp() { capturedCallContext = ArgumentCaptor.forClass(ApiCallContext.class); - Mockito.when(mockInnerCallable.futureCall(Mockito.any(), capturedCallContext.capture())) - .thenReturn(SettableApiFuture.create()); currentAttemptSettings = TimedAttemptSettings.newBuilder() @@ -66,9 +65,9 @@ void setUp() { .setAttemptCount(0) .setOverallAttemptCount(0) .setFirstAttemptStartTimeNanos(0) - .setRetryDelay(Duration.ofSeconds(1)) - .setRandomizedRetryDelay(Duration.ofSeconds(1)) - .setRpcTimeout(Duration.ZERO) + .setRetryDelayDuration(java.time.Duration.ofSeconds(1)) + .setRandomizedRetryDelayDuration(java.time.Duration.ofSeconds(1)) + .setRpcTimeoutDuration(java.time.Duration.ZERO) .build(); Mockito.when(mockExternalFuture.getAttemptSettings()) @@ -82,24 +81,45 @@ public TimedAttemptSettings answer(InvocationOnMock invocation) throws Throwable } @Test - void testRpcTimeout() { + void testRpcTimeout_gtZero_succeeds() { + Mockito.when(mockInnerCallable.futureCall(Mockito.any(), capturedCallContext.capture())) + .thenReturn(SettableApiFuture.create()); CheckingAttemptCallable callable = new CheckingAttemptCallable<>(mockInnerCallable, FakeCallContext.createDefault()); callable.setExternalFuture(mockExternalFuture); // Make sure that the rpc timeout is set - Duration timeout = Duration.ofSeconds(10); - currentAttemptSettings = currentAttemptSettings.toBuilder().setRpcTimeout(timeout).build(); + java.time.Duration timeout = java.time.Duration.ofSeconds(10); + currentAttemptSettings = + currentAttemptSettings.toBuilder().setRpcTimeoutDuration(timeout).build(); + + callable.call(); + + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(timeout); + // Make sure that subsequent attempts can extend the timeout + java.time.Duration longerTimeout = java.time.Duration.ofSeconds(20); + currentAttemptSettings = + currentAttemptSettings.toBuilder().setRpcTimeoutDuration(longerTimeout).build(); callable.call(); + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(longerTimeout); + } - assertThat(capturedCallContext.getValue().getTimeout()).isEqualTo(timeout); + @Test + void testRpcTimeout_gtZero_callsWithTimeoutDuration() { + FakeCallContext callContext = Mockito.spy(FakeCallContext.createDefault()); + Mockito.doReturn(callContext).when(callContext).withTimeoutDuration(ArgumentMatchers.any()); + CheckingAttemptCallable callable = + new CheckingAttemptCallable<>(Mockito.mock(UnaryCallable.class), callContext); + callable.setExternalFuture(mockExternalFuture); - // Make sure that subsequent attempts can extend the time out - Duration longerTimeout = Duration.ofSeconds(20); + // Make sure that the rpc timeout is set + java.time.Duration timeout = java.time.Duration.ofSeconds(10); currentAttemptSettings = - currentAttemptSettings.toBuilder().setRpcTimeout(longerTimeout).build(); + currentAttemptSettings.toBuilder().setRpcTimeoutDuration(timeout).build(); + callable.call(); - assertThat(capturedCallContext.getValue().getTimeout()).isEqualTo(longerTimeout); + + verify(callContext).withTimeoutDuration(timeout); } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java index f1449023d9..5efce3fbe9 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -46,6 +47,7 @@ import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.core.FixedExecutorProvider; import com.google.api.gax.core.NoCredentialsProvider; +import com.google.api.gax.rpc.testing.FakeCallContext; import com.google.api.gax.rpc.testing.FakeChannel; import com.google.api.gax.rpc.testing.FakeClientSettings; import com.google.api.gax.rpc.testing.FakeStubSettings; @@ -66,7 +68,6 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class ClientContextTest { private static final String DEFAULT_ENDPOINT = "test.googleapis.com"; @@ -281,17 +282,17 @@ private void runTest( Credentials credentials = Mockito.mock(Credentials.class); ApiClock clock = Mockito.mock(ApiClock.class); Watchdog watchdog = - Watchdog.create( + Watchdog.createDuration( Mockito.mock(ApiClock.class), - Duration.ZERO, + java.time.Duration.ZERO, Mockito.mock(ScheduledExecutorService.class)); - Duration watchdogCheckInterval = Duration.ofSeconds(11); + java.time.Duration watchdogCheckInterval = java.time.Duration.ofSeconds(11); builder.setExecutorProvider(executorProvider); builder.setTransportChannelProvider(transportProvider); builder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)); builder.setWatchdogProvider(FixedWatchdogProvider.create(watchdog)); - builder.setWatchdogCheckInterval(watchdogCheckInterval); + builder.setWatchdogCheckIntervalDuration(watchdogCheckInterval); builder.setClock(clock); HeaderProvider headerProvider = Mockito.mock(HeaderProvider.class); @@ -318,7 +319,7 @@ private void runTest( Truth.assertThat(clientContext.getCredentials()).isSameInstanceAs(credentials); Truth.assertThat(clientContext.getClock()).isSameInstanceAs(clock); Truth.assertThat(clientContext.getStreamWatchdog()).isSameInstanceAs(watchdog); - Truth.assertThat(clientContext.getStreamWatchdogCheckInterval()) + Truth.assertThat(clientContext.getStreamWatchdogCheckIntervalDuration()) .isEqualTo(watchdogCheckInterval); Truth.assertThat(clientContext.getHeaders()).isEqualTo(ImmutableMap.of("k1", "v1")); @@ -360,13 +361,13 @@ void testWatchdogProvider() throws IOException { builder.setExecutorProvider(new FakeExecutorProvider(executor, true)); builder.setTransportChannelProvider(transportProvider); - Duration watchdogCheckInterval = Duration.ofSeconds(11); + java.time.Duration watchdogCheckInterval = java.time.Duration.ofSeconds(11); builder.setWatchdogProvider( InstantiatingWatchdogProvider.create() .withClock(clock) - .withCheckInterval(watchdogCheckInterval) + .withCheckIntervalDuration(watchdogCheckInterval) .withExecutor(executor)); - builder.setWatchdogCheckInterval(watchdogCheckInterval); + builder.setWatchdogCheckIntervalDuration(watchdogCheckInterval); HeaderProvider headerProvider = Mockito.mock(HeaderProvider.class); Mockito.when(headerProvider.getHeaders()).thenReturn(ImmutableMap.of("k1", "v1")); @@ -1061,4 +1062,16 @@ void testCreateClientContext_setUniverseDomain() throws IOException { ClientContext clientContext = ClientContext.create(clientSettings); assertThat(clientContext.getUniverseDomain()).isEqualTo(universeDomain); } + + @Test + public void testStreamWatchdogInterval_backportMethodsBehaveCorrectly() { + final ClientContext.Builder builder = + ClientContext.newBuilder().setDefaultCallContext(FakeCallContext.createDefault()); + testDurationMethod( + 123L, + jt -> builder.setStreamWatchdogCheckIntervalDuration(jt).build(), + tt -> builder.setStreamWatchdogCheckInterval(tt).build(), + ct -> ct.getStreamWatchdogCheckIntervalDuration(), + ct -> ct.getStreamWatchdogCheckInterval()); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientSettingsTest.java index 3c4c1701ee..3e99f7471c 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientSettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientSettingsTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static org.junit.jupiter.api.Assertions.fail; import com.google.api.core.ApiClock; @@ -53,9 +54,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; +import java.util.function.Function; +import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class ClientSettingsTest { private static final String QUOTA_PROJECT_ID_KEY = "x-goog-user-project"; @@ -115,7 +117,8 @@ void testEmptyBuilder() throws Exception { Truth.assertThat(builder.getInternalHeaderProvider()).isInstanceOf(NoHeaderProvider.class); Truth.assertThat(builder.getWatchdogProvider()) .isInstanceOf(InstantiatingWatchdogProvider.class); - Truth.assertThat(builder.getWatchdogCheckInterval()).isGreaterThan(Duration.ZERO); + Truth.assertThat(builder.getWatchdogCheckIntervalDuration()) + .isGreaterThan(java.time.Duration.ZERO); Truth.assertThat(builder.getQuotaProjectId()).isNull(); FakeClientSettings settings = builder.build(); @@ -133,7 +136,8 @@ void testEmptyBuilder() throws Exception { .isSameInstanceAs(builder.getInternalHeaderProvider()); Truth.assertThat(settings.getWatchdogProvider()) .isInstanceOf(InstantiatingWatchdogProvider.class); - Truth.assertThat(settings.getWatchdogCheckInterval()).isGreaterThan(Duration.ZERO); + Truth.assertThat(settings.getWatchdogCheckIntervalDuration()) + .isGreaterThan(java.time.Duration.ZERO); Truth.assertThat((settings.getQuotaProjectId())).isSameInstanceAs(builder.getQuotaProjectId()); String settingsString = settings.toString(); @@ -159,7 +163,7 @@ void testBuilder() throws Exception { HeaderProvider headerProvider = Mockito.mock(HeaderProvider.class); HeaderProvider internalHeaderProvider = Mockito.mock(HeaderProvider.class); WatchdogProvider watchdogProvider = Mockito.mock(WatchdogProvider.class); - Duration watchdogCheckInterval = Duration.ofSeconds(13); + java.time.Duration watchdogCheckInterval = java.time.Duration.ofSeconds(13); String quotaProjectId = "test_quota_project_id"; builder.setExecutorProvider(executorProvider); @@ -169,7 +173,7 @@ void testBuilder() throws Exception { builder.setInternalHeaderProvider(internalHeaderProvider); builder.setClock(clock); builder.setWatchdogProvider(watchdogProvider); - builder.setWatchdogCheckInterval(watchdogCheckInterval); + builder.setWatchdogCheckIntervalDuration(watchdogCheckInterval); builder.setQuotaProjectId(quotaProjectId); // For backward compatibility, backgroundExecutorProvider is set to executorProvider @@ -181,7 +185,8 @@ void testBuilder() throws Exception { Truth.assertThat(builder.getHeaderProvider()).isSameInstanceAs(headerProvider); Truth.assertThat(builder.getInternalHeaderProvider()).isSameInstanceAs(internalHeaderProvider); Truth.assertThat(builder.getWatchdogProvider()).isSameInstanceAs(watchdogProvider); - Truth.assertThat(builder.getWatchdogCheckInterval()).isSameInstanceAs(watchdogCheckInterval); + Truth.assertThat(builder.getWatchdogCheckIntervalDuration()) + .isSameInstanceAs(watchdogCheckInterval); Truth.assertThat(builder.getQuotaProjectId()).isEqualTo(quotaProjectId); String builderString = builder.toString(); @@ -206,11 +211,11 @@ void testBuilderFromClientContext() throws Exception { FakeCallContext.createDefault().withEndpointContext(endpointContext); Map headers = Collections.singletonMap("spiffykey", "spiffyvalue"); Watchdog watchdog = - Watchdog.create( + Watchdog.createDuration( Mockito.mock(ApiClock.class), - Duration.ZERO, + java.time.Duration.ZERO, Mockito.mock(ScheduledExecutorService.class)); - Duration watchdogCheckInterval = Duration.ofSeconds(12); + java.time.Duration watchdogCheckInterval = java.time.Duration.ofSeconds(12); ClientContext clientContext = ClientContext.newBuilder() @@ -221,7 +226,7 @@ void testBuilderFromClientContext() throws Exception { .setDefaultCallContext(callContext) .setHeaders(headers) .setStreamWatchdog(watchdog) - .setStreamWatchdogCheckInterval(watchdogCheckInterval) + .setStreamWatchdogCheckIntervalDuration(watchdogCheckInterval) .setQuotaProjectId(QUOTA_PROJECT_ID_FROM_CONTEXT) .build(); @@ -240,7 +245,7 @@ void testBuilderFromClientContext() throws Exception { .containsEntry("spiffykey", "spiffyvalue"); Truth.assertThat(builder.getWatchdogProvider()).isInstanceOf(FixedWatchdogProvider.class); Truth.assertThat(builder.getWatchdogProvider().getWatchdog()).isSameInstanceAs(watchdog); - Truth.assertThat(builder.getWatchdogCheckInterval()).isEqualTo(watchdogCheckInterval); + Truth.assertThat(builder.getWatchdogCheckIntervalDuration()).isEqualTo(watchdogCheckInterval); Truth.assertThat(builder.getQuotaProjectId()).isEqualTo(QUOTA_PROJECT_ID_FROM_CONTEXT); } @@ -255,7 +260,7 @@ void testBuilderFromSettings() throws Exception { HeaderProvider headerProvider = Mockito.mock(HeaderProvider.class); HeaderProvider internalHeaderProvider = Mockito.mock(HeaderProvider.class); WatchdogProvider watchdogProvider = Mockito.mock(WatchdogProvider.class); - Duration watchdogCheckInterval = Duration.ofSeconds(14); + java.time.Duration watchdogCheckInterval = java.time.Duration.ofSeconds(14); String quotaProjectId = "test_builder_from_settings_quotaProjectId"; builder.setExecutorProvider(executorProvider); @@ -265,7 +270,7 @@ void testBuilderFromSettings() throws Exception { builder.setHeaderProvider(headerProvider); builder.setInternalHeaderProvider(internalHeaderProvider); builder.setWatchdogProvider(watchdogProvider); - builder.setWatchdogCheckInterval(watchdogCheckInterval); + builder.setWatchdogCheckIntervalDuration(watchdogCheckInterval); builder.setQuotaProjectId(quotaProjectId); FakeClientSettings settings = builder.build(); @@ -280,7 +285,8 @@ void testBuilderFromSettings() throws Exception { Truth.assertThat(newBuilder.getInternalHeaderProvider()) .isSameInstanceAs(internalHeaderProvider); Truth.assertThat(newBuilder.getWatchdogProvider()).isSameInstanceAs(watchdogProvider); - Truth.assertThat(newBuilder.getWatchdogCheckInterval()).isEqualTo(watchdogCheckInterval); + Truth.assertThat(newBuilder.getWatchdogCheckIntervalDuration()) + .isEqualTo(watchdogCheckInterval); Truth.assertThat(newBuilder.getQuotaProjectId()).isEqualTo(quotaProjectId); } @@ -539,4 +545,25 @@ void testBuilderFromClientContext_QuotaProjectId() { Truth.assertThat(builderQuotaFromAllSources.getQuotaProjectId()) .isEqualTo(QUOTA_PROJECT_ID_FROM_CONTEXT); } + + @Test + public void testWatchdogCheckInterval_backportMethodsBehaveCorrectly() { + final ClientSettings.Builder builder = new FakeClientSettings.Builder(); + // this helper lambda goes around the possible IOException thrown by + // ClientSettings.Builder.build() + final Function, ClientSettings> createClientSettings = + fn -> { + try { + return fn.get().build(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }; + testDurationMethod( + 123l, + jt -> createClientSettings.apply(() -> builder.setWatchdogCheckIntervalDuration(jt)), + tt -> createClientSettings.apply(() -> builder.setWatchdogCheckInterval(tt)), + cs -> cs.getWatchdogCheckIntervalDuration(), + cs -> cs.getWatchdogCheckInterval()); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/FixedWatchdogProviderTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/FixedWatchdogProviderTest.java index 4ec2dc4332..eb0355d90b 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/FixedWatchdogProviderTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/FixedWatchdogProviderTest.java @@ -30,12 +30,12 @@ package com.google.api.gax.rpc; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.core.ApiClock; import java.util.concurrent.ScheduledExecutorService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class FixedWatchdogProviderTest { @Test @@ -47,9 +47,9 @@ void testNull() { @Test void testSameInstance() { Watchdog watchdog = - Watchdog.create( + Watchdog.createDuration( Mockito.mock(ApiClock.class), - Duration.ZERO, + java.time.Duration.ZERO, Mockito.mock(ScheduledExecutorService.class)); WatchdogProvider provider = FixedWatchdogProvider.create(watchdog); @@ -59,9 +59,9 @@ void testSameInstance() { @Test void testNoModifications() { Watchdog watchdog = - Watchdog.create( + Watchdog.createDuration( Mockito.mock(ApiClock.class), - Duration.ZERO, + java.time.Duration.ZERO, Mockito.mock(ScheduledExecutorService.class)); WatchdogProvider provider = FixedWatchdogProvider.create(watchdog); @@ -72,7 +72,7 @@ void testNoModifications() { Throwable actualError = null; try { - provider.withCheckInterval(Duration.ofSeconds(10)); + provider.withCheckIntervalDuration(java.time.Duration.ofSeconds(10)); } catch (Throwable t) { actualError = t; } @@ -94,4 +94,18 @@ void testNoModifications() { } assertThat(actualError).isInstanceOf(UnsupportedOperationException.class); } + + @Test + public void testWithCheckInterval_backportMethodsBehaveTheSame() { + assertThrows( + UnsupportedOperationException.class, + () -> + FixedWatchdogProvider.create(null) + .withCheckIntervalDuration(java.time.Duration.ofMillis(123l))); + assertThrows( + UnsupportedOperationException.class, + () -> + FixedWatchdogProvider.create(null) + .withCheckInterval(org.threeten.bp.Duration.ofMillis(123l))); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/InstantiatingWatchdogProviderTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/InstantiatingWatchdogProviderTest.java index 04a183ef3f..2bceba43a1 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/InstantiatingWatchdogProviderTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/InstantiatingWatchdogProviderTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.truth.Truth.assertThat; import com.google.api.core.ApiClock; @@ -39,13 +40,12 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class InstantiatingWatchdogProviderTest { @Mock private ScheduledExecutorService executor; @Mock private ApiClock clock; - private Duration checkInterval = Duration.ofSeconds(11); + private java.time.Duration checkInterval = java.time.Duration.ofSeconds(11); @Test void happyPath() { @@ -58,7 +58,7 @@ void happyPath() { provider = provider.withClock(clock); assertThat(provider.needsCheckInterval()).isTrue(); - provider = provider.withCheckInterval(checkInterval); + provider = provider.withCheckIntervalDuration(checkInterval); assertThat(provider.shouldAutoClose()).isTrue(); @@ -71,7 +71,9 @@ void happyPath() { @Test void requiresExecutor() { WatchdogProvider provider = - InstantiatingWatchdogProvider.create().withCheckInterval(checkInterval).withClock(clock); + InstantiatingWatchdogProvider.create() + .withCheckIntervalDuration(checkInterval) + .withClock(clock); Throwable actualError = null; try { @@ -101,7 +103,7 @@ void requiresClock() { WatchdogProvider provider = InstantiatingWatchdogProvider.create() .withExecutor(executor) - .withCheckInterval(checkInterval); + .withCheckIntervalDuration(checkInterval); Throwable actualError = null; try { @@ -111,4 +113,17 @@ void requiresClock() { } assertThat(actualError).isInstanceOf(IllegalStateException.class); } + + @Test + public void testCheckInterval_backportMethodsBehaveCorrectly() { + final InstantiatingWatchdogProvider baseProvider = + (InstantiatingWatchdogProvider) + InstantiatingWatchdogProvider.create().withClock(clock).withExecutor(executor); + testDurationMethod( + 123l, + jt -> baseProvider.withCheckIntervalDuration(jt), + tt -> baseProvider.withCheckInterval(tt), + wp -> wp.getWatchdog().getScheduleIntervalDuration(), + wp -> wp.getWatchdog().getScheduleInterval()); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/OperationCallableImplTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/OperationCallableImplTest.java index 946328b042..b072c42bed 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/OperationCallableImplTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/OperationCallableImplTest.java @@ -71,35 +71,36 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; class OperationCallableImplTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(2L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(2L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(2L)) - .setInitialRpcTimeout(Duration.ofMillis(2L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(2L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(2L)) - .setTotalTimeout(Duration.ofMillis(10L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(10L)) .build(); private static final RetrySettings FAST_RECHECKING_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(1L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(1L)) - .setInitialRpcTimeout( - Duration.ZERO) // supposed to be ignored, but are not actually, so we set to zero + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1L)) + .setInitialRpcTimeoutDuration( + java.time.Duration + .ZERO) // supposed to be ignored, but are not actually, so we set to zero .setMaxAttempts(0) .setJittered(false) .setRpcTimeoutMultiplier( 1) // supposed to be ignored, but are not actually, so we set to one - .setMaxRpcTimeout( - Duration.ZERO) // supposed to be ignored, but are not actually, so we set to zero - .setTotalTimeout(Duration.ofMillis(5L)) + .setMaxRpcTimeoutDuration( + java.time.Duration + .ZERO) // supposed to be ignored, but are not actually, so we set to zero + .setTotalTimeoutDuration(java.time.Duration.ofMillis(5L)) .build(); private FakeChannel initialChannel; @@ -481,10 +482,10 @@ void testFutureCallPollRPCTimeout() throws Exception { // for LRO polling. They are not actually ignored in code, so they changing them // here has an actual affect. This test verifies that they work as such, but in // practice generated clients set the RPC timeouts to 0 to be ignored. - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofSeconds(1)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofSeconds(1)) .setRpcTimeoutMultiplier(2) - .setTotalTimeout(Duration.ofSeconds(5L)) + .setTotalTimeoutDuration(java.time.Duration.ofSeconds(5L)) .build(), clock); callSettings = callSettings.toBuilder().setPollingAlgorithm(pollingAlgorithm).build(); @@ -518,14 +519,17 @@ void testFutureCallPollRPCTimeout() throws Exception { callable.futureCall(2, FakeCallContext.createDefault()).get(10, TimeUnit.SECONDS); - List actualTimeouts = Lists.newArrayList(); + List actualTimeouts = Lists.newArrayList(); for (ApiCallContext callContext : callContextCaptor.getAllValues()) { - actualTimeouts.add(callContext.getTimeout()); + actualTimeouts.add(callContext.getTimeoutDuration()); } - List expectedTimeouts = - Lists.newArrayList(Duration.ofMillis(100), Duration.ofMillis(200), Duration.ofMillis(400)); + List expectedTimeouts = + Lists.newArrayList( + java.time.Duration.ofMillis(100), + java.time.Duration.ofMillis(200), + java.time.Duration.ofMillis(400)); assertThat(actualTimeouts).isEqualTo(expectedTimeouts); } @@ -555,11 +559,13 @@ void testFutureCallContextPropagation() throws Exception { FakeCallableFactory.createOperationCallable( initialCallable, callSettings, initialContext, longRunningClient); - ApiCallContext callContext = FakeCallContext.createDefault().withTimeout(Duration.ofMillis(10)); + ApiCallContext callContext = + FakeCallContext.createDefault().withTimeoutDuration(java.time.Duration.ofMillis(10)); callable.futureCall(2, callContext).get(10, TimeUnit.SECONDS); - assertThat(callContextCaptor.getValue().getTimeout()).isEqualTo(Duration.ofMillis(10)); + assertThat(callContextCaptor.getValue().getTimeoutDuration()) + .isEqualTo(java.time.Duration.ofMillis(10)); } @Test @@ -584,7 +590,7 @@ void testFutureCallPollDoneOnMany() throws Exception { OperationTimedPollAlgorithm.create( FAST_RECHECKING_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(iterationsCount)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(iterationsCount)) .build(), clock); callSettings = callSettings.toBuilder().setPollingAlgorithm(pollingAlgorithm).build(); @@ -692,7 +698,10 @@ void testFutureCallPollCancelOnLongTimeoutExceeded() throws Exception { pollingAlgorithm = OperationTimedPollAlgorithm.create( - FAST_RECHECKING_SETTINGS.toBuilder().setTotalTimeout(Duration.ofMillis(1000L)).build(), + FAST_RECHECKING_SETTINGS + .toBuilder() + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) + .build(), clock); callSettings = callSettings.toBuilder().setPollingAlgorithm(pollingAlgorithm).build(); @@ -1162,8 +1171,8 @@ private UnaryCallable mockGetOpSnapshotC public ApiFuture futureCall(RequestT request, ApiCallContext context) { FakeCallContext fakeCallContext = (FakeCallContext) context; if (fakeCallContext != null - && fakeCallContext.getTimeout() != null - && fakeCallContext.getTimeout().isZero()) { + && fakeCallContext.getTimeoutDuration() != null + && fakeCallContext.getTimeoutDuration().isZero()) { throw new DeadlineExceededException( "Invalid timeout of 0 s", null, diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/PagedCallSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/PagedCallSettingsTest.java index 8adb05ebf5..71b8af6490 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/PagedCallSettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/PagedCallSettingsTest.java @@ -36,7 +36,6 @@ import java.util.Set; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class PagedCallSettingsTest { @@ -72,11 +71,11 @@ void testBuilder() { Set retryCodes = Sets.newHashSet(Code.UNAVAILABLE); RetrySettings retrySettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) @@ -105,11 +104,11 @@ void testBuilderFromSettings() throws Exception { Set retryCodes = Sets.newHashSet(Code.UNAVAILABLE); RetrySettings retrySettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/RetryingTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/RetryingTest.java index 4bdc380744..488f9014f0 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/RetryingTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/RetryingTest.java @@ -53,7 +53,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class RetryingTest { @@ -66,24 +65,24 @@ class RetryingTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(2L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(2L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(2L)) - .setInitialRpcTimeout(Duration.ofMillis(2L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(2L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(2L)) - .setTotalTimeout(Duration.ofMillis(10L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(2L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(10L)) .build(); private static final RetrySettings FAILING_RETRY_SETTINGS = RetrySettings.newBuilder() .setMaxAttempts(2) - .setInitialRetryDelay(Duration.ofNanos(0L)) + .setInitialRetryDelayDuration(java.time.Duration.ofNanos(0L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(0L)) - .setInitialRpcTimeout(Duration.ofNanos(1L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(0L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofNanos(1L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofNanos(1L)) - .setTotalTimeout(Duration.ofNanos(1L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofNanos(1L)) + .setTotalTimeoutDuration(java.time.Duration.ofNanos(1L)) .build(); @BeforeEach @@ -149,8 +148,8 @@ void retryTotalTimeoutExceeded() { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) - .setMaxRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) .build(); assertThrows(ApiException.class, () -> assertRetrying(retrySettings)); @@ -167,8 +166,8 @@ void retryUsingContextTotalTimeoutExceeded() { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) - .setMaxRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(Integer.MAX_VALUE)) .build(); try { diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingAttemptCallableTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingAttemptCallableTest.java index 83c493bcee..b0b0de4554 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingAttemptCallableTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingAttemptCallableTest.java @@ -51,15 +51,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class ServerStreamingAttemptCallableTest { private MockServerStreamingCallable innerCallable; private AccumulatingObserver observer; private FakeRetryingFuture fakeRetryingFuture; private StreamResumptionStrategy resumptionStrategy; - private static Duration totalTimeout = Duration.ofHours(1); - private static final Duration attemptTimeout = Duration.ofMinutes(1); + private static java.time.Duration totalTimeout = java.time.Duration.ofHours(1); + private static final java.time.Duration attemptTimeout = java.time.Duration.ofMinutes(1); private FakeCallContext mockedCallContext; @BeforeEach @@ -89,17 +88,19 @@ private ServerStreamingAttemptCallable createCallable(ApiCallCon void testUserProvidedContextTimeout() { // Mock up the ApiCallContext as if the user provided a timeout and streamWaitTimeout. Mockito.doReturn(BaseApiTracer.getInstance()).when(mockedCallContext).getTracer(); - Mockito.doReturn(Duration.ofHours(5)).when(mockedCallContext).getTimeout(); - Mockito.doReturn(Duration.ofHours(5)).when(mockedCallContext).getStreamWaitTimeout(); + Mockito.doReturn(java.time.Duration.ofHours(5)).when(mockedCallContext).getTimeoutDuration(); + Mockito.doReturn(java.time.Duration.ofHours(5)) + .when(mockedCallContext) + .getStreamWaitTimeoutDuration(); ServerStreamingAttemptCallable callable = createCallable(mockedCallContext); callable.start(); // Ensure that the callable did not overwrite the user provided timeouts - Mockito.verify(mockedCallContext, Mockito.times(1)).getTimeout(); - Mockito.verify(mockedCallContext, Mockito.never()).withTimeout(totalTimeout); + Mockito.verify(mockedCallContext, Mockito.times(1)).getTimeoutDuration(); + Mockito.verify(mockedCallContext, Mockito.never()).withTimeoutDuration(totalTimeout); Mockito.verify(mockedCallContext, Mockito.never()) - .withStreamWaitTimeout(Mockito.any(Duration.class)); + .withStreamWaitTimeoutDuration(Mockito.any(java.time.Duration.class)); // Should notify outer observer Truth.assertThat(observer.controller).isNotNull(); @@ -123,20 +124,20 @@ void testUserProvidedContextTimeout() { void testNoUserProvidedContextTimeout() { // Mock up the ApiCallContext as if the user did not provide custom timeouts. Mockito.doReturn(BaseApiTracer.getInstance()).when(mockedCallContext).getTracer(); - Mockito.doReturn(null).when(mockedCallContext).getTimeout(); - Mockito.doReturn(null).when(mockedCallContext).getStreamWaitTimeout(); - Mockito.doReturn(mockedCallContext).when(mockedCallContext).withTimeout(attemptTimeout); + Mockito.doReturn(null).when(mockedCallContext).getTimeoutDuration(); + Mockito.doReturn(null).when(mockedCallContext).getStreamWaitTimeoutDuration(); + Mockito.doReturn(mockedCallContext).when(mockedCallContext).withTimeoutDuration(attemptTimeout); Mockito.doReturn(mockedCallContext) .when(mockedCallContext) - .withStreamWaitTimeout(Mockito.any(Duration.class)); + .withStreamWaitTimeoutDuration(Mockito.any(java.time.Duration.class)); ServerStreamingAttemptCallable callable = createCallable(mockedCallContext); callable.start(); // Ensure that the callable configured the timeouts via the Settings in the // absence of user-defined timeouts. - Mockito.verify(mockedCallContext, Mockito.times(1)).getTimeout(); - Mockito.verify(mockedCallContext, Mockito.times(1)).withTimeout(attemptTimeout); + Mockito.verify(mockedCallContext, Mockito.times(1)).getTimeoutDuration(); + Mockito.verify(mockedCallContext, Mockito.times(1)).withTimeoutDuration(attemptTimeout); // Should notify outer observer Truth.assertThat(observer.controller).isNotNull(); @@ -470,13 +471,14 @@ private static class FakeRetryingFuture extends AbstractApiFuture this.attemptCallable = attemptCallable; attemptSettings = TimedAttemptSettings.newBuilder() - .setGlobalSettings(RetrySettings.newBuilder().setTotalTimeout(totalTimeout).build()) + .setGlobalSettings( + RetrySettings.newBuilder().setTotalTimeoutDuration(totalTimeout).build()) .setFirstAttemptStartTimeNanos(0) .setAttemptCount(0) .setOverallAttemptCount(0) - .setRandomizedRetryDelay(Duration.ofMillis(1)) - .setRetryDelay(Duration.ofMillis(1)) - .setRpcTimeout(Duration.ofMinutes(1)) + .setRandomizedRetryDelayDuration(java.time.Duration.ofMillis(1)) + .setRetryDelayDuration(java.time.Duration.ofMillis(1)) + .setRpcTimeoutDuration(java.time.Duration.ofMinutes(1)) .build(); } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingCallSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingCallSettingsTest.java index ed794c8575..9ce548b8d9 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingCallSettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ServerStreamingCallSettingsTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.truth.Truth.assertThat; import com.google.api.gax.retrying.RetrySettings; @@ -36,7 +37,6 @@ import com.google.common.collect.ImmutableSet; import java.util.Set; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class ServerStreamingCallSettingsTest { @Test @@ -63,11 +63,11 @@ void retryableCodesVarArgs() { void retryableSettingsAreNotLost() { RetrySettings retrySettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) @@ -84,40 +84,40 @@ void retryableSettingsAreNotLost() { @Test void idleTimeoutIsNotLost() { - Duration idleTimeout = Duration.ofSeconds(5); + java.time.Duration idleTimeout = java.time.Duration.ofSeconds(5); ServerStreamingCallSettings.Builder builder = ServerStreamingCallSettings.newBuilder(); - builder.setIdleTimeout(idleTimeout); + builder.setIdleTimeoutDuration(idleTimeout); - assertThat(builder.getIdleTimeout()).isEqualTo(idleTimeout); - assertThat(builder.build().getIdleTimeout()).isEqualTo(idleTimeout); - assertThat(builder.build().toBuilder().getIdleTimeout()).isEqualTo(idleTimeout); + assertThat(builder.getIdleTimeoutDuration()).isEqualTo(idleTimeout); + assertThat(builder.build().getIdleTimeoutDuration()).isEqualTo(idleTimeout); + assertThat(builder.build().toBuilder().getIdleTimeoutDuration()).isEqualTo(idleTimeout); } @Test void waitTimeoutIsNotLost() { - Duration waitTimeout = Duration.ofSeconds(5); + java.time.Duration waitTimeout = java.time.Duration.ofSeconds(5); ServerStreamingCallSettings.Builder builder = ServerStreamingCallSettings.newBuilder(); - builder.setWaitTimeout(waitTimeout); + builder.setWaitTimeoutDuration(waitTimeout); - assertThat(builder.getWaitTimeout()).isEqualTo(waitTimeout); - assertThat(builder.build().getWaitTimeout()).isEqualTo(waitTimeout); - assertThat(builder.build().toBuilder().getWaitTimeout()).isEqualTo(waitTimeout); + assertThat(builder.getWaitTimeoutDuration()).isEqualTo(waitTimeout); + assertThat(builder.build().getWaitTimeoutDuration()).isEqualTo(waitTimeout); + assertThat(builder.build().toBuilder().getWaitTimeoutDuration()).isEqualTo(waitTimeout); } @Test void testRetrySettingsBuilder() { RetrySettings initialSettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) @@ -126,26 +126,49 @@ void testRetrySettingsBuilder() { ServerStreamingCallSettings.Builder builder = ServerStreamingCallSettings.newBuilder().setRetrySettings(initialSettings); - builder.retrySettings().setMaxRetryDelay(Duration.ofMinutes(1)); + builder.retrySettings().setMaxRetryDelayDuration(java.time.Duration.ofMinutes(1)); - assertThat(builder.getRetrySettings().getMaxRetryDelay()).isEqualTo(Duration.ofMinutes(1)); - assertThat(builder.build().getRetrySettings().getMaxRetryDelay()) - .isEqualTo(Duration.ofMinutes(1)); + assertThat(builder.getRetrySettings().getMaxRetryDelayDuration()) + .isEqualTo(java.time.Duration.ofMinutes(1)); + assertThat(builder.build().getRetrySettings().getMaxRetryDelayDuration()) + .isEqualTo(java.time.Duration.ofMinutes(1)); } @Test void testToString() { RetrySettings retrySettings = RetrySettings.newBuilder().build(); Set retryableCodes = ImmutableSet.of(StatusCode.Code.DEADLINE_EXCEEDED); - Duration idleTime = Duration.ofSeconds(100); + java.time.Duration idleTime = java.time.Duration.ofSeconds(100); ServerStreamingCallSettings serverCallSettings = ServerStreamingCallSettings.newBuilder() .setRetrySettings(retrySettings) .setRetryableCodes(retryableCodes) - .setIdleTimeout(idleTime) + .setIdleTimeoutDuration(idleTime) .build(); assertThat(serverCallSettings.toString()).contains("idleTimeout=" + idleTime); assertThat(serverCallSettings.toString()).contains("retryableCodes=" + retryableCodes); assertThat(serverCallSettings.toString()).contains("retrySettings=" + retrySettings); } + + @Test + public void testIdleTimeout_backportMethodsBehaveCorrectly() { + final ServerStreamingCallSettings.Builder builder = ServerStreamingCallSettings.newBuilder(); + testDurationMethod( + 123l, + jt -> builder.setIdleTimeoutDuration(jt).build(), + tt -> builder.setIdleTimeout(tt).build(), + cs -> cs.getIdleTimeoutDuration(), + cs -> cs.getIdleTimeout()); + } + + @Test + public void testWaitTimeout_backportMethodsBehaveCorrectly() { + final ServerStreamingCallSettings.Builder builder = ServerStreamingCallSettings.newBuilder(); + testDurationMethod( + 123l, + jt -> builder.setWaitTimeoutDuration(jt).build(), + tt -> builder.setWaitTimeout(tt).build(), + cs -> cs.getWaitTimeoutDuration(), + cs -> cs.getWaitTimeout()); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/StreamingRetryAlgorithmTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/StreamingRetryAlgorithmTest.java index b4ebfaae66..066e7ab4df 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/StreamingRetryAlgorithmTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/StreamingRetryAlgorithmTest.java @@ -44,31 +44,30 @@ import com.google.api.gax.retrying.TimedAttemptSettings; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class StreamingRetryAlgorithmTest { private static final RetrySettings DEFAULT_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(10L)) - .setInitialRpcTimeout(Duration.ofMillis(100L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100L)) .setMaxAttempts(10) - .setMaxRetryDelay(Duration.ofSeconds(10L)) - .setMaxRpcTimeout(Duration.ofSeconds(30L)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(10L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofSeconds(30L)) .setRetryDelayMultiplier(1.4) .setRpcTimeoutMultiplier(1.5) - .setTotalTimeout(Duration.ofMinutes(10L)) + .setTotalTimeoutDuration(java.time.Duration.ofMinutes(10L)) .build(); private static final RetrySettings CONTEXT_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(20L)) - .setInitialRpcTimeout(Duration.ofMillis(200L)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(20L)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(200L)) .setMaxAttempts(10) - .setMaxRetryDelay(Duration.ofSeconds(20L)) - .setMaxRpcTimeout(Duration.ofSeconds(60L)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(20L)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofSeconds(60L)) .setRetryDelayMultiplier(2.4) .setRpcTimeoutMultiplier(2.5) - .setTotalTimeout(Duration.ofMinutes(20L)) + .setTotalTimeoutDuration(java.time.Duration.ofMinutes(20L)) .build(); @Test @@ -83,7 +82,8 @@ void testFirstAttemptUsesDefaultSettings() { TimedAttemptSettings attempt = algorithm.createFirstAttempt(context); assertThat(attempt.getGlobalSettings()).isSameInstanceAs(DEFAULT_RETRY_SETTINGS); - assertThat(attempt.getRpcTimeout()).isEqualTo(DEFAULT_RETRY_SETTINGS.getInitialRpcTimeout()); + assertThat(attempt.getRpcTimeoutDuration()) + .isEqualTo(DEFAULT_RETRY_SETTINGS.getInitialRpcTimeoutDuration()); } @Test @@ -99,7 +99,8 @@ void testFirstAttemptUsesContextSettings() { TimedAttemptSettings attempt = algorithm.createFirstAttempt(context); assertThat(attempt.getGlobalSettings()).isSameInstanceAs(CONTEXT_RETRY_SETTINGS); - assertThat(attempt.getRpcTimeout()).isEqualTo(CONTEXT_RETRY_SETTINGS.getInitialRpcTimeout()); + assertThat(attempt.getRpcTimeoutDuration()) + .isEqualTo(CONTEXT_RETRY_SETTINGS.getInitialRpcTimeoutDuration()); } @Test @@ -172,7 +173,7 @@ void testNextAttemptResetsTimedSettings() { assertThat(third.getFirstAttemptStartTimeNanos()) .isEqualTo(first.getFirstAttemptStartTimeNanos()); // The timeout values are reset to the second call. - assertThat(third.getRpcTimeout()).isEqualTo(second.getRpcTimeout()); + assertThat(third.getRpcTimeoutDuration()).isEqualTo(second.getRpcTimeoutDuration()); } @Test diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/UnaryCallSettingsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/UnaryCallSettingsTest.java index 472383a4e9..a69efb22c3 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/UnaryCallSettingsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/UnaryCallSettingsTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.rpc; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -37,24 +38,24 @@ import com.google.common.collect.ImmutableSet; import java.util.Set; import org.junit.jupiter.api.Test; -import org.threeten.bp.Duration; class UnaryCallSettingsTest { @Test void testSetSimpleTimeoutNoRetries() { UnaryCallSettings.Builder builder = new UnaryCallSettings.Builder(); - builder.setSimpleTimeoutNoRetries(Duration.ofSeconds(13)); + builder.setSimpleTimeoutNoRetriesDuration(java.time.Duration.ofSeconds(13)); assertThat(builder.getRetryableCodes().size()).isEqualTo(0); assertThat(builder.getRetrySettings().getMaxAttempts()).isEqualTo(1); - assertThat(builder.getRetrySettings().getTotalTimeout()).isEqualTo(Duration.ofSeconds(13)); + assertThat(builder.getRetrySettings().getTotalTimeoutDuration()) + .isEqualTo(java.time.Duration.ofSeconds(13)); } @Test void testEquals() { UnaryCallSettings.Builder builder = new UnaryCallSettings.Builder(); - builder.setSimpleTimeoutNoRetries(Duration.ofSeconds(13)); + builder.setSimpleTimeoutNoRetriesDuration(java.time.Duration.ofSeconds(13)); UnaryCallSettings settings13 = builder.build(); assertEquals(settings13, settings13); @@ -63,7 +64,7 @@ void testEquals() { assertEquals(settings13.hashCode(), settings13.hashCode()); UnaryCallSettings.Builder builder5 = new UnaryCallSettings.Builder(); - builder5.setSimpleTimeoutNoRetries(Duration.ofSeconds(5)); + builder5.setSimpleTimeoutNoRetriesDuration(java.time.Duration.ofSeconds(5)); UnaryCallSettings settings5 = builder5.build(); assertNotEquals(settings13, settings5); @@ -74,11 +75,11 @@ void testEquals() { void testEquals_retrySettings() { RetrySettings initialSettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) @@ -111,11 +112,11 @@ void testEquals_retryableCodes() { void testRetrySettingsBuilder() { RetrySettings initialSettings = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(5)) - .setMaxRetryDelay(Duration.ofSeconds(1)) + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(5)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(1)) .setRetryDelayMultiplier(2) - .setInitialRpcTimeout(Duration.ofMillis(100)) - .setMaxRpcTimeout(Duration.ofMillis(200)) + .setInitialRpcTimeoutDuration(java.time.Duration.ofMillis(100)) + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(200)) .setRpcTimeoutMultiplier(1.1) .setJittered(true) .setMaxAttempts(10) @@ -124,11 +125,12 @@ void testRetrySettingsBuilder() { UnaryCallSettings.Builder builder = new UnaryCallSettings.Builder().setRetrySettings(initialSettings); - builder.retrySettings().setMaxRetryDelay(Duration.ofMinutes(1)); + builder.retrySettings().setMaxRetryDelayDuration(java.time.Duration.ofMinutes(1)); - assertThat(builder.getRetrySettings().getMaxRetryDelay()).isEqualTo(Duration.ofMinutes(1)); - assertThat(builder.build().getRetrySettings().getMaxRetryDelay()) - .isEqualTo(Duration.ofMinutes(1)); + assertThat(builder.getRetrySettings().getMaxRetryDelayDuration()) + .isEqualTo(java.time.Duration.ofMinutes(1)); + assertThat(builder.build().getRetrySettings().getMaxRetryDelayDuration()) + .isEqualTo(java.time.Duration.ofMinutes(1)); } @Test @@ -143,4 +145,17 @@ void testToString() { assertThat(unaryCallSettings.toString()).contains("retryableCodes=" + retryableCodes); assertThat(unaryCallSettings.toString()).contains("retrySettings=" + retrySettings); } + + @Test + public void testWatchDogCheckInterval_backportMethodsBehaveCorrectly() { + testDurationMethod( + 123l, + jt -> + UnaryCallSettings.newUnaryCallSettingsBuilder() + .setSimpleTimeoutNoRetriesDuration(jt) + .build(), + tt -> UnaryCallSettings.newUnaryCallSettingsBuilder().setSimpleTimeoutNoRetries(tt).build(), + ucs -> ucs.getRetrySettings().getTotalTimeoutDuration(), + ucs -> ucs.getRetrySettings().getTotalTimeout()); + } } diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/WatchdogTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/WatchdogTest.java index 0b96db78ab..fbcf5c3f2b 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/WatchdogTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/WatchdogTest.java @@ -48,15 +48,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; class WatchdogTest { private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(1); private FakeApiClock clock; - private final Duration checkInterval = Duration.ofMillis(1000); - private Duration waitTime = Duration.ofSeconds(10); - private Duration idleTime = Duration.ofMinutes(5); + private final java.time.Duration checkInterval = java.time.Duration.ofMillis(1000); + private java.time.Duration waitTime = java.time.Duration.ofSeconds(10); + private java.time.Duration idleTime = java.time.Duration.ofMinutes(5); private Watchdog watchdog; private MockServerStreamingCallable callable; @@ -66,11 +65,11 @@ class WatchdogTest { @BeforeEach void setUp() { clock = new FakeApiClock(0); - watchdog = Watchdog.create(clock, checkInterval, EXECUTOR); + watchdog = Watchdog.createDuration(clock, checkInterval, EXECUTOR); callable = new MockServerStreamingCallable<>(); innerObserver = new AccumulatingObserver<>(); - callable.call("request", watchdog.watch(innerObserver, waitTime, idleTime)); + callable.call("request", watchdog.watchDuration(innerObserver, waitTime, idleTime)); call = callable.popLastCall(); } @@ -130,7 +129,7 @@ void testIdleTimeout() throws InterruptedException { void testTimedOutBeforeStart() throws InterruptedException { MockServerStreamingCallable callable1 = new MockServerStreamingCallable<>(); AccumulatingObserver downstreamObserver1 = new AccumulatingObserver<>(); - ResponseObserver observer = watchdog.watch(downstreamObserver1, waitTime, idleTime); + ResponseObserver observer = watchdog.watchDuration(downstreamObserver1, waitTime, idleTime); clock.incrementNanoTime(idleTime.toNanos() + 1); // This should not remove callable1 from watched list watchdog.run(); @@ -157,7 +156,8 @@ void testTimedOutBeforeResponse() throws InterruptedException { new MockServerStreamingCallable<>(); AutoFlowControlObserver downstreamObserver = new AutoFlowControlObserver<>(); - autoFlowControlCallable.call("request", watchdog.watch(downstreamObserver, waitTime, idleTime)); + autoFlowControlCallable.call( + "request", watchdog.watchDuration(downstreamObserver, waitTime, idleTime)); MockServerStreamingCall call1 = autoFlowControlCallable.popLastCall(); clock.incrementNanoTime(idleTime.toNanos() + 1); @@ -180,13 +180,13 @@ void testTimedOutBeforeResponse() throws InterruptedException { void testMultiple() throws Exception { // Start stream1 AccumulatingObserver downstreamObserver1 = new AccumulatingObserver<>(); - callable.call("request", watchdog.watch(downstreamObserver1, waitTime, idleTime)); + callable.call("request", watchdog.watchDuration(downstreamObserver1, waitTime, idleTime)); MockServerStreamingCall call1 = callable.popLastCall(); downstreamObserver1.controller.get().request(1); // Start stream2 AccumulatingObserver downstreamObserver2 = new AccumulatingObserver<>(); - callable.call("req2", watchdog.watch(downstreamObserver2, waitTime, idleTime)); + callable.call("req2", watchdog.watchDuration(downstreamObserver2, waitTime, idleTime)); MockServerStreamingCall call2 = callable.popLastCall(); downstreamObserver2.controller.get().request(1); @@ -219,7 +219,7 @@ void testMultiple() throws Exception { void testWatchdogBeingClosed() { ScheduledFuture future = Mockito.mock(ScheduledFuture.class); ScheduledExecutorService mockExecutor = getMockExecutorService(future); - Watchdog underTest = Watchdog.create(clock, checkInterval, mockExecutor); + Watchdog underTest = Watchdog.createDuration(clock, checkInterval, mockExecutor); assertThat(underTest).isInstanceOf(BackgroundResource.class); underTest.close(); @@ -241,7 +241,7 @@ void awaitTermination_shouldReturnTrueIfFutureIsDone() throws Exception { TimeUnit timeUnit = TimeUnit.MILLISECONDS; ScheduledFuture future = Mockito.mock(ScheduledFuture.class); ScheduledExecutorService mockExecutor = getMockExecutorService(future); - Watchdog watchdog = Watchdog.create(clock, checkInterval, mockExecutor); + Watchdog watchdog = Watchdog.createDuration(clock, checkInterval, mockExecutor); watchdog.shutdown(); boolean actual = watchdog.awaitTermination(duration, timeUnit); @@ -256,7 +256,7 @@ void awaitTermination_shouldReturnFalseIfGettingFutureTimedOut() throws Exceptio ScheduledFuture future = Mockito.mock(ScheduledFuture.class); Mockito.doThrow(new TimeoutException()).when(future).get(duration, timeUnit); ScheduledExecutorService mockExecutor = getMockExecutorService(future); - Watchdog watchdog = Watchdog.create(clock, checkInterval, mockExecutor); + Watchdog watchdog = Watchdog.createDuration(clock, checkInterval, mockExecutor); boolean actual = watchdog.awaitTermination(duration, timeUnit); @@ -270,7 +270,7 @@ void awaitTermination_shouldReturnTrueIfFutureIsAlreadyCancelled() throws Except ScheduledFuture future = Mockito.mock(ScheduledFuture.class); Mockito.doThrow(new CancellationException()).when(future).get(duration, timeUnit); ScheduledExecutorService mockExecutor = getMockExecutorService(future); - Watchdog watchdog = Watchdog.create(clock, checkInterval, mockExecutor); + Watchdog watchdog = Watchdog.createDuration(clock, checkInterval, mockExecutor); boolean actual = watchdog.awaitTermination(duration, timeUnit); @@ -287,7 +287,7 @@ void awaitTermination_shouldReturnFalseIfGettingFutureThrowsExecutionException() .when(future) .get(duration, timeUnit); ScheduledExecutorService mockExecutor = getMockExecutorService(future); - Watchdog watchdog = Watchdog.create(clock, checkInterval, mockExecutor); + Watchdog watchdog = Watchdog.createDuration(clock, checkInterval, mockExecutor); boolean actual = watchdog.awaitTermination(duration, timeUnit); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/testing/FakeCallContext.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/testing/FakeCallContext.java index a075e02cc1..1cdefe435d 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/testing/FakeCallContext.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/testing/FakeCallContext.java @@ -29,6 +29,9 @@ */ package com.google.api.gax.rpc.testing; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; + import com.google.api.core.InternalApi; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; @@ -49,15 +52,14 @@ import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.threeten.bp.Duration; @InternalApi("for testing") public class FakeCallContext implements ApiCallContext { private final Credentials credentials; private final FakeChannel channel; - private final Duration timeout; - private final Duration streamWaitTimeout; - private final Duration streamIdleTimeout; + private final java.time.Duration timeout; + private final java.time.Duration streamWaitTimeout; + private final java.time.Duration streamIdleTimeout; private final ImmutableMap> extraHeaders; private final ApiCallContextOptions options; private final ApiTracer tracer; @@ -68,9 +70,9 @@ public class FakeCallContext implements ApiCallContext { private FakeCallContext( Credentials credentials, FakeChannel channel, - Duration timeout, - Duration streamWaitTimeout, - Duration streamIdleTimeout, + java.time.Duration timeout, + java.time.Duration streamWaitTimeout, + java.time.Duration streamIdleTimeout, ImmutableMap> extraHeaders, ApiCallContextOptions options, ApiTracer tracer, @@ -144,17 +146,17 @@ public ApiCallContext merge(ApiCallContext inputCallContext) { newCallCredentials = credentials; } - Duration newTimeout = fakeCallContext.timeout; + java.time.Duration newTimeout = fakeCallContext.timeout; if (newTimeout == null) { newTimeout = timeout; } - Duration newStreamWaitTimeout = fakeCallContext.streamWaitTimeout; + java.time.Duration newStreamWaitTimeout = fakeCallContext.streamWaitTimeout; if (newStreamWaitTimeout == null) { newStreamWaitTimeout = streamWaitTimeout; } - Duration newStreamIdleTimeout = fakeCallContext.streamIdleTimeout; + java.time.Duration newStreamIdleTimeout = fakeCallContext.streamIdleTimeout; if (newStreamIdleTimeout == null) { newStreamIdleTimeout = streamIdleTimeout; } @@ -240,19 +242,31 @@ public FakeChannel getChannel() { } @Override - public Duration getTimeout() { + public java.time.Duration getTimeoutDuration() { return timeout; } + @Override + public ApiCallContext withStreamWaitTimeout( + @Nullable org.threeten.bp.Duration streamWaitTimeout) { + return withStreamWaitTimeoutDuration(toJavaTimeDuration(streamWaitTimeout)); + } + @Nullable @Override - public Duration getStreamWaitTimeout() { + public java.time.Duration getStreamWaitTimeoutDuration() { return streamWaitTimeout; } + @Override + public ApiCallContext withStreamIdleTimeout( + @Nullable org.threeten.bp.Duration streamIdleTimeout) { + return withStreamIdleTimeoutDuration(toJavaTimeDuration(streamIdleTimeout)); + } + @Nullable @Override - public Duration getStreamIdleTimeout() { + public java.time.Duration getStreamIdleTimeoutDuration() { return streamIdleTimeout; } @@ -300,6 +314,11 @@ public FakeCallContext withEndpointContext(EndpointContext endpointContext) { endpointContext); } + @Override + public FakeCallContext withTimeout(@Nullable org.threeten.bp.Duration timeout) { + return withTimeoutDuration(toJavaTimeDuration(timeout)); + } + public FakeCallContext withChannel(FakeChannel channel) { return new FakeCallContext( this.credentials, @@ -316,7 +335,7 @@ public FakeCallContext withChannel(FakeChannel channel) { } @Override - public FakeCallContext withTimeout(Duration timeout) { + public FakeCallContext withTimeoutDuration(java.time.Duration timeout) { // Default RetrySettings use 0 for RPC timeout. Treat that as disabled timeouts. if (timeout != null && (timeout.isZero() || timeout.isNegative())) { timeout = null; @@ -341,8 +360,15 @@ public FakeCallContext withTimeout(Duration timeout) { this.endpointContext); } + @Nullable + @Override + public org.threeten.bp.Duration getTimeout() { + return toThreetenDuration(getTimeoutDuration()); + } + @Override - public ApiCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeout) { + public ApiCallContext withStreamWaitTimeoutDuration( + @Nullable java.time.Duration streamWaitTimeout) { return new FakeCallContext( this.credentials, this.channel, @@ -357,8 +383,15 @@ public ApiCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeout this.endpointContext); } + @Nullable @Override - public ApiCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTimeout) { + public org.threeten.bp.Duration getStreamWaitTimeout() { + return toThreetenDuration(getStreamWaitTimeoutDuration()); + } + + @Override + public ApiCallContext withStreamIdleTimeoutDuration( + @Nullable java.time.Duration streamIdleTimeout) { Preconditions.checkNotNull(streamIdleTimeout); return new FakeCallContext( this.credentials, @@ -374,6 +407,12 @@ public ApiCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTimeout this.endpointContext); } + @Nullable + @Override + public org.threeten.bp.Duration getStreamIdleTimeout() { + return toThreetenDuration(getStreamIdleTimeoutDuration()); + } + @Override public ApiCallContext withExtraHeaders(Map> extraHeaders) { Preconditions.checkNotNull(extraHeaders); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/tracing/BaseApiTracerTest.java b/gax-java/gax/src/test/java/com/google/api/gax/tracing/BaseApiTracerTest.java new file mode 100644 index 0000000000..8397efbb7d --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/tracing/BaseApiTracerTest.java @@ -0,0 +1,162 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.tracing; + +import org.junit.jupiter.api.Test; + +public class BaseApiTracerTest { + + @Test + public void testInScope() { + BaseApiTracer tracer = new BaseApiTracer(); + ApiTracer.Scope scope = tracer.inScope(); + scope.close(); + // No-op, so nothing to verify. + } + + @Test + public void testOperationSucceeded() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.operationSucceeded(); + // No-op, so nothing to verify. + } + + @Test + public void testOperationCancelled() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.operationCancelled(); + // No-op, so nothing to verify. + } + + @Test + public void testOperationFailed() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.operationFailed(new RuntimeException()); + // No-op, so nothing to verify. + } + + @Test + public void testConnectionSelected() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.connectionSelected("test-connection"); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptStarted() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptStarted(1); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptStartedWithRequest() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptStarted(new Object(), 1); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptSucceeded() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptSucceeded(); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptCancelled() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptCancelled(); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptFailedDuration() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptFailedDuration(new RuntimeException(), java.time.Duration.ofMillis(100)); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptFailed() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptFailed(new RuntimeException(), org.threeten.bp.Duration.ofMillis(100)); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptFailedRetriesExhausted() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptFailedRetriesExhausted(new RuntimeException()); + // No-op, so nothing to verify. + } + + @Test + public void testAttemptPermanentFailure() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.attemptPermanentFailure(new RuntimeException()); + // No-op, so nothing to verify. + } + + @Test + public void testLroStartFailed() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.lroStartFailed(new RuntimeException()); + // No-op, so nothing to verify. + } + + @Test + public void testLroStartSucceeded() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.lroStartSucceeded(); + // No-op, so nothing to verify. + } + + @Test + public void testResponseReceived() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.responseReceived(); + // No-op, so nothing to verify. + } + + @Test + public void testRequestSent() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.requestSent(); + // No-op, so nothing to verify. + } + + @Test + public void testBatchRequestSent() { + BaseApiTracer tracer = new BaseApiTracer(); + tracer.batchRequestSent(10, 100); + // No-op, so nothing to verify. + } +} diff --git a/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTestUtils.java b/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTestUtils.java new file mode 100644 index 0000000000..fd9477becb --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTestUtils.java @@ -0,0 +1,51 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.tracing; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.lang.reflect.Method; + +public class MetricsTestUtils { + public static void reportFailedAttempt(ApiTracer tracer, Exception ex, Object delayValue) { + try { + final String methodName = + delayValue.getClass().getName().startsWith("java.time") + ? "attemptFailedDuration" + : "attemptFailed"; + Method attemptFailed = + tracer.getClass().getDeclaredMethod(methodName, Throwable.class, delayValue.getClass()); + attemptFailed.invoke(tracer, ex, delayValue); + } catch (Exception e) { + fail(); + throw new RuntimeException(e); + } + } +} diff --git a/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTracerTest.java b/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTracerTest.java index f409d27ec4..18162f1ee9 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTracerTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTracerTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.tracing; +import static com.google.api.gax.tracing.MetricsTestUtils.reportFailedAttempt; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyDouble; @@ -48,7 +49,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class MetricsTracerTest { @@ -130,7 +130,16 @@ void testAttemptSucceeded_recordsAttributes() { } @Test - void testAttemptFailed_recordsAttributes() { + void testAttemptFailed_usingJavaTime_recordsAttributes() { + testAttemptFailed_recordsAttributes(java.time.Duration.ofMillis(2)); + } + + @Test + public void testAttemptFailed_usingThreeten_recordsAttributes() { + testAttemptFailed_recordsAttributes(org.threeten.bp.Duration.ofMillis(2)); + } + + public void testAttemptFailed_recordsAttributes(final Object attemptFailedValue) { // initialize mock-request Object mockFailedRequest = new Object(); @@ -139,7 +148,7 @@ void testAttemptFailed_recordsAttributes() { ApiException error0 = new NotFoundException( "invalid argument", null, new FakeStatusCode(Code.INVALID_ARGUMENT), false); - metricsTracer.attemptFailed(error0, Duration.ofMillis(2)); + reportFailedAttempt(metricsTracer, error0, attemptFailedValue); Map attributes = getAttributes(Code.INVALID_ARGUMENT); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpencensusTracerTest.java b/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpencensusTracerTest.java index d407ca7157..8c495623cc 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpencensusTracerTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpencensusTracerTest.java @@ -29,6 +29,7 @@ */ package com.google.api.gax.tracing; +import static com.google.api.gax.tracing.MetricsTestUtils.reportFailedAttempt; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; @@ -56,7 +57,6 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class OpencensusTracerTest { @@ -73,13 +73,22 @@ void setUp() { } @Test - void testUnarySuccessExample() { + void testUnarySuccessExample_javaTime() { + testUnarySuccessExample(java.time.Duration.ofMillis(5)); + } + + @Test + public void testUnarySuccessExample_threeten() { + testUnarySuccessExample(org.threeten.bp.Duration.ofMillis(5)); + } + + public void testUnarySuccessExample(Object attemptFailedValue) { tracer.attemptStarted(0); tracer.connectionSelected("1"); ApiException error0 = new DeadlineExceededException( "deadline exceeded", null, new FakeStatusCode(Code.DEADLINE_EXCEEDED), true); - tracer.attemptFailed(error0, Duration.ofMillis(5)); + reportFailedAttempt(tracer, error0, attemptFailedValue); tracer.attemptStarted(1); tracer.connectionSelected("2"); @@ -125,12 +134,21 @@ void testBatchExample() { } @Test - void testLongRunningExample() { + void testLongRunningExample_javaTime() { + testLongRunningExample(java.time.Duration.ofMillis(5)); + } + + @Test + public void testLongRunningExample_threeten() { + testLongRunningExample(org.threeten.bp.Duration.ofMillis(5)); + } + + public void testLongRunningExample(Object attemptFailedValue) { tracer = new OpencensusTracer(internalTracer, span, OperationType.LongRunning); // Initial poll of the initial rpc tracer.attemptStarted(0); - tracer.attemptFailed(null, Duration.ofMillis(5)); + reportFailedAttempt(tracer, null, attemptFailedValue); // Initial rpc finished tracer.lroStartSucceeded(); @@ -249,12 +267,21 @@ void testFailureExample() { } @Test - void testResponseCount() { + void testResponseCount_javaTime() { + testResponseCount(java.time.Duration.ofMillis(5)); + } + + @Test + public void testResponseCount_threeten() { + testResponseCount(java.time.Duration.ofMillis(5)); + } + + public void testResponseCount(Object attemptFailedValue) { // Initial attempt got 2 messages, then failed tracer.attemptStarted(0); tracer.responseReceived(); tracer.responseReceived(); - tracer.attemptFailed(new RuntimeException(), Duration.ofMillis(1)); + reportFailedAttempt(tracer, new RuntimeException(), attemptFailedValue); // Next attempt got 1 message, then successfully finished the attempt and the logical operation. tracer.attemptStarted(1); @@ -277,12 +304,21 @@ void testResponseCount() { } @Test - void testRequestCount() { + void testRequestCount_javaTime() { + testRequestCount(java.time.Duration.ofMillis(2)); + } + + @Test + public void testRequestCount_threeten() { + testRequestCount(org.threeten.bp.Duration.ofMillis(2)); + } + + public void testRequestCount(Object attemptFailedValue) { // Initial attempt sent 2 messages, then failed tracer.attemptStarted(0); tracer.requestSent(); tracer.requestSent(); - tracer.attemptFailed(new RuntimeException(), Duration.ofMillis(1)); + reportFailedAttempt(tracer, new RuntimeException(), attemptFailedValue); // Next attempt sent 1 message, then successfully finished the attempt and the logical // operation. @@ -306,9 +342,18 @@ void testRequestCount() { } @Test - void testAttemptNumber() { + void testAttemptNumber_javaTime() { + testAttemptNumber(java.time.Duration.ofMillis(5)); + } + + @Test + public void testAttemptNumber_threeten() { + testAttemptNumber(org.threeten.bp.Duration.ofMillis(5)); + } + + public void testAttemptNumber(Object attemptFailedValue) { tracer.attemptStarted(0); - tracer.attemptFailed(new RuntimeException(), Duration.ofMillis(1)); + reportFailedAttempt(tracer, new RuntimeException(), attemptFailedValue); tracer.attemptStarted(1); tracer.attemptSucceeded(); tracer.operationSucceeded(); @@ -330,10 +375,11 @@ void testAttemptNumber() { @Test void testStatusCode() { tracer.attemptStarted(0); - tracer.attemptFailed( + reportFailedAttempt( + tracer, new DeadlineExceededException( "deadline exceeded", null, new FakeStatusCode(Code.DEADLINE_EXCEEDED), true), - Duration.ofMillis(1)); + java.time.Duration.ofMillis(1)); tracer.attemptStarted(1); ApiException permanentError = diff --git a/gax-java/gax/src/test/java/com/google/api/gax/tracing/TracedCallableTest.java b/gax-java/gax/src/test/java/com/google/api/gax/tracing/TracedCallableTest.java index d0a6ec2df0..86c72fbd33 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/tracing/TracedCallableTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/tracing/TracedCallableTest.java @@ -52,7 +52,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.threeten.bp.Duration; @ExtendWith(MockitoExtension.class) class TracedCallableTest { @@ -96,7 +95,7 @@ void testNonRetriedCallable() throws Exception { // Verify that callables configured to not retry have the appropriate tracer interactions. UnaryCallSettings callSettings = UnaryCallSettings.newUnaryCallSettingsBuilder() - .setSimpleTimeoutNoRetries(Duration.ofMillis(5L)) + .setSimpleTimeoutNoRetriesDuration(java.time.Duration.ofMillis(5L)) .build(); UnaryCallable callable = setupTracedUnaryCallable(callSettings); innerResult.set("No, my refrigerator is not running!"); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionTestUtils.java b/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionTestUtils.java new file mode 100644 index 0000000000..bc49bec95e --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionTestUtils.java @@ -0,0 +1,153 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.function.Function; + +public class TimeConversionTestUtils { + + /** + * Confirms that the behavior of getters and setters of an Instant property (both {@link + * java.time.Instant} and {@link org.threeten.bp.Instant}) is the same. + * + * @param testValue the value in millis to be tested + * @param javaTimeTargetSupplier a supplier of a {@link Target} that is created using an {@link + * java.time.Instant} + * @param threetenTargetSupplier a supplier of a {@link Target} that is created using an {@link + * org.threeten.bp.Instant} + * @param javaTimeGetter a getter of the {@link java.time.Instant} obtained from the instance of + * {@link Target} + * @param threetenGetter a getter of the {{@link org.threeten.bp.Instant} obtained from the + * instance of {@link Target} + * @param the type of the target containing the Instant property + */ + public static void testInstantMethod( + Long testValue, + Function javaTimeTargetSupplier, + Function threetenTargetSupplier, + Function javaTimeGetter, + Function threetenGetter) { + Function javaTimeTester = value -> value.toEpochMilli(); + Function threetenTester = value -> value.toEpochMilli(); + java.time.Instant javaTimeSupplierValue = + testValue == null ? null : java.time.Instant.ofEpochMilli(testValue); + org.threeten.bp.Instant threetenSupplierValue = + testValue == null ? null : org.threeten.bp.Instant.ofEpochMilli(testValue); + testTimeObjectMethod( + testValue, + javaTimeSupplierValue, + javaTimeTargetSupplier, + javaTimeGetter, + threetenGetter, + javaTimeTester, + threetenTester); + testTimeObjectMethod( + testValue, + threetenSupplierValue, + threetenTargetSupplier, + javaTimeGetter, + threetenGetter, + javaTimeTester, + threetenTester); + } + + /** + * Confirms that the behavior of getters and setters of a Duration property (both {@link + * java.time.Duration} and {@link org.threeten.bp.Duration}) is the same. + * + * @param testValue the value in millis to be tested + * @param javaTimeTargetSupplier a supplier of a {@link Target} that is created using an {@link + * java.time.Duration} + * @param threetenTargetSupplier a supplier of a {@link Target} that is created using an {@link + * org.threeten.bp.Duration} + * @param javaTimeGetter a getter of the {@link java.time.Duration} obtained from the instance of + * {@link Target} + * @param threetenGetter a getter of the {{@link org.threeten.bp.Duration} obtained from the + * instance of {@link Target} + * @param the type of the target containing the Duration property + */ + public static void testDurationMethod( + Long testValue, + Function javaTimeTargetSupplier, + Function threetenTargetSupplier, + Function javaTimeGetter, + Function threetenGetter) { + Function javaTimeTester = value -> value.toMillis(); + Function threetenTester = value -> value.toMillis(); + java.time.Duration javaTimeSupplierValue = + testValue == null ? null : java.time.Duration.ofMillis(testValue); + org.threeten.bp.Duration threetenSupplierValue = + testValue == null ? null : org.threeten.bp.Duration.ofMillis(testValue); + testTimeObjectMethod( + testValue, + javaTimeSupplierValue, + javaTimeTargetSupplier, + javaTimeGetter, + threetenGetter, + javaTimeTester, + threetenTester); + testTimeObjectMethod( + testValue, + threetenSupplierValue, + threetenTargetSupplier, + javaTimeGetter, + threetenGetter, + javaTimeTester, + threetenTester); + } + + /** + * Contains the common implementation of {@link #testInstantMethod(Long, Function, Function, + * Function, Function)} and {@link #testDurationMethod(Long, Function, Function, Function, + * Function)} and performs the corresponding assertions. + */ + private static void testTimeObjectMethod( + Long testValue, + SupplierType targetSupplierValue, + Function targetSupplier, + Function javaTimeGetter, + Function threetenGetter, + Function javaTimeTester, + Function threetenTester) { + Target target = targetSupplier.apply(targetSupplierValue); + JavaTime javaTimeValue = javaTimeGetter.apply(target); + Threeten threetenValue = threetenGetter.apply(target); + if (testValue == null) { + assertNull(javaTimeValue); + assertNull(threetenValue); + } else { + assertEquals(testValue.longValue(), javaTimeTester.apply(javaTimeValue).longValue()); + assertEquals(testValue.longValue(), threetenTester.apply(threetenValue).longValue()); + } + } +} diff --git a/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionUtilsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionUtilsTest.java new file mode 100644 index 0000000000..e288a06bae --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionUtilsTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2024 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.google.api.gax.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +public class TimeConversionUtilsTest { + + final org.threeten.bp.Duration ttDuration = org.threeten.bp.Duration.ofMillis(123); + final org.threeten.bp.Instant ttInstant = org.threeten.bp.Instant.ofEpochMilli(123); + final java.time.Duration jtDuration = java.time.Duration.ofMillis(345); + final java.time.Instant jtInstant = java.time.Instant.ofEpochMilli(345); + + @Test + void testToJavaTimeDuration_validInput_succeeds() { + assertEquals( + ttDuration.toMillis(), TimeConversionUtils.toJavaTimeDuration(ttDuration).toMillis()); + assertNull(TimeConversionUtils.toJavaTimeDuration(null)); + } + + @Test + void testToThreetenTimeDuration_validInput_succeeds() { + assertEquals( + jtDuration.toMillis(), TimeConversionUtils.toThreetenDuration(jtDuration).toMillis()); + assertNull(TimeConversionUtils.toThreetenDuration(null)); + } + + @Test + void testToJavaTimeInstant_validInput_succeeds() { + assertEquals( + ttInstant.toEpochMilli(), TimeConversionUtils.toJavaTimeInstant(ttInstant).toEpochMilli()); + assertNull(TimeConversionUtils.toJavaTimeInstant(null)); + } + + @Test + void testToThreetenTimeInstant_validInput_succeeds() { + assertEquals( + jtInstant.toEpochMilli(), TimeConversionUtils.toThreetenInstant(jtInstant).toEpochMilli()); + assertNull(TimeConversionUtils.toThreetenInstant(null)); + } +} diff --git a/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITTimeObjectsPropagationTest.java b/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITTimeObjectsPropagationTest.java new file mode 100644 index 0000000000..f7f801f627 --- /dev/null +++ b/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITTimeObjectsPropagationTest.java @@ -0,0 +1,64 @@ +package com.google.showcase.v1beta1.it; + +import static org.junit.Assert.assertEquals; + +import com.google.api.gax.retrying.RetrySettings; +import org.junit.Test; + +/** + * Tests to confirm that usage of retry settings can be done regardless of whether threeten or + * java.time is being used + */ +public class ITTimeObjectsPropagationTest { + @Test + public void testRetrySettings_fromJavaTimeHasEquivalentThreetenValues() { + java.time.Duration javaTimeCommonValue = java.time.Duration.ofMillis(123l); + org.threeten.bp.Duration threetenConvertedValue = + org.threeten.bp.Duration.ofMillis(javaTimeCommonValue.toMillis()); + RetrySettings javaTimeRetrySettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(javaTimeCommonValue) + .setMaxRetryDelayDuration(javaTimeCommonValue) + .setInitialRpcTimeoutDuration(javaTimeCommonValue) + .setMaxRpcTimeoutDuration(javaTimeCommonValue) + .setTotalTimeoutDuration(javaTimeCommonValue) + .build(); + + assertEquals( + threetenConvertedValue.toMillis(), javaTimeRetrySettings.getInitialRetryDelay().toMillis()); + assertEquals( + threetenConvertedValue.toMillis(), javaTimeRetrySettings.getMaxRetryDelay().toMillis()); + assertEquals( + threetenConvertedValue.toMillis(), javaTimeRetrySettings.getInitialRpcTimeout().toMillis()); + assertEquals( + threetenConvertedValue.toMillis(), javaTimeRetrySettings.getMaxRpcTimeout().toMillis()); + assertEquals( + threetenConvertedValue.toMillis(), javaTimeRetrySettings.getTotalTimeout().toMillis()); + } + + @Test + public void testRetrySettings_fromThreetenHasEquivalentJavaTimeValues() { + org.threeten.bp.Duration threetenCommonValue = org.threeten.bp.Duration.ofMillis(123l); + java.time.Duration javaTimeConvertedValue = + java.time.Duration.ofMillis(threetenCommonValue.toMillis()); + RetrySettings threetenRetrySettings = + RetrySettings.newBuilder() + .setInitialRetryDelay(threetenCommonValue) + .setMaxRetryDelay(threetenCommonValue) + .setInitialRpcTimeout(threetenCommonValue) + .setMaxRpcTimeout(threetenCommonValue) + .setTotalTimeout(threetenCommonValue) + .build(); + + assertEquals( + javaTimeConvertedValue.toMillis(), threetenRetrySettings.getInitialRetryDelay().toMillis()); + assertEquals( + javaTimeConvertedValue.toMillis(), threetenRetrySettings.getMaxRetryDelay().toMillis()); + assertEquals( + javaTimeConvertedValue.toMillis(), threetenRetrySettings.getInitialRpcTimeout().toMillis()); + assertEquals( + javaTimeConvertedValue.toMillis(), threetenRetrySettings.getMaxRpcTimeout().toMillis()); + assertEquals( + javaTimeConvertedValue.toMillis(), threetenRetrySettings.getTotalTimeout().toMillis()); + } +}