001/*
002 * Copyright 2015-2022 Transmogrify LLC, 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.pyranid;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.ThreadSafe;
023import java.time.Duration;
024import java.util.Optional;
025
026import static java.lang.String.format;
027import static java.util.Objects.requireNonNull;
028
029/**
030 * Defines when and how {@link Database#transactionWithRetry(RetryPolicy, TransactionalOperation)} retries a transaction.
031 * <p>
032 * A retry policy requires all retry-critical decisions to be explicit: total attempts, retry condition, and backoff.
033 *
034 * @author <a href="https://www.revetkn.com">Mark Allen</a>
035 * @since 4.4.0
036 */
037@ThreadSafe
038public final class RetryPolicy {
039        @NonNull
040        private final Integer maxAttempts;
041        @NonNull
042        private final Condition condition;
043        @NonNull
044        private final Backoff backoff;
045        @Nullable
046        private final Duration maxElapsedTime;
047
048        private RetryPolicy(@NonNull Integer maxAttempts,
049                                                                                        @NonNull Condition condition,
050                                                                                        @NonNull Backoff backoff, @Nullable Duration maxElapsedTime) {
051                this.maxAttempts = maxAttempts;
052                this.condition = condition;
053                this.backoff = backoff;
054                this.maxElapsedTime = maxElapsedTime;
055        }
056
057        /**
058         * Creates a retry policy.
059         * <p>
060         * {@code maxAttempts} is the total number of attempts, including the initial attempt. For example, {@code 3} means one
061         * initial attempt plus up to two retries.
062         *
063         * @param maxAttempts total attempts, including the initial attempt
064         * @param backoff     determines how long to wait before the next retry
065         * @param condition   determines whether a failed attempt is retryable
066         * @return a retry policy
067         */
068        @NonNull
069        public static RetryPolicy ofMaxAttempts(@NonNull Integer maxAttempts,
070                        @NonNull Backoff backoff,
071                        @NonNull Condition condition) {
072                requireNonNull(maxAttempts);
073                requireNonNull(backoff);
074                requireNonNull(condition);
075
076                if (maxAttempts < 1)
077                        throw new IllegalArgumentException("maxAttempts must be at least 1");
078
079                return new RetryPolicy(maxAttempts, condition, backoff, null);
080        }
081
082        /**
083         * Gets the total number of attempts, including the initial attempt.
084         *
085         * @return total attempts
086         */
087        @NonNull
088        public Integer getMaxAttempts() {
089                return this.maxAttempts;
090        }
091
092        /**
093         * Gets the retry condition.
094         *
095         * @return retry condition
096         */
097        @NonNull
098        public Condition getCondition() {
099                return this.condition;
100        }
101
102        /**
103         * Gets the retry backoff.
104         *
105         * @return retry backoff
106         */
107        @NonNull
108        public Backoff getBackoff() {
109                return this.backoff;
110        }
111
112        /**
113         * Copies this policy with a positive elapsed retry budget measured from the start of the first attempt.
114         * <p>
115         * Work, cleanup, completion observation, policy evaluation, and backoff all consume the budget. The initial attempt
116         * always runs. No later attempt starts once the budget is exhausted, and a delay that would exhaust the remaining
117         * budget is not slept. Exhaustion propagates the final original database failure, retaining earlier failures as
118         * suppressed exceptions. This is retry admission control, not a timeout: an in-flight attempt can succeed after the
119         * budget expires and is never cancelled by this setting.
120         *
121         * @param limit strictly positive elapsed limit
122         * @return a new policy with the elapsed limit
123         * @since 4.8.0
124         */
125        @NonNull
126        public RetryPolicy withMaxElapsedTime(@NonNull Duration limit) {
127                requireNonNull(limit);
128                if (limit.isZero() || limit.isNegative())
129                        throw new IllegalArgumentException("maxElapsedTime must be positive");
130                return new RetryPolicy(this.maxAttempts, this.condition, this.backoff, limit);
131        }
132
133        /**
134         * Copies this policy without an elapsed retry budget.
135         *
136         * @return a new policy without an elapsed limit
137         * @since 4.8.0
138         */
139        @NonNull
140        public RetryPolicy withoutMaxElapsedTime() {
141                return new RetryPolicy(this.maxAttempts, this.condition, this.backoff, null);
142        }
143
144        /**
145         * Gets the elapsed retry budget, if any.
146         *
147         * @return elapsed limit
148         * @since 4.8.0
149         */
150        @NonNull
151        public Optional<Duration> getMaxElapsedTime() {
152                return Optional.ofNullable(this.maxElapsedTime);
153        }
154
155        @Override
156        @NonNull
157        public String toString() {
158                return format("%s{maxAttempts=%s, condition=%s, backoff=%s%s}",
159                                getClass().getSimpleName(), getMaxAttempts(), getCondition(), getBackoff(),
160                                this.maxElapsedTime == null ? "" : ", maxElapsedTime=" + this.maxElapsedTime);
161        }
162
163        /**
164         * Determines whether a failed transaction attempt should be retried.
165         * <p>
166         * Implementations should be thread-safe if the {@link RetryPolicy} is shared across threads.
167         *
168         * @author <a href="https://www.revetkn.com">Mark Allen</a>
169         * @since 4.4.0
170         */
171        @FunctionalInterface
172        public interface Condition {
173                /**
174                 * Determines whether a failed transaction attempt should be retried.
175                 *
176                 * @param failure the database failure that caused the transaction attempt to fail
177                 * @return {@code true} to retry, {@code false} to stop retrying
178                 */
179                @NonNull
180                Boolean shouldRetry(@NonNull DatabaseException failure);
181
182                /**
183                 * Creates a condition that retries serialization failures and deadlocks.
184                 *
185                 * @return a serialization-failure-or-deadlock retry condition
186                 */
187                @NonNull
188                static Condition serializationFailureOrDeadlock() {
189                        return failure -> {
190                                requireNonNull(failure);
191                                return failure.isSerializationFailure() || failure.isDeadlock();
192                        };
193                }
194
195                /**
196                 * Creates a condition that retries serialization failures.
197                 *
198                 * @return a serialization-failure retry condition
199                 */
200                @NonNull
201                static Condition serializationFailure() {
202                        return failure -> {
203                                requireNonNull(failure);
204                                return failure.isSerializationFailure();
205                        };
206                }
207
208                /**
209                 * Creates a condition that retries deadlocks.
210                 *
211                 * @return a deadlock retry condition
212                 */
213                @NonNull
214                static Condition deadlock() {
215                        return failure -> {
216                                requireNonNull(failure);
217                                return failure.isDeadlock();
218                        };
219                }
220
221                /**
222                 * Creates a condition that retries timeouts and cancellations recognized by Pyranid.
223                 * <p>
224                 * Timeouts and cancellations are not always safe to retry: the database may have completed part or all of the work
225                 * before the timeout surfaced to the caller. Use this condition only when the retried transaction body is safe to run
226                 * more than once for the application workflow.
227                 *
228                 * @return a timeout retry condition
229                 */
230                @NonNull
231                static Condition timeout() {
232                        return failure -> {
233                                requireNonNull(failure);
234                                return failure.isTimeout();
235                        };
236                }
237        }
238
239        /**
240         * Determines how long to wait before retrying after a failed attempt.
241         * <p>
242         * Implementations should be thread-safe if the {@link RetryPolicy} is shared across threads.
243         *
244         * @author <a href="https://www.revetkn.com">Mark Allen</a>
245         * @since 4.4.0
246         */
247        @FunctionalInterface
248        public interface Backoff {
249                /**
250                 * Determines how long to wait after a failed attempt before the next retry.
251                 *
252                 * @param failedAttemptNumber one-based number of the attempt that just failed
253                 * @param failure             the database failure that caused the attempt to fail
254                 * @return delay before the next retry
255                 */
256                @NonNull
257                Duration delayAfterFailedAttempt(@NonNull Integer failedAttemptNumber,
258                                                                                                                                                        @NonNull DatabaseException failure);
259
260                /**
261                 * Creates a fixed backoff.
262                 *
263                 * @param delay delay before every retry
264                 * @return a fixed backoff
265                 */
266                @NonNull
267                static Backoff fixed(@NonNull Duration delay) {
268                        requireNonNull(delay);
269                        validateDelay(delay, "delay");
270
271                        return (failedAttemptNumber, failure) -> {
272                                requireNonNull(failedAttemptNumber);
273                                requireNonNull(failure);
274                                validateFailedAttemptNumber(failedAttemptNumber);
275                                return delay;
276                        };
277                }
278
279                /**
280                 * Randomizes a delegate's delay uniformly at nanosecond resolution from zero (inclusive) to its cap (exclusive).
281                 * A zero cap remains zero. This is useful for spreading simultaneous retries across clients. The delegate must
282                 * return a non-null, nonnegative duration and be thread-safe when shared.
283                 *
284                 * @param delegate backoff supplying the delay cap
285                 * @return a backoff with full jitter
286                 * @since 4.8.0
287                 */
288                @NonNull
289                static Backoff fullJitter(@NonNull Backoff delegate) {
290                        return new FullJitterBackoff(requireNonNull(delegate));
291                }
292
293                /**
294                 * Creates an exponential backoff.
295                 * <p>
296                 * Failed attempt 1 returns {@code initialDelay}, failed attempt 2 returns {@code initialDelay * 2}, failed attempt 3
297                 * returns {@code initialDelay * 4}, and so on until the delay reaches {@code maxDelay}. Arithmetic overflow saturates
298                 * at {@code maxDelay}.
299                 *
300                 * @param initialDelay initial delay
301                 * @param maxDelay     maximum delay
302                 * @return an exponential backoff
303                 */
304                @NonNull
305                static Backoff exponential(@NonNull Duration initialDelay,
306                                                                                                                         @NonNull Duration maxDelay) {
307                        requireNonNull(initialDelay);
308                        requireNonNull(maxDelay);
309                        validateDelay(initialDelay, "initialDelay");
310                        validateDelay(maxDelay, "maxDelay");
311
312                        if (maxDelay.compareTo(initialDelay) < 0)
313                                throw new IllegalArgumentException("maxDelay must be greater than or equal to initialDelay");
314
315                        return (failedAttemptNumber, failure) -> {
316                                requireNonNull(failedAttemptNumber);
317                                requireNonNull(failure);
318                                validateFailedAttemptNumber(failedAttemptNumber);
319
320                                if (initialDelay.isZero())
321                                        return Duration.ZERO;
322
323                                Duration delay = initialDelay;
324
325                                for (int attempt = 1; attempt < failedAttemptNumber && delay.compareTo(maxDelay) < 0; ++attempt) {
326                                        try {
327                                                delay = delay.multipliedBy(2);
328                                        } catch (ArithmeticException e) {
329                                                return maxDelay;
330                                        }
331
332                                        if (delay.compareTo(maxDelay) > 0)
333                                                return maxDelay;
334                                }
335
336                                return delay;
337                        };
338                }
339
340                private static void validateDelay(@NonNull Duration delay,
341                                                                                                                                                        @NonNull String name) {
342                        requireNonNull(delay);
343                        requireNonNull(name);
344
345                        if (delay.isNegative())
346                                throw new IllegalArgumentException(format("%s must not be negative", name));
347                }
348
349                private static void validateFailedAttemptNumber(@NonNull Integer failedAttemptNumber) {
350                        requireNonNull(failedAttemptNumber);
351
352                        if (failedAttemptNumber < 1)
353                                throw new IllegalArgumentException("failedAttemptNumber must be at least 1");
354                }
355        }
356}