001/*-
002 * #%L
003 * HAPI FHIR JPA - Search Parameters
004 * %%
005 * Copyright (C) 2014 - 2025 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.jpa.searchparam.retry;
021
022import ca.uhn.fhir.system.HapiSystemProperties;
023import org.apache.commons.lang3.Validate;
024import org.apache.commons.lang3.time.DateUtils;
025import org.slf4j.Logger;
026import org.slf4j.LoggerFactory;
027import org.springframework.beans.factory.BeanCreationException;
028import org.springframework.retry.RetryCallback;
029import org.springframework.retry.RetryContext;
030import org.springframework.retry.RetryListener;
031import org.springframework.retry.backoff.ExponentialBackOffPolicy;
032import org.springframework.retry.policy.SimpleRetryPolicy;
033import org.springframework.retry.support.RetryTemplate;
034
035import java.util.function.Supplier;
036
037public class Retrier<T> {
038        private static final Logger ourLog = LoggerFactory.getLogger(Retrier.class);
039
040        private final Supplier<T> mySupplier;
041
042        private final RetryTemplate myRetryTemplate;
043
044        public Retrier(Supplier<T> theSupplier, int theMaxRetries) {
045                Validate.isTrue(theMaxRetries > 0, "maxRetries must be above zero.");
046                mySupplier = theSupplier;
047
048                myRetryTemplate = new RetryTemplate();
049
050                ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
051                backOff.setInitialInterval(500);
052                backOff.setMaxInterval(DateUtils.MILLIS_PER_MINUTE);
053                backOff.setMultiplier(2);
054                myRetryTemplate.setBackOffPolicy(backOff);
055
056                SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy() {
057                        private static final long serialVersionUID = -4522467251787518700L;
058
059                        @Override
060                        public boolean canRetry(RetryContext context) {
061                                Throwable lastThrowable = context.getLastThrowable();
062                                if (lastThrowable instanceof BeanCreationException || lastThrowable instanceof NullPointerException) {
063                                        return false;
064                                }
065                                return super.canRetry(context);
066                        }
067                };
068                retryPolicy.setMaxAttempts(theMaxRetries);
069                myRetryTemplate.setRetryPolicy(retryPolicy);
070
071                RetryListener listener = new RetryListener() {
072                        @Override
073                        public <TT, E extends Throwable> void onError(
074                                        RetryContext context, RetryCallback<TT, E> callback, Throwable throwable) {
075                                if (throwable instanceof NullPointerException
076                                                || throwable instanceof UnsupportedOperationException
077                                                || HapiSystemProperties.isUnitTestModeEnabled()) {
078                                        ourLog.error(
079                                                        "Retry failure {}/{}: {}",
080                                                        context.getRetryCount(),
081                                                        theMaxRetries,
082                                                        throwable.getMessage(),
083                                                        throwable);
084                                } else {
085                                        ourLog.error(
086                                                        "Retry failure {}/{}: {}", context.getRetryCount(), theMaxRetries, throwable.toString());
087                                }
088                        }
089                };
090                myRetryTemplate.registerListener(listener);
091        }
092
093        public T runWithRetry() {
094                return myRetryTemplate.execute(retryContext -> mySupplier.get());
095        }
096}