1 /*
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */

15
16 package software.amazon.awssdk.core.internal.retry;
17
18 import java.time.Duration;
19 import java.time.Instant;
20 import software.amazon.awssdk.annotations.SdkInternalApi;
21 import software.amazon.awssdk.annotations.ThreadSafe;
22 import software.amazon.awssdk.core.exception.SdkException;
23 import software.amazon.awssdk.core.internal.http.HttpClientDependencies;
24 import software.amazon.awssdk.core.retry.ClockSkew;
25 import software.amazon.awssdk.core.retry.RetryUtils;
26 import software.amazon.awssdk.http.SdkHttpResponse;
27 import software.amazon.awssdk.utils.Logger;
28
29 /**
30  * Suggests a clock skew adjustment that should be applied to future requests.
31  */

32 @ThreadSafe
33 @SdkInternalApi
34 public final class ClockSkewAdjuster {
35     private static final Logger log = Logger.loggerFor(ClockSkewAdjuster.class);
36
37     /**
38      * Returns true if the clock should be adjusted for future requests.
39      */

40     public boolean shouldAdjust(SdkException exception) {
41         return RetryUtils.isClockSkewException(exception);
42     }
43
44     /**
45      * Returns the recommended clock adjustment that should be used for future requests (in seconds). The result has the same
46      * semantics of {@link HttpClientDependencies#timeOffset()}. Positive values imply the client clock is "fast" and negative
47      * values imply the client clock is "slow".
48      */

49     public Integer getAdjustmentInSeconds(SdkHttpResponse response) {
50         Instant now = Instant.now();
51         Instant serverTime = ClockSkew.getServerTime(response).orElse(null);
52         Duration skew = ClockSkew.getClockSkew(now, serverTime);
53         try {
54             return Math.toIntExact(skew.getSeconds());
55         } catch (ArithmeticException e) {
56             log.warn(() -> "The clock skew between the client and server was too large to be compensated for (" + now +
57                            " versus " + serverTime + ").");
58             return 0;
59         }
60     }
61 }