|
| 1 | +package cloud.stackit.sdk.core.wait; |
| 2 | + |
| 3 | +import cloud.stackit.sdk.core.exception.ApiException; |
| 4 | +import cloud.stackit.sdk.core.exception.GenericOpenAPIException; |
| 5 | +import java.net.HttpURLConnection; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.HashSet; |
| 8 | +import java.util.Set; |
| 9 | +import java.util.concurrent.CompletableFuture; |
| 10 | +import java.util.concurrent.ScheduledFuture; |
| 11 | +import java.util.concurrent.TimeUnit; |
| 12 | +import java.util.concurrent.TimeoutException; |
| 13 | +import java.util.concurrent.atomic.AtomicInteger; |
| 14 | + |
| 15 | +public class AsyncActionHandler<T> { |
| 16 | + public static final Set<Integer> RETRY_HTTP_ERROR_STATUS_CODES = |
| 17 | + new HashSet<>( |
| 18 | + Arrays.asList( |
| 19 | + HttpURLConnection.HTTP_BAD_GATEWAY, |
| 20 | + HttpURLConnection.HTTP_GATEWAY_TIMEOUT)); |
| 21 | + |
| 22 | + public static final String TEMPORARY_ERROR_MESSAGE = |
| 23 | + "Temporary error was found and the retry limit was reached."; |
| 24 | + public static final String TIMEOUT_ERROR_MESSAGE = "WaitWithContextAsync() has timed out."; |
| 25 | + public static final String NON_GENERIC_API_ERROR_MESSAGE = "Found non-GenericOpenAPIError."; |
| 26 | + |
| 27 | + private final CheckFunction<AsyncActionResult<T>> checkFn; |
| 28 | + |
| 29 | + private long sleepBeforeWaitMillis; |
| 30 | + private long throttleMillis; |
| 31 | + private long timeoutMillis; |
| 32 | + private int tempErrRetryLimit; |
| 33 | + |
| 34 | + public AsyncActionHandler(CheckFunction<AsyncActionResult<T>> checkFn) { |
| 35 | + this.checkFn = checkFn; |
| 36 | + this.sleepBeforeWaitMillis = 0; |
| 37 | + this.throttleMillis = TimeUnit.SECONDS.toMillis(5); |
| 38 | + this.timeoutMillis = TimeUnit.MINUTES.toMillis(30); |
| 39 | + this.tempErrRetryLimit = 5; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * SetThrottle sets the time interval between each check of the async action. |
| 44 | + * |
| 45 | + * @param duration |
| 46 | + * @param unit |
| 47 | + */ |
| 48 | + public void setThrottle(long duration, TimeUnit unit) { |
| 49 | + this.throttleMillis = unit.toMillis(duration); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * SetTimeout sets the duration for wait timeout. |
| 54 | + * |
| 55 | + * @param duration |
| 56 | + * @param unit |
| 57 | + */ |
| 58 | + public void setTimeout(long duration, TimeUnit unit) { |
| 59 | + this.timeoutMillis = unit.toMillis(duration); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * SetSleepBeforeWait sets the duration for sleep before wait. |
| 64 | + * |
| 65 | + * @param duration |
| 66 | + * @param unit |
| 67 | + */ |
| 68 | + public void setSleepBeforeWait(long duration, TimeUnit unit) { |
| 69 | + this.sleepBeforeWaitMillis = unit.toMillis(duration); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * SetTempErrRetryLimit sets the retry limit if a temporary error is found. The list of |
| 74 | + * temporary errors is defined in the RetryHttpErrorStatusCodes variable. |
| 75 | + * |
| 76 | + * @param limit |
| 77 | + */ |
| 78 | + public void setTempErrRetryLimit(int limit) { |
| 79 | + this.tempErrRetryLimit = limit; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Runnable task which is executed periodically. |
| 84 | + * |
| 85 | + * @param future |
| 86 | + * @param startTime |
| 87 | + * @param retryTempErrorCounter |
| 88 | + */ |
| 89 | + private void executeCheckTask( |
| 90 | + CompletableFuture<T> future, long startTime, AtomicInteger retryTempErrorCounter) { |
| 91 | + if (future.isDone()) { |
| 92 | + return; |
| 93 | + } |
| 94 | + if (System.currentTimeMillis() - startTime >= timeoutMillis) { |
| 95 | + future.completeExceptionally(new TimeoutException(TIMEOUT_ERROR_MESSAGE)); |
| 96 | + } |
| 97 | + try { |
| 98 | + AsyncActionResult<T> result = checkFn.execute(); |
| 99 | + if (result != null && result.isFinished()) { |
| 100 | + future.complete(result.getResponse()); |
| 101 | + } |
| 102 | + } catch (ApiException e) { |
| 103 | + GenericOpenAPIException oapiErr = new GenericOpenAPIException(e); |
| 104 | + // Some APIs may return temporary errors and the request should be retried |
| 105 | + if (!RETRY_HTTP_ERROR_STATUS_CODES.contains(oapiErr.getStatusCode())) { |
| 106 | + return; |
| 107 | + } |
| 108 | + if (retryTempErrorCounter.incrementAndGet() == tempErrRetryLimit) { |
| 109 | + // complete the future with corresponding exception |
| 110 | + future.completeExceptionally(new Exception(TEMPORARY_ERROR_MESSAGE, oapiErr)); |
| 111 | + } |
| 112 | + } catch (IllegalStateException e) { |
| 113 | + future.completeExceptionally(e); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + /** |
| 118 | + * WaitWithContextAsync starts the wait until there's an error or wait is done |
| 119 | + * |
| 120 | + * @return |
| 121 | + */ |
| 122 | + public CompletableFuture<T> waitWithContextAsync() { |
| 123 | + if (throttleMillis <= 0) { |
| 124 | + throw new IllegalArgumentException("Throttle can't be 0 or less"); |
| 125 | + } |
| 126 | + |
| 127 | + CompletableFuture<T> future = new CompletableFuture<>(); |
| 128 | + long startTime = System.currentTimeMillis(); |
| 129 | + AtomicInteger retryTempErrorCounter = new AtomicInteger(0); |
| 130 | + |
| 131 | + // This runnable is called periodically. |
| 132 | + Runnable checkTask = () -> executeCheckTask(future, startTime, retryTempErrorCounter); |
| 133 | + |
| 134 | + // start the periodic execution |
| 135 | + ScheduledFuture<?> scheduledFuture = |
| 136 | + ScheduleExecutorSingleton.getInstance() |
| 137 | + .getScheduler() |
| 138 | + .scheduleWithFixedDelay( |
| 139 | + checkTask, |
| 140 | + sleepBeforeWaitMillis, |
| 141 | + throttleMillis, |
| 142 | + TimeUnit.MILLISECONDS); |
| 143 | + |
| 144 | + // stop task when future is completed |
| 145 | + future.whenComplete( |
| 146 | + (result, error) -> { |
| 147 | + scheduledFuture.cancel(true); |
| 148 | + }); |
| 149 | + |
| 150 | + return future; |
| 151 | + } |
| 152 | + |
| 153 | + // Helper class to encapsulate the result of the checkFn |
| 154 | + public static class AsyncActionResult<T> { |
| 155 | + private final boolean finished; |
| 156 | + private final T response; |
| 157 | + |
| 158 | + public AsyncActionResult(boolean finished, T response) { |
| 159 | + this.finished = finished; |
| 160 | + this.response = response; |
| 161 | + } |
| 162 | + |
| 163 | + public boolean isFinished() { |
| 164 | + return finished; |
| 165 | + } |
| 166 | + |
| 167 | + public T getResponse() { |
| 168 | + return response; |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + /** |
| 173 | + * Helper function to check http status codes during deletion of a resource. |
| 174 | + * |
| 175 | + * @param apiException ApiException to check |
| 176 | + * @return true if resource is gone otherwise false |
| 177 | + */ |
| 178 | + public static boolean checkResourceGoneStatusCodes(ApiException apiException) { |
| 179 | + GenericOpenAPIException oapiErr = new GenericOpenAPIException(apiException); |
| 180 | + return oapiErr.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND |
| 181 | + || oapiErr.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN; |
| 182 | + } |
| 183 | +} |
0 commit comments