-
Couldn't load subscription status.
- Fork 0
feature(core): Add wait handler structure #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| 0.3.0 | ||
| 0.4.0 |
76 changes: 76 additions & 0 deletions
76
core/src/main/java/cloud/stackit/sdk/core/exception/GenericOpenAPIException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| package cloud.stackit.sdk.core.exception; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Arrays; | ||
|
|
||
| public class GenericOpenAPIException extends ApiException { | ||
| // Created with serialver | ||
| private static final long serialVersionUID = 3551449573139480120L; | ||
| // When a response has a bad status, this limits the number of characters that are shown from | ||
| // the response Body | ||
| public int apiErrorMaxCharacterLimit = 500; | ||
|
|
||
| private final int statusCode; | ||
| private byte[] body; | ||
| private final String errorMessage; | ||
|
|
||
| public GenericOpenAPIException(ApiException apiException) { | ||
| super(apiException.getMessage()); | ||
| this.statusCode = apiException.getCode(); | ||
| this.errorMessage = apiException.getMessage(); | ||
| } | ||
|
|
||
| public GenericOpenAPIException(int statusCode, String errorMessage) { | ||
| this(statusCode, errorMessage, null); | ||
| } | ||
|
|
||
| public GenericOpenAPIException(int statusCode, String errorMessage, byte[] body) { | ||
| super(errorMessage); | ||
| this.statusCode = statusCode; | ||
| this.errorMessage = errorMessage; | ||
| if (body != null) { | ||
| this.body = Arrays.copyOf(body, body.length); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public String getMessage() { | ||
| // Prevent negative values | ||
| if (apiErrorMaxCharacterLimit < 0) { | ||
| apiErrorMaxCharacterLimit = 500; | ||
| } | ||
|
|
||
| if (body == null) { | ||
| return String.format("%s, status code %d", errorMessage, statusCode); | ||
| } | ||
|
|
||
| String bodyStr = new String(body, StandardCharsets.UTF_8); | ||
|
|
||
| if (bodyStr.length() <= apiErrorMaxCharacterLimit) { | ||
| return String.format("%s, status code %d, Body: %s", errorMessage, statusCode, bodyStr); | ||
| } | ||
|
|
||
| int indexStart = apiErrorMaxCharacterLimit / 2; | ||
| int indexEnd = bodyStr.length() - apiErrorMaxCharacterLimit / 2; | ||
| int numberTruncatedCharacters = indexEnd - indexStart; | ||
|
|
||
| return String.format( | ||
| "%s, status code %d, Body: %s [...truncated %d characters...] %s", | ||
| errorMessage, | ||
| statusCode, | ||
| bodyStr.substring(0, indexStart), | ||
| numberTruncatedCharacters, | ||
| bodyStr.substring(indexEnd)); | ||
| } | ||
|
|
||
| public int getStatusCode() { | ||
| return statusCode; | ||
| } | ||
|
|
||
| public byte[] getBody() { | ||
| if (body == null) { | ||
| return new byte[0]; | ||
| } | ||
| return Arrays.copyOf(body, body.length); | ||
| } | ||
| } |
183 changes: 183 additions & 0 deletions
183
core/src/main/java/cloud/stackit/sdk/core/wait/AsyncActionHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| package cloud.stackit.sdk.core.wait; | ||
|
|
||
| import cloud.stackit.sdk.core.exception.ApiException; | ||
| import cloud.stackit.sdk.core.exception.GenericOpenAPIException; | ||
| import java.net.HttpURLConnection; | ||
| import java.util.Arrays; | ||
| import java.util.HashSet; | ||
| import java.util.Set; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.concurrent.ScheduledFuture; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.TimeoutException; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
|
|
||
| public class AsyncActionHandler<T> { | ||
| public static final Set<Integer> RETRY_HTTP_ERROR_STATUS_CODES = | ||
| new HashSet<>( | ||
| Arrays.asList( | ||
| HttpURLConnection.HTTP_BAD_GATEWAY, | ||
| HttpURLConnection.HTTP_GATEWAY_TIMEOUT)); | ||
|
|
||
| public static final String TEMPORARY_ERROR_MESSAGE = | ||
| "Temporary error was found and the retry limit was reached."; | ||
| public static final String TIMEOUT_ERROR_MESSAGE = "WaitWithContextAsync() has timed out."; | ||
| public static final String NON_GENERIC_API_ERROR_MESSAGE = "Found non-GenericOpenAPIError."; | ||
|
|
||
| private final CheckFunction<AsyncActionResult<T>> checkFn; | ||
|
|
||
| private long sleepBeforeWaitMillis; | ||
| private long throttleMillis; | ||
| private long timeoutMillis; | ||
| private int tempErrRetryLimit; | ||
|
|
||
| public AsyncActionHandler(CheckFunction<AsyncActionResult<T>> checkFn) { | ||
| this.checkFn = checkFn; | ||
| this.sleepBeforeWaitMillis = 0; | ||
| this.throttleMillis = TimeUnit.SECONDS.toMillis(5); | ||
| this.timeoutMillis = TimeUnit.MINUTES.toMillis(30); | ||
| this.tempErrRetryLimit = 5; | ||
| } | ||
|
|
||
| /** | ||
| * SetThrottle sets the time interval between each check of the async action. | ||
| * | ||
| * @param duration | ||
| * @param unit | ||
| */ | ||
| public void setThrottle(long duration, TimeUnit unit) { | ||
| this.throttleMillis = unit.toMillis(duration); | ||
| } | ||
|
|
||
| /** | ||
| * SetTimeout sets the duration for wait timeout. | ||
| * | ||
| * @param duration | ||
| * @param unit | ||
| */ | ||
| public void setTimeout(long duration, TimeUnit unit) { | ||
| this.timeoutMillis = unit.toMillis(duration); | ||
| } | ||
|
|
||
| /** | ||
| * SetSleepBeforeWait sets the duration for sleep before wait. | ||
| * | ||
| * @param duration | ||
| * @param unit | ||
| */ | ||
| public void setSleepBeforeWait(long duration, TimeUnit unit) { | ||
| this.sleepBeforeWaitMillis = unit.toMillis(duration); | ||
| } | ||
|
|
||
| /** | ||
| * SetTempErrRetryLimit sets the retry limit if a temporary error is found. The list of | ||
| * temporary errors is defined in the RetryHttpErrorStatusCodes variable. | ||
| * | ||
| * @param limit | ||
| */ | ||
| public void setTempErrRetryLimit(int limit) { | ||
| this.tempErrRetryLimit = limit; | ||
| } | ||
|
|
||
| /** | ||
| * Runnable task which is executed periodically. | ||
| * | ||
| * @param future | ||
| * @param startTime | ||
| * @param retryTempErrorCounter | ||
| */ | ||
| private void executeCheckTask( | ||
| CompletableFuture<T> future, long startTime, AtomicInteger retryTempErrorCounter) { | ||
| if (future.isDone()) { | ||
| return; | ||
| } | ||
| if (System.currentTimeMillis() - startTime >= timeoutMillis) { | ||
| future.completeExceptionally(new TimeoutException(TIMEOUT_ERROR_MESSAGE)); | ||
| } | ||
| try { | ||
| AsyncActionResult<T> result = checkFn.execute(); | ||
| if (result != null && result.isFinished()) { | ||
| future.complete(result.getResponse()); | ||
| } | ||
| } catch (ApiException e) { | ||
| GenericOpenAPIException oapiErr = new GenericOpenAPIException(e); | ||
| // Some APIs may return temporary errors and the request should be retried | ||
| if (!RETRY_HTTP_ERROR_STATUS_CODES.contains(oapiErr.getStatusCode())) { | ||
| return; | ||
| } | ||
| if (retryTempErrorCounter.incrementAndGet() == tempErrRetryLimit) { | ||
| // complete the future with corresponding exception | ||
| future.completeExceptionally(new Exception(TEMPORARY_ERROR_MESSAGE, oapiErr)); | ||
| } | ||
| } catch (IllegalStateException e) { | ||
| future.completeExceptionally(e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * WaitWithContextAsync starts the wait until there's an error or wait is done | ||
| * | ||
| * @return | ||
| */ | ||
| public CompletableFuture<T> waitWithContextAsync() { | ||
| if (throttleMillis <= 0) { | ||
| throw new IllegalArgumentException("Throttle can't be 0 or less"); | ||
| } | ||
|
|
||
| CompletableFuture<T> future = new CompletableFuture<>(); | ||
| long startTime = System.currentTimeMillis(); | ||
| AtomicInteger retryTempErrorCounter = new AtomicInteger(0); | ||
|
|
||
| // This runnable is called periodically. | ||
| Runnable checkTask = () -> executeCheckTask(future, startTime, retryTempErrorCounter); | ||
|
|
||
| // start the periodic execution | ||
| ScheduledFuture<?> scheduledFuture = | ||
| ScheduleExecutorSingleton.getInstance() | ||
| .getScheduler() | ||
| .scheduleWithFixedDelay( | ||
| checkTask, | ||
| sleepBeforeWaitMillis, | ||
| throttleMillis, | ||
| TimeUnit.MILLISECONDS); | ||
|
|
||
| // stop task when future is completed | ||
| future.whenComplete( | ||
| (result, error) -> { | ||
| scheduledFuture.cancel(true); | ||
| }); | ||
|
|
||
| return future; | ||
| } | ||
|
|
||
| // Helper class to encapsulate the result of the checkFn | ||
| public static class AsyncActionResult<T> { | ||
| private final boolean finished; | ||
| private final T response; | ||
|
|
||
| public AsyncActionResult(boolean finished, T response) { | ||
| this.finished = finished; | ||
| this.response = response; | ||
| } | ||
|
|
||
| public boolean isFinished() { | ||
| return finished; | ||
| } | ||
|
|
||
| public T getResponse() { | ||
| return response; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Helper function to check http status codes during deletion of a resource. | ||
| * | ||
| * @param apiException ApiException to check | ||
| * @return true if resource is gone otherwise false | ||
| */ | ||
| public static boolean checkResourceGoneStatusCodes(ApiException apiException) { | ||
| GenericOpenAPIException oapiErr = new GenericOpenAPIException(apiException); | ||
| return oapiErr.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND | ||
| || oapiErr.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN; | ||
| } | ||
| } | ||
11 changes: 11 additions & 0 deletions
11
core/src/main/java/cloud/stackit/sdk/core/wait/CheckFunction.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package cloud.stackit.sdk.core.wait; | ||
|
|
||
| import cloud.stackit.sdk.core.exception.ApiException; | ||
|
|
||
| // Since the Callable FunctionalInterface throws a generic Exception | ||
| // and the linter complains about catching a generic Exception this | ||
| // FunctionalInterface is needed. | ||
| @FunctionalInterface | ||
| public interface CheckFunction<V> { | ||
| V execute() throws ApiException; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.