diff --git a/gax-java/gax-grpc/clirr-ignored-differences.xml b/gax-java/gax-grpc/clirr-ignored-differences.xml new file mode 100644 index 0000000000..5af8ca965a --- /dev/null +++ b/gax-java/gax-grpc/clirr-ignored-differences.xml @@ -0,0 +1,9 @@ + + + + + 7002 + com/google/api/gax/grpc/InstantiatingGrpcChannelProvider$Builder + org.threeten.bp.Duration * + + 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..7d7fab0ee2 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,18 @@ public GrpcCallContext withEndpointContext(EndpointContext endpointContext) { endpointContext); } + /** + * Overload of {@link #withTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ @Override - public GrpcCallContext withTimeout(@Nullable Duration timeout) { + @ObsoleteApi("Use withTimeoutDuration(java.time.Duration) instead") + public GrpcCallContext withTimeout(@Nullable org.threeten.bp.Duration timeout) { + return withTimeoutDuration(toJavaTimeDuration(timeout)); + } + + @Override + 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; @@ -257,15 +270,34 @@ public GrpcCallContext withTimeout(@Nullable Duration timeout) { @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; } + /** + * Overload of {@link #withStreamWaitTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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 +315,26 @@ public GrpcCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeou endpointContext); } + /** + * Overload of {@link #withStreamIdleTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + * + * @param streamIdleTimeout + * @return + */ + @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 +471,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 +543,39 @@ public CallOptions getCallOptions() { return callOptions; } + /** Backport of {@link #getStreamWaitTimeoutDuration()} */ + @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; } + @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 5969ed4693..889c71c1a6 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,10 +29,14 @@ */ 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.InternalExtensionOnly; +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; @@ -68,7 +72,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; @@ -452,13 +455,23 @@ public String getEndpoint() { return endpoint; } + @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; } + @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; } @@ -502,8 +515,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; @@ -641,25 +654,44 @@ public Integer getMaxInboundMetadataSize() { return maxInboundMetadataSize; } + /** + * Overload of {@link #setKeepAliveTime(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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; } + /** Backport of {@link #getKeepAliveTimeDuration()} */ + @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; } + @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; } /** 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..853242eedd 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 public void testWithNegativeTimeout() { - assertNull(GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(-1L)).getTimeout()); + assertNull( + GrpcCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(-1L)) + .getTimeoutDuration()); } @Test public void testWithZeroTimeout() { - assertNull(GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(0L)).getTimeout()); + assertNull( + GrpcCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(0L)) + .getTimeoutDuration()); } @Test public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 a274512e14..6a38229274 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 @@ -61,7 +61,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class GrpcCallableFactoryTest { @@ -106,7 +105,7 @@ public void createServerStreamingCallableRetryableExceptions() { ServerStreamingCallSettings.newBuilder() .setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofSeconds(1)) + .setTotalTimeout(java.time.Duration.ofSeconds(1)) .setMaxAttempts(1) .build()) .build(); @@ -131,7 +130,7 @@ public void createServerStreamingCallableRetryableExceptions() { .setRetryableCodes(Code.INVALID_ARGUMENT) .setRetrySettings( RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofSeconds(1)) + .setTotalTimeout(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 eb9277b2e1..1b6f332dc8 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.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; public class GrpcClientCallsTest { @@ -195,10 +194,11 @@ public 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 @@ public 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 @@ public 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 @@ public 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 96d7cf1063..082b2a15ef 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 @@ -57,7 +57,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class GrpcDirectStreamControllerTest { @@ -101,11 +100,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)) + .setTotalTimeout(java.time.Duration.ofMinutes(1)) + .setInitialRpcTimeout(java.time.Duration.ofMillis(1)) + .setMaxRpcTimeout(java.time.Duration.ofMillis(1)) + .setInitialRetryDelay(java.time.Duration.ofMillis(1)) + .setMaxRetryDelay(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 20bceeae2c..ecb1148420 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 @@ -71,22 +71,21 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class GrpcLongRunningTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(1L)) + .setInitialRetryDelay(java.time.Duration.ofMillis(1L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(1L)) - .setInitialRpcTimeout(Duration.ofMillis(1L)) + .setMaxRetryDelay(java.time.Duration.ofMillis(1L)) + .setInitialRpcTimeout(java.time.Duration.ofMillis(1L)) .setMaxAttempts(0) .setJittered(false) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(1L)) - .setTotalTimeout(Duration.ofMillis(5L)) + .setMaxRpcTimeout(java.time.Duration.ofMillis(1L)) + .setTotalTimeout(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 a58d10ffc6..ae421232f1 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 @@ -29,6 +29,7 @@ */ package com.google.api.gax.grpc; +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.Assert.assertEquals; @@ -48,6 +49,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; @@ -56,6 +58,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.function.Function; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.stream.Collectors; @@ -65,7 +68,6 @@ import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class InstantiatingGrpcChannelProviderTest extends AbstractMtlsTransportChannelTest { @@ -94,20 +96,45 @@ public void testEndpointBadPort() { @Test public 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 @@ -156,8 +183,8 @@ public void testWithPoolSize() throws IOException { @Test public 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(); @@ -170,9 +197,9 @@ public 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) @@ -183,8 +210,8 @@ public 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); @@ -619,6 +646,7 @@ public void testLogDirectPathMisconfigNotOnGCE() throws Exception { } 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 e24e36c686..a556a4ddc3 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.Assert.assertEquals; import com.google.api.gax.batching.BatchingSettings; @@ -58,11 +59,12 @@ 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.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class SettingsTest { @@ -112,13 +114,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)) + .setMaxRetryDelay(java.time.Duration.ofMillis(1000L)) + .setInitialRpcTimeout(java.time.Duration.ofMillis(2000L)) .setRpcTimeoutMultiplier(1.5) - .setMaxRpcTimeout(Duration.ofMillis(30000L)) - .setTotalTimeout(Duration.ofMillis(45000L)) + .setMaxRpcTimeout(java.time.Duration.ofMillis(30000L)) + .setTotalTimeout(java.time.Duration.ofMillis(45000L)) .build(); definitions.put("default", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); @@ -224,7 +226,7 @@ private static Builder createDefault() { BatchingSettings.newBuilder() .setElementCountThreshold(800L) .setRequestByteThreshold(8388608L) - .setDelayThreshold(Duration.ofMillis(100)) + .setDelayThresholdDuration(java.time.Duration.ofMillis(100)) .build()); builder .fakeMethodBatching() @@ -337,7 +339,7 @@ public void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() { @Test public void callSettingsBuildFromTimeoutNoRetries() { - Duration timeout = Duration.ofMillis(60000); + java.time.Duration timeout = java.time.Duration.ofMillis(60000); UnaryCallSettings.Builder builderA = UnaryCallSettings.newUnaryCallSettingsBuilder(); @@ -350,17 +352,37 @@ public 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("UnaryCallSettings", settingsA, settingsB); } + + @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 ce5f04d786..d4c60d5c31 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 @@ -67,7 +67,6 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class TimeoutTest { @@ -78,9 +77,12 @@ public 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; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @@ -102,9 +104,9 @@ public void testNonRetryUnarySettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setInitialRpcTimeout(initialRpcTimeout) @@ -128,16 +130,16 @@ public void testNonRetryUnarySettingsContextWithRetry() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setInitialRpcTimeout(initialRpcTimeout) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(maxRpcTimeout) .build(); - Duration newTimeout = Duration.ofSeconds(5); + java.time.Duration newTimeout = java.time.Duration.ofSeconds(5); RetrySettings contextRetrySettings = retrySettings .toBuilder() @@ -168,9 +170,9 @@ public void testNonRetryUnarySettingsWithoutInitialRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) @@ -193,9 +195,9 @@ public void testNonRetryUnarySettingsWithoutIndividualRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) @@ -217,9 +219,9 @@ public void testNonRetryServerStreamingSettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setInitialRpcTimeout(initialRpcTimeout) @@ -243,16 +245,16 @@ public void testNonRetryServerStreamingSettingsContextWithRetry() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setInitialRpcTimeout(initialRpcTimeout) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(maxRpcTimeout) .build(); - Duration newTimeout = Duration.ofSeconds(5); + java.time.Duration newTimeout = java.time.Duration.ofSeconds(5); RetrySettings contextRetrySettings = retrySettings .toBuilder() @@ -283,9 +285,9 @@ public void testNonRetryServerStreamingSettingsWithoutInitialRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) @@ -308,9 +310,9 @@ public void testNonRetryServerStreamingSettingsWithoutIndividualRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) - .setInitialRetryDelay(Duration.ZERO) + .setInitialRetryDelay(java.time.Duration.ZERO) .setRetryDelayMultiplier(1.0) - .setMaxRetryDelay(Duration.ZERO) + .setMaxRetryDelay(java.time.Duration.ZERO) .setMaxAttempts(1) .setJittered(true) .setRpcTimeoutMultiplier(1.0) @@ -454,7 +456,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..a1a344ca4a 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,14 @@ */ 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.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 +59,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 +73,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 +117,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 +185,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 +254,16 @@ public HttpJsonCallContext withTransportChannel(TransportChannel inputChannel) { return withChannel(transportChannel.getChannel()); } + /** + * Overload of {@link #withTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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 +282,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 +307,37 @@ public HttpJsonCallContext withTimeout(Duration timeout) { this.endpointContext); } + /** Backport of {@link #getTimeoutDuration()} */ + @Nullable + @Override + @ObsoleteApi("Use getTimeoutDuration instead") + public org.threeten.bp.Duration getTimeout() { + return toThreetenDuration(getTimeoutDuration()); + } + @Nullable @Override - public Duration getTimeout() { + public java.time.Duration getTimeoutDuration() { return timeout; } + /** + * Overload of {@link #withStreamWaitTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ @Override - public HttpJsonCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeout) { + @ObsoleteApi("Use withStreamWaitTimeoutDuration(java.time.Duration) instead") + public HttpJsonCallContext withStreamWaitTimeout( + @Nullable org.threeten.bp.Duration streamWaitTimeout) { + return withStreamWaitTimeoutDuration(toJavaTimeDuration(streamWaitTimeout)); + } + + @Override + 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 +354,42 @@ public HttpJsonCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTi this.endpointContext); } + /** Backport of {@link #getStreamWaitTimeoutDuration()} */ + @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; } + /** + * Overload of {@link #withStreamIdleTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ @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 +406,22 @@ public HttpJsonCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTi this.endpointContext); } + /** Backport of {@link #getStreamIdleTimeoutDuration()} */ + @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; } @@ -446,12 +508,20 @@ public HttpJsonCallOptions getCallOptions() { return callOptions; } + /** Backport of {@link #getDeadlineInstant()} */ @Deprecated @Nullable - public Instant getDeadline() { + @ObsoleteApi("Use getDeadlineInstant() instead") + public org.threeten.bp.Instant getDeadline() { return getCallOptions() != null ? getCallOptions().getDeadline() : null; } + @Deprecated + @Nullable + public java.time.Instant getDeadlineInstant() { + return toJavaTimeInstant(getDeadline()); + } + @Deprecated @Nullable public Credentials getCredentials() { @@ -530,13 +600,20 @@ public HttpJsonCallContext withCallOptions(HttpJsonCallOptions newCallOptions) { this.endpointContext); } + /** Overload of {@link #withDeadline(java.time.Instant)} using {@link org.threeten.bp.Instant} */ @Deprecated - public HttpJsonCallContext withDeadline(Instant newDeadline) { + @ObsoleteApi("Use withDeadline(java.time.Instant) instead") + public HttpJsonCallContext withDeadline(org.threeten.bp.Instant newDeadline) { HttpJsonCallOptions.Builder builder = callOptions != null ? callOptions.toBuilder() : HttpJsonCallOptions.newBuilder(); return withCallOptions(builder.setDeadline(newDeadline).build()); } + @Deprecated + public HttpJsonCallContext withDeadline(java.time.Instant newDeadline) { + return withDeadline(toThreetenInstant(newDeadline)); + } + @Nonnull @Override public ApiTracer getTracer() { 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..4634a38c16 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,12 +29,16 @@ */ 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 @@ -42,10 +46,22 @@ public abstract class HttpJsonCallOptions { public static final HttpJsonCallOptions DEFAULT = newBuilder().build(); @Nullable - public abstract Duration getTimeout(); + @ObsoleteApi("Use getTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getTimeout(); + + @Nullable + public java.time.Duration getTimeoutDuration() { + return toJavaTimeDuration(getTimeout()); + } @Nullable - public abstract Instant getDeadline(); + @ObsoleteApi("Use getDeadlineInstant() instead") + public abstract org.threeten.bp.Instant getDeadline(); + + @Nullable + public final java.time.Instant getDeadlineInstant() { + return toJavaTimeInstant(getDeadline()); + } @Nullable public abstract Credentials getCredentials(); @@ -66,15 +82,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 +109,21 @@ public HttpJsonCallOptions merge(HttpJsonCallOptions inputOptions) { @AutoValue.Builder public abstract static class Builder { - public abstract Builder setTimeout(java.time.Duration value); + /** Backport of {@link #setTimeoutDuration(java.time.Duration)} */ + @ObsoleteApi("Use setTimeoutDuration(java.time.Duration) instead") + public abstract Builder setTimeout(org.threeten.bp.Duration value); + + public Builder setTimeoutDuration(java.time.Duration value) { + return setTimeout(toThreetenDuration(value)); + } - public abstract Builder setDeadline(Instant value); + /** Backport of {@link #setDeadlineInstant(java.time.Instant)} */ + @ObsoleteApi("Use setDeadlineInstant(java.time.Instant) instead") + public abstract Builder setDeadline(org.threeten.bp.Instant value); + + public final Builder setDeadlineInstant(java.time.Instant value) { + return setDeadline(toThreetenInstant(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..c573d786f6 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,7 +51,7 @@ 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 @@ -60,13 +59,14 @@ public static HttpJsonClientCall newC // This is temporary here as we plan to migrate to java.util.Duration if (callOptions.getTimeout() == null || httpJsonContext - .getTimeout() - .compareTo(Duration.ofMillis(callOptions.getTimeout().toMillis())) + .getTimeoutDuration() + .compareTo(java.time.Duration.ofMillis(callOptions.getTimeout().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..b47755b714 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 public void testWithNegativeTimeout() { assertNull( - HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(-1L)).getTimeout()); + HttpJsonCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(-1L)) + .getTimeoutDuration()); } @Test public void testWithZeroTimeout() { assertNull( - HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(0L)).getTimeout()); + HttpJsonCallContext.createDefault() + .withTimeoutDuration(java.time.Duration.ofSeconds(0L)) + .getTimeoutDuration()); } @Test public 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 public 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 public 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 public 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..a761045459 --- /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.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 0355dd0d4b..a99f566c63 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 @@ public class HttpJsonClientCallImplTest { public 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<>( @@ -94,7 +93,8 @@ public void responseReceived_cancellationTaskExists_isCancelledProperly() 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 463b76112b..c41fbc7201 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 @@ -54,7 +54,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class HttpJsonClientInterceptorTest { @@ -194,7 +193,7 @@ public void testCustomInterceptor() throws ExecutionException, InterruptedExcept 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 619052744a..3cdbb96aab 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 @@ -57,7 +57,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class HttpJsonDirectCallableTest { @@ -129,7 +128,7 @@ public static void initialize() throws IOException { defaultCallContext = HttpJsonCallContext.createDefault() .withChannel(channel) - .withTimeout(Duration.ofSeconds(30)) + .withTimeoutDuration(java.time.Duration.ofSeconds(30)) .withEndpointContext(endpointContext); } @@ -335,7 +334,8 @@ public 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 3fc1724439..de46afb5a1 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 @@ -68,7 +68,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class HttpJsonDirectServerStreamingCallableTest { @@ -91,10 +90,10 @@ public class HttpJsonDirectServerStreamingCallableTest { @Before public void initialize() throws IOException { - initialize(Duration.ofSeconds(30)); + initialize(java.time.Duration.ofSeconds(30)); } - public void initialize(Duration timeout) throws IOException { + public void initialize(java.time.Duration timeout) throws IOException { this.methodServerStreamingRecognize = ApiMethodDescriptor.newBuilder() .setFullMethodName("google.cloud.v1.Fake/ServerStreamingRecognize") @@ -150,7 +149,7 @@ public void initialize(Duration timeout) throws IOException { .setTransportChannel(HttpJsonTransportChannel.create(channel)) .setDefaultCallContext( HttpJsonCallContext.of(channel, HttpJsonCallOptions.DEFAULT) - .withTimeout(timeout) + .withTimeoutDuration(timeout) .withEndpointContext(endpointContext)) .build(); @@ -335,7 +334,7 @@ public void testBlockingServerStreaming() { @Test public 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 b6d4b0943f..f95eaf6e5f 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 @@ public 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 @@ public 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 f7b9935d31..c05a9c5d56 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 @@ -66,7 +66,6 @@ import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class RetryingTest { @@ -106,13 +105,13 @@ public class RetryingTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofMillis(2L)) + .setInitialRetryDelay(java.time.Duration.ofMillis(2L)) .setRetryDelayMultiplier(1) - .setMaxRetryDelay(Duration.ofMillis(2L)) - .setInitialRpcTimeout(Duration.ofMillis(2L)) + .setMaxRetryDelay(java.time.Duration.ofMillis(2L)) + .setInitialRpcTimeout(java.time.Duration.ofMillis(2L)) .setRpcTimeoutMultiplier(1) - .setMaxRpcTimeout(Duration.ofMillis(2L)) - .setTotalTimeout(Duration.ofMillis(10L)) + .setMaxRpcTimeout(java.time.Duration.ofMillis(2L)) + .setTotalTimeout(java.time.Duration.ofMillis(10L)) .build(); @Before @@ -176,8 +175,8 @@ public void retryTotalTimeoutExceeded() { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setInitialRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) - .setMaxRetryDelay(Duration.ofMillis(Integer.MAX_VALUE)) + .setInitialRetryDelay(java.time.Duration.ofMillis(Integer.MAX_VALUE)) + .setMaxRetryDelay(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 b08615ef13..69c789d80b 100644 --- a/gax-java/gax/clirr-ignored-differences.xml +++ b/gax-java/gax/clirr-ignored-differences.xml @@ -19,6 +19,57 @@ *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/*/* + * *(*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/* + * attemptFailed(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/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..0f69a17024 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,14 @@ */ 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 javax.annotation.Nullable; -import org.threeten.bp.Duration; /** * Represents the batching settings to use for an API method that is capable of batching. @@ -100,7 +103,14 @@ public abstract class BatchingSettings { /** Get the delay threshold to use for batching. */ @Nullable - public abstract Duration getDelayThreshold(); + @ObsoleteApi("Use getDelayThresholdDuration() instead") + public abstract org.threeten.bp.Duration getDelayThreshold(); + + /** Get the delay threshold to use for batching. */ + @Nullable + public final java.time.Duration getDelayThresholdDuration() { + return toJavaTimeDuration(getDelayThreshold()); + } /** Returns the Boolean object to indicate if the batching is enabled. Default to true */ public abstract Boolean getIsEnabled(); @@ -114,7 +124,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 +152,19 @@ public abstract static class Builder { */ public abstract Builder setRequestByteThreshold(Long requestByteThreshold); + /** Backport of {@link #setDelayThresholdDuration(java.time.Duration)} */ + @ObsoleteApi("Use setDelayThresholdDuration(java.time.Duration) instead") + public abstract Builder setDelayThreshold(org.threeten.bp.Duration 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 final Builder setDelayThresholdDuration(java.time.Duration delayThreshold) { + return setDelayThreshold(toThreetenDuration(delayThreshold)); + } /** * Set if the batch should be enabled. If set to false, the batch logic will be disabled and the @@ -171,8 +187,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..384cf52393 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,12 +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 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; @@ -45,7 +48,6 @@ 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; @@ -100,11 +102,21 @@ private ThresholdBatcher(Builder builder) { resetThresholds(); } + @VisibleForTesting + org.threeten.bp.Duration getMaxDelay() { + return toThreetenDuration(this.maxDelay); + } + + @VisibleForTesting + java.time.Duration getMaxDelayDuration() { + return this.maxDelay; + } + /** Builder for a ThresholdBatcher. */ 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 +130,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; } + /** Overload of {@link #setMaxDelayDuration(java.time.Duration} */ + @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; 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..ce3bcab9f4 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,10 @@ public abstract class RetrySettings implements Serializable { private static final long serialVersionUID = 8258475264439710899L; + /** Backport of {@link #getTotalTimeoutDuration()} */ + @ObsoleteApi("Use getTotalTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getTotalTimeout(); + /** * 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 +98,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 final java.time.Duration getTotalTimeoutDuration() { + return toJavaTimeDuration(getTotalTimeout()); + } + + /** Backport of {@link #getInitialRetryDelayDuration()} */ + @ObsoleteApi("Use getInitialRetryDelayDuration() instead") + public abstract org.threeten.bp.Duration getInitialRetryDelay(); /** * InitialRetryDelay controls the delay before the first retry/ poll. Subsequent retries and polls @@ -101,7 +114,9 @@ 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 final java.time.Duration getInitialRetryDelayDuration() { + return toJavaTimeDuration(getInitialRetryDelay()); + } /** * RetryDelayMultiplier controls the change in delay before the next retry or poll. The retry @@ -113,6 +128,10 @@ public abstract class RetrySettings implements Serializable { */ public abstract double getRetryDelayMultiplier(); + /** Backport of {@link #getMaxRetryDelayDuration()} */ + @ObsoleteApi("Use getMaxRetryDelayDuration()") + public abstract org.threeten.bp.Duration getMaxRetryDelay(); + /** * 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 +140,9 @@ 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 final java.time.Duration getMaxRetryDelayDuration() { + return toJavaTimeDuration(getMaxRetryDelay()); + } /** * MaxAttempts defines the maximum number of retry attempts to perform. If this value is set to 0, @@ -152,6 +173,10 @@ public abstract class RetrySettings implements Serializable { @VisibleForTesting public abstract boolean isJittered(); + /** Backport of {@link #getInitialRpcTimeoutDuration()} */ + @ObsoleteApi("Use getInitialRpcTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getInitialRpcTimeout(); + /** * 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 +190,9 @@ 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 final java.time.Duration getInitialRpcTimeoutDuration() { + return toJavaTimeDuration(getInitialRpcTimeout()); + } /** * RpcTimeoutMultiplier controls the change in RPC timeout. The timeout of the previous call is @@ -176,6 +203,10 @@ public abstract class RetrySettings implements Serializable { */ public abstract double getRpcTimeoutMultiplier(); + /** Backport of {@link #getMaxRpcTimeoutDuration()} */ + @ObsoleteApi("Use getMaxRpcTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getMaxRpcTimeout(); + /** * 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 +214,21 @@ 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 final java.time.Duration getMaxRpcTimeoutDuration() { + return toJavaTimeDuration(getMaxRpcTimeout()); + } 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,10 @@ public static Builder newBuilder() { @AutoValue.Builder public abstract static class Builder { + /** Backport of {@link #setTotalTimeoutDuration(java.time.Duration)} */ + @ObsoleteApi("Use setTotalTimeoutDuration(java.time.Duration) instead") + public abstract Builder setTotalTimeout(org.threeten.bp.Duration 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 +257,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 Builder setTotalTimeout(Duration totalTimeout); + public final Builder setTotalTimeoutDuration(java.time.Duration totalTimeout) { + return setTotalTimeout(toThreetenDuration(totalTimeout)); + } + + /** Backport of {@link #setInitialRetryDelayDuration(java.time.Duration)} */ + @ObsoleteApi("Use setInitialRetryDelayDuration(java.time.Duration) instead") + public abstract Builder setInitialRetryDelay(org.threeten.bp.Duration initialDelay); /** * InitialRetryDelay controls the delay before the first retry/ poll. Subsequent retries and @@ -230,7 +273,9 @@ 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 final Builder setInitialRetryDelayDuration(java.time.Duration initialDelay) { + return setInitialRetryDelay(toThreetenDuration(initialDelay)); + } /** * RetryDelayMultiplier controls the change in delay before the next retry or poll. The retry @@ -242,6 +287,10 @@ public abstract static class Builder { */ public abstract Builder setRetryDelayMultiplier(double multiplier); + /** Backport of {@link #setMaxRetryDelayDuration(java.time.Duration)} */ + @ObsoleteApi("Use setMaxRetryDelayDuration(java.time.Duration) instead") + public abstract Builder setMaxRetryDelay(org.threeten.bp.Duration 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 +299,9 @@ 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 final Builder setMaxRetryDelayDuration(java.time.Duration maxDelay) { + return setMaxRetryDelay(toThreetenDuration(maxDelay)); + } /** * MaxAttempts defines the maximum number of retry attempts to perform. If this value is set to @@ -281,6 +332,10 @@ public abstract static class Builder { @VisibleForTesting public abstract Builder setJittered(boolean jittered); + /** Backport of {@link #setInitialRpcTimeoutDuration(java.time.Duration)} */ + @ObsoleteApi("Use setInitialRpcTimeoutDuration(java.time.Duration) instead") + public abstract Builder setInitialRpcTimeout(org.threeten.bp.Duration 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 +349,9 @@ 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 final Builder setInitialRpcTimeoutDuration(java.time.Duration initialTimeout) { + return setInitialRpcTimeout(toThreetenDuration(initialTimeout)); + } /** * RpcTimeoutMultiplier controls the change in RPC timeout. The timeout of the previous call is @@ -305,6 +362,10 @@ public abstract static class Builder { */ public abstract Builder setRpcTimeoutMultiplier(double multiplier); + /** Backport of {@link #setMaxRpcTimeoutDuration(java.time.Duration)} */ + @ObsoleteApi("Use setMaxRpcTimeoutDuration(java.time.Duration) instead") + public abstract Builder setMaxRpcTimeout(org.threeten.bp.Duration 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 +373,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 final Builder setMaxRpcTimeoutDuration(java.time.Duration maxTimeout) { + return setMaxRpcTimeout(toThreetenDuration(maxTimeout)); + } + + /** Backport of {@link #getTotalTimeoutDuration()} */ + @ObsoleteApi("Use getTotalTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getTotalTimeout(); /** * TotalTimeout has ultimate control over how long the logic should keep trying the remote call @@ -327,7 +394,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 final java.time.Duration getTotalTimeoutDuration() { + return toJavaTimeDuration(getTotalTimeout()); + } + + /** Backport of {@link #getInitialRetryDelayDuration()} */ + @ObsoleteApi("Use getInitialRetryDelayDuration() instead") + public abstract org.threeten.bp.Duration getInitialRetryDelay(); /** * InitialRetryDelay controls the delay before the first retry/ poll. Subsequent retries and @@ -337,7 +410,9 @@ 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 final java.time.Duration getInitialRetryDelayDuration() { + return toJavaTimeDuration(getInitialRetryDelay()); + } /** * RetryDelayMultiplier controls the change in delay before the next retry or poll. The retry @@ -374,6 +449,10 @@ public abstract static class Builder { */ public abstract boolean isJittered(); + /** Backport of {@link #getMaxRetryDelayDuration()} */ + @ObsoleteApi("Use getMaxRetryDelayDuration() instead") + public abstract org.threeten.bp.Duration getMaxRetryDelay(); + /** * 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 +461,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 final java.time.Duration getMaxRetryDelayDuration() { + return toJavaTimeDuration(getMaxRetryDelay()); + } + + /** Backport of {@link #getInitialRpcTimeoutDuration()} */ + @ObsoleteApi("Use getInitialRpcTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getInitialRpcTimeout(); /** * InitialRpcTimeout controls the timeout for the initial RPC. Subsequent calls will use this @@ -397,7 +482,9 @@ 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 final java.time.Duration getInitialRpcTimeoutDuration() { + return toJavaTimeDuration(getInitialRpcTimeout()); + } /** * RpcTimeoutMultiplier controls the change in RPC timeout. The timeout of the previous call is @@ -408,6 +495,10 @@ public abstract static class Builder { */ public abstract double getRpcTimeoutMultiplier(); + /** Backport of {@link #getMaxRpcTimeoutDuration()} */ + @ObsoleteApi("Use getMaxRpcTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getMaxRpcTimeout(); + /** * 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 +506,19 @@ 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 final java.time.Duration getMaxRpcTimeoutDuration() { + return toJavaTimeDuration(getMaxRpcTimeout()); + } + + /** + * Overload of {@link #setLogicalTimeout(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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 +530,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 +569,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..ce4b69bdd2 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(); + /** Backport of {@link #getRetryDelayDuration()} */ + @ObsoleteApi("Use getRetryDelayDuration() instead") + public abstract org.threeten.bp.Duration getRetryDelay(); + /** * 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 final java.time.Duration getRetryDelayDuration() { + return toJavaTimeDuration(getRetryDelay()); + } + + /** Backport of {@link #getRpcTimeoutDuration()} */ + @ObsoleteApi("Use getRpcTimeoutDuration() instead") + public abstract org.threeten.bp.Duration getRpcTimeout(); /** Returns rpc timeout used for this attempt. */ - public abstract Duration getRpcTimeout(); + public final java.time.Duration getRpcTimeoutDuration() { + return toJavaTimeDuration(getRpcTimeout()); + } + + /** Backport of {@link #getRandomizedRetryDelayDuration()} */ + @ObsoleteApi("Use getRandomizedRetryDelayDuration() instead") + public abstract org.threeten.bp.Duration getRandomizedRetryDelay(); /** * 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 final java.time.Duration getRandomizedRetryDelayDuration() { + return toJavaTimeDuration(getRandomizedRetryDelay()); + } /** * The attempt count. It is a zero-based value (first attempt will have this value set to 0). For @@ -85,20 +106,47 @@ public abstract static class Builder { /** Sets global (attempt-independent) retry settings. */ public abstract Builder setGlobalSettings(RetrySettings value); + /** + * Backport of {@link #setRetryDelayDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @ObsoleteApi("Use setRetryDelayDuration(java.time.Duration) instead") + public abstract Builder setRetryDelay(org.threeten.bp.Duration 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 final Builder setRetryDelayDuration(java.time.Duration value) { + return setRetryDelay(toThreetenDuration(value)); + } + + /** + * Backport of {@link #setRpcTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @ObsoleteApi("Use setRpcTimeoutDuration(java.time.Duration) instead") + public abstract Builder setRpcTimeout(org.threeten.bp.Duration value); /** Sets rpc timeout used for this attempt. */ - public abstract Builder setRpcTimeout(Duration value); + public final Builder setRpcTimeoutDuration(java.time.Duration value) { + return setRpcTimeout(toThreetenDuration(value)); + } + + /** + * Backport of {@link #setRandomizedRetryDelayDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @ObsoleteApi("Use setRandomizedRetryDelayDuration(java.time.Duration) instead") + public abstract Builder setRandomizedRetryDelay(org.threeten.bp.Duration value); /** * 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 final Builder setRandomizedRetryDelayDuration(java.time.Duration value) { + return setRandomizedRetryDelay(toThreetenDuration(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..0b45b722bf 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,13 @@ public interface ApiCallContext extends RetryingContext { /** Returns a new ApiCallContext with the given Endpoint Context. */ ApiCallContext withEndpointContext(EndpointContext endpointContext); + /** + * Overload of {@link #withTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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 +85,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); + + /** Backport of {@link #getTimeoutDuration()} */ + @Nullable + @ObsoleteApi("Use getTimeoutDuration() instead") + org.threeten.bp.Duration getTimeout(); /** Returns the configured per-RPC timeout. */ @Nullable - Duration getTimeout(); + java.time.Duration getTimeoutDuration(); + + /** + * Overload of {@link #withStreamWaitTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration } + */ + @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 +114,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); + + /** Backport of {@link #getStreamWaitTimeoutDuration()} */ + @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(); + + /** + * Overload of {@link #withStreamIdleTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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 +149,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); + + /** Backport of {@link #getStreamIdleTimeoutDuration()} */ + @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 +228,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..450156e19f 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,19 @@ public abstract class ClientContext { @Nullable public abstract Watchdog getStreamWatchdog(); + /** + * Backport of {@link #getStreamWatchdogCheckIntervalDuration()} + * + * @return + */ + @Nonnull + @ObsoleteApi("Use getStreamWatchdogCheckIntervalDuration() instead") + public abstract org.threeten.bp.Duration getStreamWatchdogCheckInterval(); + @Nonnull - public abstract Duration getStreamWatchdogCheckInterval(); + public final java.time.Duration getStreamWatchdogCheckIntervalDuration() { + return toJavaTimeDuration(getStreamWatchdogCheckInterval()); + } @Nullable public abstract String getUniverseDomain(); @@ -133,7 +147,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 +252,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 +289,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 +360,13 @@ public abstract static class Builder { public abstract Builder setStreamWatchdog(Watchdog watchdog); - public abstract Builder setStreamWatchdogCheckInterval(Duration duration); + /** Backport of {@link #setStreamWatchdogCheckIntervalDuration(java.time.Duration)} */ + @ObsoleteApi("Use setStreamWatchdogCheckIntervalDuration(java.time.Duration) instead") + public abstract Builder setStreamWatchdogCheckInterval(org.threeten.bp.Duration duration); + + public final Builder setStreamWatchdogCheckIntervalDuration(java.time.Duration duration) { + return setStreamWatchdogCheckInterval(toThreetenDuration(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..04cbbc2dab 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,22 @@ public final WatchdogProvider getWatchdogProvider() { return stubSettings.getStreamWatchdogProvider(); } + /** + * Backport of {@link #getWatchdogCheckIntervalDuration()} + * + * @return + */ @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 +280,14 @@ public B setWatchdogProvider(@Nullable WatchdogProvider watchdogProvider) { return self(); } - public B setWatchdogCheckInterval(@Nullable Duration checkInterval) { - stubSettings.setStreamWatchdogCheckInterval(checkInterval); + /** Backport of {@link #setWatchdogCheckIntervalDuration(java.time.Duration)} */ + @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(); } @@ -347,10 +366,16 @@ public WatchdogProvider getWatchdogProvider() { } @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..a35940adfd 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,10 @@ import com.google.api.core.ApiClock; import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; 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 @@ -71,7 +71,13 @@ public boolean needsCheckInterval() { } @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..aca98b8ffb 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,15 @@ public boolean needsCheckInterval() { return checkInterval == null; } + /** Backport of {@link #withCheckIntervalDuration(java.time.Duration)} */ + @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)); } 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..a942af0b02 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; @@ -39,7 +43,6 @@ import com.google.common.collect.Sets; import java.util.Set; import javax.annotation.Nonnull; -import org.threeten.bp.Duration; /** * A settings class to configure a {@link ServerStreamingCallable}. @@ -51,7 +54,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 +70,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 +83,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 +121,35 @@ public StreamResumptionStrategy getResumptionStrategy() { return resumptionStrategy; } + /** Backport of {@link #getIdleTimeoutDuration()} */ + @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; } + /** Backport of {@link #getWaitTimeoutDuration()} */ + @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 +177,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 +187,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 +259,29 @@ public RetrySettings getRetrySettings() { return retrySettingsBuilder.build(); } + /** + * Overload of {@link #setSimpleTimeoutNoRetriesDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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 +304,66 @@ public StreamResumptionStrategy getResumptionStrategy() { return resumptionStrategy; } + /** Backport of {@link #getIdleTimeoutDuration()} */ @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; } + /** + * Overlad of {@link #setIdleTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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; } + /** Backport of {@link #getWaitTimeoutDuration()} */ + @Nonnull + @ObsoleteApi("Use getWaitTimeoutDuration() instead") + public org.threeten.bp.Duration getWaitTimeout() { + return toThreetenDuration(getWaitTimeoutDuration()); + } + @Nonnull - public Duration getWaitTimeout() { + public java.time.Duration getWaitTimeoutDuration() { return waitTimeout; } + /** + * Overload of {@link #setWaitTimeoutDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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..25241ba260 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; } + /** Backport of {@link #getStreamWatchdogCheckIntervalDuration()} */ @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(); } + /** + * Overload of {@link #setStreamWatchdogCheckIntervalDuration(java.time.Duration)} using {@link + * org.threeten.bp.Duration} + */ + @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,8 +640,13 @@ public String getQuotaProjectId() { return quotaProjectId; } + @ObsoleteApi("Use getStreamWatchdogCheckIntervalDuration() instead") + public org.threeten.bp.Duration getStreamWatchdogCheckInterval() { + return toThreetenDuration(getStreamWatchdogCheckIntervalDuration()); + } + @Nonnull - public Duration getStreamWatchdogCheckInterval() { + public java.time.Duration getStreamWatchdogCheckIntervalDuration() { return streamWatchdogCheckInterval; } 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..43fa461425 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,26 @@ public UnaryCallSettings.Builder setRetrySettings( return this; } - /** Disables retries and sets the RPC timeout. */ + /** Backport of {@link #setSimpleTimeoutNoRetriesDuration(java.time.Duration)} */ + @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..7cf458452e 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,20 @@ 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. */ public static Watchdog create( - ApiClock clock, Duration scheduleInterval, ScheduledExecutorService executor) { + 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 +100,22 @@ private void start() { this, scheduleInterval.toMillis(), scheduleInterval.toMillis(), TimeUnit.MILLISECONDS); } + /** + * Overload of {@link #watch(ResponseObserver, java.time.Duration, java.time.Duration)} using + * {@link org.threeten.bp.Duration} + */ + @ObsoleteApi("Use watch(ResponseObserver, java.time.Duration, java.time.Duration) instead") + public ResponseObserver watch( + ResponseObserver innerObserver, + @Nonnull org.threeten.bp.Duration waitTimeout, + @Nonnull org.threeten.bp.Duration idleTimeout) { + return watch(innerObserver, toJavaTimeDuration(waitTimeout), toJavaTimeDuration(idleTimeout)); + } /** Wraps the target observer with timing constraints. */ public ResponseObserver watch( ResponseObserver innerObserver, - @Nonnull Duration waitTimeout, - @Nonnull Duration idleTimeout) { + @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 +187,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 +211,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 +234,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..852e2992c2 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 @@ -30,10 +30,12 @@ package com.google.api.gax.rpc; import com.google.api.core.ApiClock; +import com.google.api.core.InternalApi; +import com.google.api.core.ObsoleteApi; import java.util.concurrent.ScheduledExecutorService; import javax.annotation.Nonnull; -import org.threeten.bp.Duration; +@InternalApi public interface WatchdogProvider { boolean needsClock(); @@ -41,7 +43,11 @@ public interface WatchdogProvider { boolean needsCheckInterval(); - WatchdogProvider withCheckInterval(Duration checkInterval); + /** Backport of {@link #withCheckIntervalDuration(java.time.Duration)} */ + @ObsoleteApi("Use withCheckIntervalDuration(java.time.Duration) instead") + WatchdogProvider withCheckInterval(org.threeten.bp.Duration checkInterval); + + WatchdogProvider withCheckIntervalDuration(java.time.Duration 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..c5b5d1a6cc 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,8 +61,10 @@ 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); 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..005d707b9d 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 @@ -29,8 +29,10 @@ */ package com.google.api.gax.tracing; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + 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 +110,19 @@ default Scope inScope() { /** Add an annotation that the attempt was cancelled by the user. */ default void attemptCancelled() {}; + /** Backport of {@link #attemptFailedDuration(Throwable, java.time.Duration)} */ + @ObsoleteApi("Use attemptFailedDuration(Throwable, java.time.Duration) instead") + default void attemptFailed(Throwable error, org.threeten.bp.Duration delay) { + attemptFailedDuration(error, toJavaTimeDuration(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..6867ccee83 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 @@ -29,8 +29,10 @@ */ package com.google.api.gax.tracing; +import static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration; + 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,10 +106,17 @@ public void attemptCancelled() { } @Override - public void attemptFailed(Throwable error, Duration delay) { + public void attemptFailedDuration(Throwable error, java.time.Duration delay) { // noop } + /** Backport of {@link #attemptFailedDuration(Throwable, java.time.Duration)} */ + @Override + @ObsoleteApi("Use attemptFailed(Throwable, java.time.Duration) instead") + public void attemptFailed(Throwable error, org.threeten.bp.Duration delay) { + attemptFailedDuration(error, toJavaTimeDuration(delay)); + } + @Override public void attemptFailedRetriesExhausted(Throwable error) { // 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 7938bde82b..090f1a594e 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. @@ -171,12 +173,19 @@ 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); } + /** Backport of {@link #attemptFailedDuration(Throwable, java.time.Duration)} */ + @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..ec1523d186 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,13 @@ public void attemptFailed(Throwable error, Duration delay) { lastConnectionId = null; } + /** Backport of {@link #attemptFailedDuration(Throwable, java.time.Duration)} */ + @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 d392a7393d..778610eee9 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(...));
      * }
    */ public 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 bc1949f871..5033162a35 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.Assert; @@ -45,7 +44,9 @@ public void testFailsWhenTimeoutExceeded() { AssertionError error = Assert.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 @@ public void testImmediateSuccessSucceedsRegardlessOfTimeout() throws Interrupted 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 @@ public 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 70340d77d6..1901dc77e2 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 @@ -80,7 +80,6 @@ import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BatcherImplTest { @@ -96,7 +95,7 @@ public class BatcherImplTest { BatchingSettings.newBuilder() .setElementCountThreshold(1000L) .setRequestByteThreshold(1000L) - .setDelayThreshold(Duration.ofSeconds(1000)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1000)) .build(); @After @@ -375,7 +374,7 @@ public void testWhenThresholdIsDisabled() throws Exception { BatchingSettings.newBuilder() .setElementCountThreshold(null) .setRequestByteThreshold(null) - .setDelayThreshold(null) + .setDelayThresholdDuration(null) .build(); underTest = createDefaultBatcherImpl(settings, null); Future result = underTest.add(2); @@ -387,7 +386,10 @@ public void testWhenThresholdIsDisabled() throws Exception { @Test public 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(); @@ -418,7 +420,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)) { @@ -462,7 +467,10 @@ public Void call() throws InterruptedException { public 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); @@ -1025,7 +1033,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 51339dfa15..d4d1bf6796 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 @@ -41,7 +41,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BatchingCallSettingsTest { @@ -50,7 +49,7 @@ public class BatchingCallSettingsTest { BatchingSettings.newBuilder() .setElementCountThreshold(10L) .setRequestByteThreshold(20L) - .setDelayThreshold(Duration.ofMillis(5)) + .setDelayThresholdDuration(java.time.Duration.ofMillis(5)) .setFlowControlSettings( FlowControlSettings.newBuilder() .setMaxOutstandingElementCount(100L) @@ -91,7 +90,7 @@ public 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..07c3bc5a8e --- /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.Test; + +public class BatchingSettingsTest { + + private 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 534ad3c137..85ce0665d0 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; @@ -608,7 +607,8 @@ public 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; @@ -652,7 +652,8 @@ public 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 45eaa84b7f..aa97650974 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 @@ -29,6 +29,7 @@ */ package com.google.api.gax.batching; +import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.truth.Truth.assertThat; import com.google.api.core.ApiFutures; @@ -36,13 +37,13 @@ import com.google.api.gax.batching.FlowController.LimitExceededBehavior; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.junit.Assert; import org.junit.Test; -import org.threeten.bp.Duration; public class ThresholdBatcherTest { @@ -123,6 +124,7 @@ private List getIntegers() { } private static class SimpleBatchMerger implements BatchMerger { + @Override public void merge(SimpleBatch batch, SimpleBatch newBatch) { batch.merge(newBatch); @@ -134,7 +136,7 @@ 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()); @@ -194,7 +196,9 @@ public 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)); @@ -220,7 +224,7 @@ public 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))) .setBatchMerger(new SimpleBatchMerger()) @@ -357,4 +361,18 @@ public void testBatchingFailedRPC() throws Exception { assertThat(trackedFlowController.getBytesReserved()) .isEqualTo(trackedFlowController.getBytesReleased()); } + + @Test + public void testMaxDelay() { + AccumulatingBatchReceiver receiver = + new AccumulatingBatchReceiver<>(ApiFutures.immediateFuture(null)); + final ThresholdBatcher.Builder builder = + createSimpleBatcherBuidler(receiver).setThresholds(Collections.emptyList()); + testDurationMethod( + 123l, + jt -> builder.setMaxDelayDuration(jt).build(), + tt -> builder.setMaxDelay(tt).build(), + o -> o.getMaxDelayDuration(), + o -> o.getMaxDelay()); + } } 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 2a914ee06f..82ea52250e 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 @@ -67,7 +67,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import org.threeten.bp.Duration; @RunWith(Parameterized.class) public abstract class AbstractRetryingExecutorTest { @@ -90,7 +89,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) { @@ -144,7 +143,8 @@ public void testSuccessWithFailures() 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); } @@ -189,7 +189,8 @@ public void testMaxRetriesExceeded() 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); } @@ -199,8 +200,8 @@ public void testTotalTimeoutExceeded() 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 = @@ -233,9 +234,9 @@ public void testCancelOuterFutureBeforeStart() { 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)); @@ -267,7 +268,8 @@ public void testCancelByRetryingAlgorithm() throws Exception { 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); @@ -287,7 +289,8 @@ public void testUnexpectedExceptionFromRetryAlgorithm() throws Exception { 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); @@ -298,8 +301,8 @@ public void testPollExceptionByPollAlgorithm() 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; 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 c95cda7ebf..970d841693 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 @@ -43,7 +43,6 @@ import org.junit.runners.JUnit4; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BasicRetryingFutureTest { @@ -96,7 +95,8 @@ public void testHandleAttemptDoesNotThrowNPEWhenLogLevelLowerThanFiner() throws future.handleAttempt(null, null); Mockito.verify(tracer) - .attemptFailed(ArgumentMatchers.any(), ArgumentMatchers.any()); + .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 ca39a429cd..d3be4ab5f6 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 @@ -39,7 +39,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class ExponentialRetryAlgorithmTest { @@ -47,26 +46,26 @@ public class ExponentialRetryAlgorithmTest { 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); @@ -78,10 +77,10 @@ public 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 @@ -91,10 +90,11 @@ public 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 @@ -104,35 +104,37 @@ public 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(); @@ -147,13 +149,13 @@ public 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 @@ -164,13 +166,13 @@ public 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 @@ -178,19 +180,20 @@ public 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 @@ -228,11 +231,11 @@ public 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 5360312bbc..a14f927c03 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 8bcdea4cc8..582de93439 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.Test; -import org.threeten.bp.Duration; public class RetrySettingsTest { + private static final RetrySettings.Builder DEFAULT_BUILDER = + RetrySettings.newBuilder() + .setMaxRpcTimeoutDuration(java.time.Duration.ofMillis(5000l)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(5000l)); @Test public 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 public 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 60ba301c62..0989f73005 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 @@ -51,7 +51,6 @@ import org.junit.After; import org.junit.Test; import org.mockito.Mockito; -import org.threeten.bp.Duration; // @RunWith(MockitoJUnitRunner.class) public class ScheduledRetryingExecutorTest extends AbstractRetryingExecutorTest { @@ -94,7 +93,7 @@ public void testSuccessWithFailuresPeekAttempt() throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(1000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) .setMaxAttempts(maxRetries) .build(); @@ -145,7 +144,7 @@ public void testSuccessWithFailuresGetAttempt() throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(1000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) .setMaxAttempts(maxRetries) .build(); @@ -199,7 +198,7 @@ public void testCancelGetAttempt() throws Exception { RetrySettings retrySettings = FAST_RETRY_SETTINGS .toBuilder() - .setTotalTimeout(Duration.ofMillis(1000L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) .setMaxAttempts(maxRetries) .build(); @@ -259,10 +258,10 @@ public 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 @@ -311,9 +310,9 @@ public 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..a8b0d80d1e --- /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.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 3b16b568d0..39250d507c 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 @@ -45,7 +45,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; -import org.threeten.bp.Duration; @RunWith(MockitoJUnitRunner.class) public class AttemptCallableTest { @@ -66,9 +65,9 @@ public 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()) @@ -88,28 +87,31 @@ public void testRpcTimeout() { 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); + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(timeout); // Make sure that subsequent attempts can extend the time out - Duration longerTimeout = Duration.ofSeconds(20); + 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); + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(longerTimeout); } @Test public 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 +119,6 @@ public 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 254ba2831c..3ea1ecf3ca 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 @@ -47,7 +47,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BatcherFactoryTest { @@ -67,7 +66,7 @@ public void tearDown() { public void testGetPushingBatcher() { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(2L) .setRequestByteThreshold(1000L) .build(); 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 baafb1044e..e21e729a00 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 @@ -40,7 +40,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BatchingCallSettingsTest { @@ -85,11 +84,11 @@ public 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) @@ -129,11 +128,11 @@ public 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 a0234a441a..8ac84bade4 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 @@ -47,7 +47,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BatchingCallableTest { @@ -68,7 +67,7 @@ public 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 2b4a075963..03170a64f6 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 @@ -54,7 +54,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class BatchingTest { @@ -82,7 +81,7 @@ public void teardown() { public void batching() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(2L) .build(); BatchingCallSettings> batchingCallSettings = @@ -102,7 +101,7 @@ public void batching() throws Exception { public void batchingWithFlowControl() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(4L) .setRequestByteThreshold(null) .setFlowControlSettings( @@ -180,7 +179,7 @@ public void batchingDisabled() throws Exception { public void batchingWithBlockingCallThreshold() throws Exception { BatchingSettings batchingSettings = BatchingSettings.newBuilder() - .setDelayThreshold(Duration.ofSeconds(1)) + .setDelayThresholdDuration(java.time.Duration.ofSeconds(1)) .setElementCountThreshold(2L) .build(); BatchingCallSettings> batchingCallSettings = @@ -209,7 +208,7 @@ public ApiFuture> futureCall(LabeledIntList request, ApiCallContex public 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 8d24a19c53..0bf780d483 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 @@ -48,7 +48,6 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; -import org.threeten.bp.Duration; public class CallableTest { @@ -62,9 +61,9 @@ public 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(); @@ -80,14 +79,16 @@ public class CallableTest { public 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!"; @@ -100,8 +101,8 @@ public 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()); } @@ -116,14 +117,14 @@ public 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); @@ -134,41 +135,41 @@ public 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 public 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 public 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); } } 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 bb36d863cd..2003aa6189 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 @@ -53,7 +53,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class CancellationTest { @@ -63,24 +62,24 @@ public 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 92554616bc..10f5618d6b 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 @@ -45,7 +45,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; -import org.threeten.bp.Duration; @RunWith(MockitoJUnitRunner.class) public class CheckingAttemptCallableTest { @@ -66,9 +65,9 @@ public 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()) @@ -88,18 +87,19 @@ public void testRpcTimeout() { 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); + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(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); + assertThat(capturedCallContext.getValue().getTimeoutDuration()).isEqualTo(longerTimeout); } } 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 2f82489528..1e28a6e32a 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.Assert.assertEquals; import static org.junit.Assert.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; @@ -68,7 +70,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class ClientContextTest { @@ -286,15 +287,15 @@ private void runTest( Watchdog watchdog = Watchdog.create( 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); @@ -321,7 +322,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")); @@ -363,13 +364,13 @@ public 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")); @@ -1066,4 +1067,16 @@ public 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 bbbda6f93a..96aa3e1931 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.Assert.fail; import com.google.api.core.ApiClock; @@ -54,11 +55,12 @@ 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.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class ClientSettingsTest { @@ -119,7 +121,8 @@ public 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(); @@ -137,7 +140,8 @@ public 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(); @@ -163,7 +167,7 @@ public 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); @@ -173,7 +177,7 @@ public 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 @@ -185,7 +189,8 @@ public 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(); @@ -212,9 +217,9 @@ public void testBuilderFromClientContext() throws Exception { Watchdog watchdog = Watchdog.create( 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() @@ -225,7 +230,7 @@ public void testBuilderFromClientContext() throws Exception { .setDefaultCallContext(callContext) .setHeaders(headers) .setStreamWatchdog(watchdog) - .setStreamWatchdogCheckInterval(watchdogCheckInterval) + .setStreamWatchdogCheckIntervalDuration(watchdogCheckInterval) .setQuotaProjectId(QUOTA_PROJECT_ID_FROM_CONTEXT) .build(); @@ -244,7 +249,7 @@ public 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); } @@ -259,7 +264,7 @@ public 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); @@ -269,7 +274,7 @@ public 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(); @@ -284,7 +289,8 @@ public 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); } @@ -546,4 +552,25 @@ public 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 9fb9659371..0d6070b056 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,6 +30,7 @@ package com.google.api.gax.rpc; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.api.core.ApiClock; import java.util.concurrent.ScheduledExecutorService; @@ -37,7 +38,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class FixedWatchdogProviderTest { @@ -52,7 +52,7 @@ public void testSameInstance() { Watchdog watchdog = Watchdog.create( Mockito.mock(ApiClock.class), - Duration.ZERO, + java.time.Duration.ZERO, Mockito.mock(ScheduledExecutorService.class)); WatchdogProvider provider = FixedWatchdogProvider.create(watchdog); @@ -64,7 +64,7 @@ public void testNoModifications() { Watchdog watchdog = Watchdog.create( Mockito.mock(ApiClock.class), - Duration.ZERO, + java.time.Duration.ZERO, Mockito.mock(ScheduledExecutorService.class)); WatchdogProvider provider = FixedWatchdogProvider.create(watchdog); @@ -75,7 +75,7 @@ public void testNoModifications() { Throwable actualError = null; try { - provider.withCheckInterval(Duration.ofSeconds(10)); + provider.withCheckIntervalDuration(java.time.Duration.ofSeconds(10)); } catch (Throwable t) { actualError = t; } @@ -97,4 +97,18 @@ public 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 0607dc7179..0da5098e28 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.MockitoJUnitRunner; -import org.threeten.bp.Duration; @RunWith(MockitoJUnitRunner.class) public 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 public void happyPath() { @@ -58,7 +58,7 @@ public 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 @@ public void happyPath() { @Test public void requiresExecutor() { WatchdogProvider provider = - InstantiatingWatchdogProvider.create().withCheckInterval(checkInterval).withClock(clock); + InstantiatingWatchdogProvider.create() + .withCheckIntervalDuration(checkInterval) + .withClock(clock); Throwable actualError = null; try { @@ -101,7 +103,7 @@ public void requiresClock() { WatchdogProvider provider = InstantiatingWatchdogProvider.create() .withExecutor(executor) - .withCheckInterval(checkInterval); + .withCheckIntervalDuration(checkInterval); Throwable actualError = null; try { @@ -111,4 +113,17 @@ public 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 5779f72f71..5e55e32242 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 @@ -73,36 +73,37 @@ import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public 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; @@ -484,10 +485,10 @@ public 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(); @@ -521,14 +522,17 @@ public 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); } @@ -558,11 +562,13 @@ public 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 @@ -587,7 +593,7 @@ public 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(); @@ -695,7 +701,10 @@ public 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(); @@ -1165,8 +1174,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 25c6b8064f..038ade9231 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 @@ -38,7 +38,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class PagedCallSettingsTest { @@ -75,11 +74,11 @@ public 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) @@ -108,11 +107,11 @@ public 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 b58bd2c2c4..d8c5b02796 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 @@ -55,7 +55,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class RetryingTest { @@ -69,24 +68,24 @@ public 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(); @Before @@ -152,8 +151,8 @@ public 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(); assertRetrying(retrySettings); @@ -170,8 +169,8 @@ public 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 acc70467bf..0036906ff2 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 @@ -53,7 +53,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class ServerStreamingAttemptCallableTest { @@ -61,8 +60,8 @@ public class ServerStreamingAttemptCallableTest { 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; @Before @@ -92,17 +91,19 @@ private ServerStreamingAttemptCallable createCallable(ApiCallCon public 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(); @@ -126,20 +127,20 @@ public void testUserProvidedContextTimeout() { public 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(); @@ -473,13 +474,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 bcd5a9272e..5469ea78f2 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; @@ -38,7 +39,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class ServerStreamingCallSettingsTest { @@ -66,11 +66,11 @@ public void retryableCodesVarArgs() { public 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) @@ -87,40 +87,40 @@ public void retryableSettingsAreNotLost() { @Test public 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 public 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 public 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) @@ -129,26 +129,49 @@ public 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 public 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 7400007231..c45704eac5 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 @@ -46,32 +46,31 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public 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 @@ -86,7 +85,8 @@ public 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 @@ -102,7 +102,8 @@ public 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 @@ -175,7 +176,7 @@ public 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 6838d57252..5d88246e8e 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.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -39,7 +40,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class UnaryCallSettingsTest { @@ -47,17 +47,18 @@ public class UnaryCallSettingsTest { @Test public 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 public 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); @@ -66,7 +67,7 @@ public 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); @@ -77,11 +78,11 @@ public void testEquals() { public 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) @@ -114,11 +115,11 @@ public void testEquals_retryableCodes() { public 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) @@ -127,11 +128,12 @@ public 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 @@ -146,4 +148,17 @@ public 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 d82fbeec49..86093789f6 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 @@ -50,16 +50,15 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public 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; 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/MetricsTestUtils.java b/gax-java/gax/src/test/java/com/google/api/gax/tracing/MetricsTestUtils.java new file mode 100644 index 0000000000..0e04196c21 --- /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.Assert.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 817c53656c..94c844adee 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.Assert.assertThrows; import static org.mockito.ArgumentMatchers.anyDouble; @@ -52,7 +53,6 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class MetricsTracerTest { @@ -137,7 +137,17 @@ public void testAttemptSucceeded_recordsAttributes() { } @Test - public void testAttemptFailed_recordsAttributes() { + public 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(); @@ -146,7 +156,7 @@ public 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 8cf6f82fa9..e3382adf4f 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; @@ -60,7 +61,6 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class OpencensusTracerTest { @@ -79,13 +79,22 @@ public void setUp() { } @Test - public void testUnarySuccessExample() { + public 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"); @@ -131,12 +140,21 @@ public void testBatchExample() { } @Test - public void testLongRunningExample() { + public 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(); @@ -255,12 +273,21 @@ public void testFailureExample() { } @Test - public void testResponseCount() { + public 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); @@ -283,12 +310,21 @@ public void testResponseCount() { } @Test - public void testRequestCount() { + public 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. @@ -312,9 +348,18 @@ public void testRequestCount() { } @Test - public void testAttemptNumber() { + public 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(); @@ -336,10 +381,11 @@ public void testAttemptNumber() { @Test public 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 834b357e4d..3e87d648ab 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 @@ -56,7 +56,6 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; -import org.threeten.bp.Duration; @RunWith(JUnit4.class) public class TracedCallableTest { @@ -103,7 +102,7 @@ public 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..b097fcbb71 --- /dev/null +++ b/gax-java/gax/src/test/java/com/google/api/gax/util/TimeConversionTestUtils.java @@ -0,0 +1,118 @@ +/* + * 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.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.function.Function; + +public class TimeConversionTestUtils { + + 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); + } + + 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); + } + + 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/java-core/google-cloud-core/clirr-ignored-differences.xml b/java-core/google-cloud-core/clirr-ignored-differences.xml index 0f7f80a7b4..e1bb7bcc78 100644 --- a/java-core/google-cloud-core/clirr-ignored-differences.xml +++ b/java-core/google-cloud-core/clirr-ignored-differences.xml @@ -12,4 +12,10 @@ com/google/cloud/ReadChannel long limit() + + 7005 + com/google/cloud/testing/* + * *(org.threeten.bp.Duration) + * + diff --git a/java-core/google-cloud-core/src/main/java/com/google/cloud/RetryOption.java b/java-core/google-cloud-core/src/main/java/com/google/cloud/RetryOption.java index a1069b48a2..51e87be750 100644 --- a/java-core/google-cloud-core/src/main/java/com/google/cloud/RetryOption.java +++ b/java-core/google-cloud-core/src/main/java/com/google/cloud/RetryOption.java @@ -16,12 +16,13 @@ package com.google.cloud; +import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration; import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.core.BetaApi; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.retrying.RetrySettings; import java.io.Serializable; -import org.threeten.bp.Duration; /** * This class represents an options wrapper around the {@link RetrySettings} class and is an @@ -52,25 +53,43 @@ private RetryOption(OptionType type, Object value) { } /** See {@link RetrySettings#getTotalTimeout()}. */ - public static RetryOption totalTimeout(Duration totalTimeout) { + @ObsoleteApi("Use totalTimeout(java.time.Duration) instead") + public static RetryOption totalTimeout(org.threeten.bp.Duration totalTimeout) { return new RetryOption(OptionType.TOTAL_TIMEOUT, totalTimeout); } + /** See {@link RetrySettings#getTotalTimeout()}. */ + public static RetryOption totalTimeout(java.time.Duration totalTimeout) { + return totalTimeout(toThreetenDuration(totalTimeout)); + } + /** See {@link RetrySettings#getInitialRetryDelay()}. */ - public static RetryOption initialRetryDelay(Duration initialRetryDelay) { + @ObsoleteApi("Use initialRetryDelay(java.time.Duration) instead") + public static RetryOption initialRetryDelay(org.threeten.bp.Duration initialRetryDelay) { return new RetryOption(OptionType.INITIAL_RETRY_DELAY, initialRetryDelay); } + /** See {@link RetrySettings#getInitialRetryDelay()}. */ + public static RetryOption initialRetryDelay(java.time.Duration initialRetryDelay) { + return initialRetryDelay(toThreetenDuration(initialRetryDelay)); + } + /** See {@link RetrySettings#getRetryDelayMultiplier()}. */ public static RetryOption retryDelayMultiplier(double retryDelayMultiplier) { return new RetryOption(OptionType.RETRY_DELAY_MULTIPLIER, retryDelayMultiplier); } /** See {@link RetrySettings#getMaxRetryDelay()}. */ - public static RetryOption maxRetryDelay(Duration maxRetryDelay) { + @ObsoleteApi("Use maxRetryDelay(java.time.Duration) instead") + public static RetryOption maxRetryDelay(org.threeten.bp.Duration maxRetryDelay) { return new RetryOption(OptionType.MAX_RETRY_DELAY, maxRetryDelay); } + /** See {@link RetrySettings#getMaxRetryDelay()}. */ + public static RetryOption maxRetryDelay(java.time.Duration maxRetryDelay) { + return maxRetryDelay(toThreetenDuration(maxRetryDelay)); + } + /** See {@link RetrySettings#getMaxAttempts()}. */ public static RetryOption maxAttempts(int maxAttempts) { return new RetryOption(OptionType.MAX_ATTEMPTS, maxAttempts); @@ -124,16 +143,16 @@ public static RetrySettings mergeToSettings(RetrySettings settings, RetryOption. for (RetryOption option : options) { switch (option.type) { case TOTAL_TIMEOUT: - builder.setTotalTimeout((Duration) option.value); + builder.setTotalTimeout((org.threeten.bp.Duration) option.value); break; case INITIAL_RETRY_DELAY: - builder.setInitialRetryDelay((Duration) option.value); + builder.setInitialRetryDelay((org.threeten.bp.Duration) option.value); break; case RETRY_DELAY_MULTIPLIER: builder.setRetryDelayMultiplier((Double) option.value); break; case MAX_RETRY_DELAY: - builder.setMaxRetryDelay((Duration) option.value); + builder.setMaxRetryDelay((org.threeten.bp.Duration) option.value); break; case MAX_ATTEMPTS: builder.setMaxAttempts((Integer) option.value); diff --git a/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index 985fac4804..5c9a16f0d4 100644 --- a/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -70,7 +70,6 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.threeten.bp.Duration; /** * Abstract class representing service options. @@ -787,13 +786,13 @@ public static RetrySettings getNoRetrySettings() { private static RetrySettings.Builder getDefaultRetrySettingsBuilder() { return RetrySettings.newBuilder() .setMaxAttempts(6) - .setInitialRetryDelay(Duration.ofMillis(1000L)) - .setMaxRetryDelay(Duration.ofMillis(32_000L)) + .setInitialRetryDelay(org.threeten.bp.Duration.ofMillis(1000L)) + .setMaxRetryDelay(org.threeten.bp.Duration.ofMillis(32_000L)) .setRetryDelayMultiplier(2.0) - .setTotalTimeout(Duration.ofMillis(50_000L)) - .setInitialRpcTimeout(Duration.ofMillis(50_000L)) + .setTotalTimeout(org.threeten.bp.Duration.ofMillis(50_000L)) + .setInitialRpcTimeout(org.threeten.bp.Duration.ofMillis(50_000L)) .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(Duration.ofMillis(50_000L)); + .setMaxRpcTimeout(org.threeten.bp.Duration.ofMillis(50_000L)); } protected abstract Set getScopes(); diff --git a/java-core/google-cloud-core/src/main/java/com/google/cloud/testing/BaseEmulatorHelper.java b/java-core/google-cloud-core/src/main/java/com/google/cloud/testing/BaseEmulatorHelper.java index 9679c6299c..a6bd70d5f3 100644 --- a/java-core/google-cloud-core/src/main/java/com/google/cloud/testing/BaseEmulatorHelper.java +++ b/java-core/google-cloud-core/src/main/java/com/google/cloud/testing/BaseEmulatorHelper.java @@ -56,7 +56,6 @@ import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import org.threeten.bp.Duration; /** Utility class to start and stop a local service which is used by unit testing. */ @InternalApi @@ -116,7 +115,7 @@ protected final void startProcess(String blockUntilOutput) * Waits for the local service's subprocess to terminate, and stop any possible thread listening * for its output. */ - protected final int waitForProcess(Duration timeout) + protected final int waitForProcess(java.time.Duration timeout) throws IOException, InterruptedException, TimeoutException { if (activeRunner != null) { int exitCode = activeRunner.waitFor(timeout); @@ -130,7 +129,7 @@ protected final int waitForProcess(Duration timeout) return 0; } - private static int waitForProcess(final Process process, Duration timeout) + private static int waitForProcess(final Process process, java.time.Duration timeout) throws InterruptedException, TimeoutException { if (process == null) { return 0; @@ -181,7 +180,7 @@ public String getProjectId() { public abstract void start() throws IOException, InterruptedException; /** Stops the local emulator. */ - public abstract void stop(Duration timeout) + public abstract void stop(java.time.Duration timeout) throws IOException, InterruptedException, TimeoutException; /** Resets the internal state of the emulator. */ @@ -227,7 +226,7 @@ protected interface EmulatorRunner { void start() throws IOException; /** Wait for the emulator associated to this runner to terminate, returning the exit status. */ - int waitFor(Duration timeout) throws InterruptedException, TimeoutException; + int waitFor(java.time.Duration timeout) throws InterruptedException, TimeoutException; /** Returns the process associated to the emulator, if any. */ Process getProcess(); @@ -265,7 +264,7 @@ public void start() throws IOException { } @Override - public int waitFor(Duration timeout) throws InterruptedException, TimeoutException { + public int waitFor(java.time.Duration timeout) throws InterruptedException, TimeoutException { return waitForProcess(process, timeout); } @@ -375,7 +374,7 @@ public Path call() throws IOException { } @Override - public int waitFor(Duration timeout) throws InterruptedException, TimeoutException { + public int waitFor(java.time.Duration timeout) throws InterruptedException, TimeoutException { return waitForProcess(process, timeout); } diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java index ebea89f2fc..aa2cc3e6b8 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java @@ -21,26 +21,25 @@ import com.google.api.gax.retrying.RetrySettings; import org.junit.Test; -import org.threeten.bp.Duration; public class RetryOptionTest { private static final RetryOption TOTAL_TIMEOUT = - RetryOption.totalTimeout(Duration.ofMillis(420L)); + RetryOption.totalTimeout(java.time.Duration.ofMillis(420L)); private static final RetryOption INITIAL_RETRY_DELAY = - RetryOption.initialRetryDelay(Duration.ofMillis(42L)); + RetryOption.initialRetryDelay(java.time.Duration.ofMillis(42L)); private static final RetryOption RETRY_DELAY_MULTIPLIER = RetryOption.retryDelayMultiplier(1.5); private static final RetryOption MAX_RETRY_DELAY = - RetryOption.maxRetryDelay(Duration.ofMillis(100)); + RetryOption.maxRetryDelay(java.time.Duration.ofMillis(100)); private static final RetryOption MAX_ATTEMPTS = RetryOption.maxAttempts(100); private static final RetryOption JITTERED = RetryOption.jittered(false); private static final RetrySettings retrySettings = RetrySettings.newBuilder() - .setTotalTimeout(Duration.ofMillis(420L)) - .setInitialRetryDelay(Duration.ofMillis(42L)) + .setTotalTimeout(java.time.Duration.ofMillis(420L)) + .setInitialRetryDelay(java.time.Duration.ofMillis(42L)) .setRetryDelayMultiplier(1.5) - .setMaxRetryDelay(Duration.ofMillis(100)) + .setMaxRetryDelay(java.time.Duration.ofMillis(100)) .setMaxAttempts(100) .setJittered(false) .build(); @@ -61,10 +60,10 @@ public void testEqualsAndHashCode() { assertNotEquals(MAX_ATTEMPTS, MAX_RETRY_DELAY); assertNotEquals(JITTERED, MAX_ATTEMPTS); - RetryOption totalTimeout = RetryOption.totalTimeout(Duration.ofMillis(420L)); - RetryOption initialRetryDelay = RetryOption.initialRetryDelay(Duration.ofMillis(42L)); + RetryOption totalTimeout = RetryOption.totalTimeout(java.time.Duration.ofMillis(420L)); + RetryOption initialRetryDelay = RetryOption.initialRetryDelay(java.time.Duration.ofMillis(42L)); RetryOption retryDelayMultiplier = RetryOption.retryDelayMultiplier(1.5); - RetryOption maxRetryDelay = RetryOption.maxRetryDelay(Duration.ofMillis(100)); + RetryOption maxRetryDelay = RetryOption.maxRetryDelay(java.time.Duration.ofMillis(100)); RetryOption maxAttempts = RetryOption.maxAttempts(100); RetryOption jittered = RetryOption.jittered(false); @@ -101,17 +100,17 @@ public void testMergeToSettings() { assertEquals(retrySettings, mergedRetrySettings); defRetrySettings = - defRetrySettings.toBuilder().setTotalTimeout(Duration.ofMillis(420L)).build(); + defRetrySettings.toBuilder().setTotalTimeout(java.time.Duration.ofMillis(420L)).build(); mergedRetrySettings = RetryOption.mergeToSettings(defRetrySettings, TOTAL_TIMEOUT); assertEquals(defRetrySettings, mergedRetrySettings); defRetrySettings = - defRetrySettings.toBuilder().setMaxRetryDelay(Duration.ofMillis(100)).build(); + defRetrySettings.toBuilder().setMaxRetryDelay(java.time.Duration.ofMillis(100)).build(); mergedRetrySettings = RetryOption.mergeToSettings(defRetrySettings, MAX_RETRY_DELAY); assertEquals(defRetrySettings, mergedRetrySettings); defRetrySettings = - defRetrySettings.toBuilder().setInitialRetryDelay(Duration.ofMillis(42L)).build(); + defRetrySettings.toBuilder().setInitialRetryDelay(java.time.Duration.ofMillis(42L)).build(); mergedRetrySettings = RetryOption.mergeToSettings(defRetrySettings, INITIAL_RETRY_DELAY); assertEquals(defRetrySettings, mergedRetrySettings); diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java index 6c35c665b5..996efecca1 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java @@ -23,7 +23,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.Serializable; -import org.threeten.bp.Duration; public class SerializationTest extends BaseSerializationTest { @@ -37,7 +36,7 @@ public class SerializationTest extends BaseSerializationTest { private static final Role SOME_ROLE = Role.viewer(); private static final Policy SOME_IAM_POLICY = Policy.newBuilder().build(); private static final RetryOption CHECKING_PERIOD = - RetryOption.initialRetryDelay(Duration.ofSeconds(42)); + RetryOption.initialRetryDelay(java.time.Duration.ofSeconds(42)); private static final LabelDescriptor LABEL_DESCRIPTOR = new LabelDescriptor("project_id", ValueType.STRING, "The project id"); private static final MonitoredResourceDescriptor MONITORED_RESOURCE_DESCRIPTOR = diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java index 2c6d7495be..db3f17dc36 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java @@ -33,7 +33,6 @@ import java.util.logging.Logger; import org.easymock.EasyMock; import org.junit.Test; -import org.threeten.bp.Duration; public class BaseEmulatorHelperTest { @@ -71,7 +70,8 @@ public void start() throws IOException, InterruptedException { } @Override - public void stop(Duration timeout) throws IOException, InterruptedException, TimeoutException { + public void stop(java.time.Duration timeout) + throws IOException, InterruptedException, TimeoutException { waitForProcess(timeout); } @@ -91,13 +91,13 @@ public void testEmulatorHelper() throws IOException, InterruptedException, Timeo emulatorRunner.start(); EasyMock.expectLastCall(); EasyMock.expect(emulatorRunner.getProcess()).andReturn(process); - emulatorRunner.waitFor(Duration.ofMinutes(1)); + emulatorRunner.waitFor(java.time.Duration.ofMinutes(1)); EasyMock.expectLastCall().andReturn(0); EasyMock.replay(process, emulatorRunner); TestEmulatorHelper helper = new TestEmulatorHelper(ImmutableList.of(emulatorRunner), BLOCK_UNTIL); helper.start(); - helper.stop(Duration.ofMinutes(1)); + helper.stop(java.time.Duration.ofMinutes(1)); EasyMock.verify(); } @@ -157,13 +157,13 @@ public void testEmulatorHelperMultipleRunners() secondRunner.start(); EasyMock.expectLastCall(); EasyMock.expect(secondRunner.getProcess()).andReturn(process); - secondRunner.waitFor(Duration.ofMinutes(1)); + secondRunner.waitFor(java.time.Duration.ofMinutes(1)); EasyMock.expectLastCall().andReturn(0); EasyMock.replay(process, secondRunner); TestEmulatorHelper helper = new TestEmulatorHelper(ImmutableList.of(firstRunner, secondRunner), BLOCK_UNTIL); helper.start(); - helper.stop(Duration.ofMinutes(1)); + helper.stop(java.time.Duration.ofMinutes(1)); EasyMock.verify(); } diff --git a/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITDynamicRoutingHeaders.java b/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITDynamicRoutingHeaders.java index 326de3c61f..bafe8730d0 100644 --- a/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITDynamicRoutingHeaders.java +++ b/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITDynamicRoutingHeaders.java @@ -43,6 +43,7 @@ import io.grpc.MethodDescriptor; import java.util.Arrays; import java.util.List; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; @@ -153,11 +154,21 @@ public void createClients() throws Exception { } @After - public void destroyClient() { + public void destroyClient() throws InterruptedException { grpcClient.close(); - httpJsonClient.close(); grpcComplianceClient.close(); + + httpJsonClient.close(); httpJsonComplianceClient.close(); + + grpcClient.awaitTermination(TestClientInitializer.AWAIT_TERMINATION_SECONDS, TimeUnit.SECONDS); + grpcComplianceClient.awaitTermination( + TestClientInitializer.AWAIT_TERMINATION_SECONDS, TimeUnit.SECONDS); + + httpJsonClient.awaitTermination( + TestClientInitializer.AWAIT_TERMINATION_SECONDS, TimeUnit.SECONDS); + httpJsonComplianceClient.awaitTermination( + TestClientInitializer.AWAIT_TERMINATION_SECONDS, TimeUnit.SECONDS); } @Test 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..050f167044 --- /dev/null +++ b/showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/it/ITTimeObjectsPropagationTest.java @@ -0,0 +1,53 @@ +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() + .setInitialRetryDelay(javaTimeCommonValue) + .setMaxRetryDelay(javaTimeCommonValue) + .setInitialRpcTimeout(javaTimeCommonValue) + .setMaxRpcTimeout(javaTimeCommonValue) + .setTotalTimeout(javaTimeCommonValue) + .build(); + + assertEquals(threetenConvertedValue, javaTimeRetrySettings.getInitialRetryDelay()); + assertEquals(threetenConvertedValue, javaTimeRetrySettings.getMaxRetryDelay()); + assertEquals(threetenConvertedValue, javaTimeRetrySettings.getInitialRpcTimeout()); + assertEquals(threetenConvertedValue, javaTimeRetrySettings.getMaxRpcTimeout()); + assertEquals(threetenConvertedValue, javaTimeRetrySettings.getTotalTimeout()); + } + + @Test + public void testRetrySettings_fromThreetenHasEquivalentJavaTimeValues() { + java.time.Duration threetenCommonValue = java.time.Duration.ofMillis(123l); + org.threeten.bp.Duration javaTimeConvertedValue = + org.threeten.bp.Duration.ofMillis(threetenCommonValue.toMillis()); + RetrySettings threetenRetrySettings = RetrySettings.newBuilder() + .setInitialRetryDelay(threetenCommonValue) + .setMaxRetryDelay(threetenCommonValue) + .setInitialRpcTimeout(threetenCommonValue) + .setMaxRpcTimeout(threetenCommonValue) + .setTotalTimeout(threetenCommonValue) + .build(); + + assertEquals(javaTimeConvertedValue, threetenRetrySettings.getInitialRetryDelay()); + assertEquals(javaTimeConvertedValue, threetenRetrySettings.getMaxRetryDelay()); + assertEquals(javaTimeConvertedValue, threetenRetrySettings.getInitialRpcTimeout()); + assertEquals(javaTimeConvertedValue, threetenRetrySettings.getMaxRpcTimeout()); + assertEquals(javaTimeConvertedValue, threetenRetrySettings.getTotalTimeout()); + } + +}