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