aboutsummaryrefslogtreecommitdiffstats
path: root/http-utils/src/main/java/ai/vespa/util/http/hc4/retry/DelaySupplier.java
blob: edf7a4d20935094dededd67200158214b2aa4765 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.util.http.hc4.retry;

import java.time.Duration;

/**
 * An abstraction that calculates the next delay based on the current retry count.
 *
 * @author bjorncs
 */
@FunctionalInterface
interface DelaySupplier {
    Duration getDelay(int executionCount);

    class Fixed implements DelaySupplier {
        private final Duration delay;

        Fixed(Duration delay) {
            this.delay = delay;
        }

        @Override
        public Duration getDelay(int executionCount) { return delay; }
    }

    class Exponential implements DelaySupplier {
        private final Duration startDelay;
        private final Duration maxDelay;

        Exponential(Duration startDelay, Duration maxDelay) {
            this.startDelay = startDelay;
            this.maxDelay = maxDelay;
        }

        @Override
        public Duration getDelay(int executionCount) {
            Duration nextDelay = startDelay;
            for (int i = 1; i < executionCount; ++i) {
                nextDelay = nextDelay.multipliedBy(2);
            }
            return maxDelay.compareTo(nextDelay) > 0 ? nextDelay : maxDelay;
        }
    }
}