package com.bcxin.Infrastructures.components;

import com.bcxin.Infrastructures.exceptions.ConflictTenantException;
import com.bcxin.Infrastructures.exceptions.RetryableTenantException;
import org.springframework.stereotype.Component;

/**
 * 重试接口
 */
public interface RetryProvider {
    void execute(Runnable runnable, int times);

    @Component
    public static class RetryProviderImpl implements RetryProvider
    {
        @Override
        public void execute(Runnable runnable, int times) {
            int retryTime = 0;
            while (true) {
                try {
                    runnable.run();
                    return;
                } catch (Exception ex) {
                    if(ex instanceof ConflictTenantException) {
                        throw ex;
                    }

                    retryTime++;
                    if (ex instanceof RetryableTenantException || ex.getMessage().contains("No provider available")) {
                        if (retryTime > times) {
                            throw ex;
                        }
                    } else {
                        throw ex;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {

                    }

                    ex.printStackTrace();
                }
            }
        }
    }
}
