Skip to content

Commit f95f92d

Browse files
committed
feature(core): Add wait handler structure
Signed-off-by: Alexander Dahmen <[email protected]>
1 parent e7b3c89 commit f95f92d

File tree

12 files changed

+1025
-72
lines changed

12 files changed

+1025
-72
lines changed

CONTRIBUTION.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ We greatly value your feedback, feature requests, additions to the code, bug rep
77

88
- [Developer Guide](#developer-guide)
99
- [Repository structure](#repository-structure)
10+
- [Implementing a module waiter](#implementing-a-module-waiter)
11+
- [Waiter structure](#waiter-structure)
12+
- [Notes](#notes)
1013
- [Code Contributions](#code-contributions)
1114
- [Bug Reports](#bug-reports)
1215

@@ -39,6 +42,29 @@ The files located in `services/[service]` are automatically generated from the [
3942

4043
Inside the `core` submodule you can find several classes that are used by all service modules. Examples of usage of the SDK are located in the `examples` directory.
4144

45+
### Implementing a service waiter
46+
47+
Waiters are routines that wait for the completion of asynchronous operations. They are located in a package named `wait` inside each service project.
48+
49+
Let's suppose you want to implement the waiters for the `Create`, `Update` and `Delete` operations of a resource `bar` of service `foo`:
50+
51+
1. Start by creating a new Java package `cloud.stackit.sdk.<service>.wait` inside `services/foo/` project, if it doesn't exist yet
52+
2. Create a file `FooWait.java` inside your new Java package `cloud.stackit.sdk.resourcemanager.wait`, if it doesn't exist yet. The class should be named `FooWait`.
53+
3. Refer to the [Waiter structure](./CONTRIBUTION.md/#waiter-structure) section for details on the structure of the file and the methods
54+
4. Add unit tests to the wait functions
55+
56+
#### Waiter structure
57+
58+
You can find a typical waiter structure here: [Example](./services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/wait/ResourcemanagerWait.java)
59+
60+
#### Notes
61+
62+
- The success condition may vary from service to service. In the example above we wait for the field `Status` to match a successful or failed message, but other services may have different fields and/or values to represent the state of the create, update or delete operations.
63+
- The `id` and the `state` might not be present on the root level of the API response, this also varies from service to service. You must always match the resource `id` and the resource `state` to what is expected.
64+
- The timeout values included above are just for reference, each resource takes different amounts of time to finish the create, update or delete operations. You should account for some buffer, e.g. 15 minutes, on top of normal execution times.
65+
- For some resources, after a successful delete operation the resource can't be found anymore, so a call to the `Get` method would result in an error. In those cases, the waiter can be implemented by calling the `List` method and check that the resource is not present.
66+
- The main objective of the waiter functions is to make sure that the operation was successful, which means any other special cases such as intermediate error states should also be handled.
67+
4268
## Code Contributions
4369

4470
To make your contribution, follow these steps:

core/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
## v0.4.0
2+
- **Feature:** Added core wait handler structure which can be used by every service waiter implementation.
3+
14
## v0.3.0
25
- **Feature:** New exception types for better error handling
36
- `AuthenticationException`: New exception for authentication-related failures (token generation, refresh, validation)
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package cloud.stackit.sdk.core.exception;
2+
3+
import java.nio.charset.StandardCharsets;
4+
import java.util.Arrays;
5+
6+
public class GenericOpenAPIException extends ApiException {
7+
// Created with serialver
8+
private static final long serialVersionUID = 3551449573139480120L;
9+
// When a response has a bad status, this limits the number of characters that are shown from
10+
// the response Body
11+
public int apiErrorMaxCharacterLimit = 500;
12+
13+
private final int statusCode;
14+
private byte[] body;
15+
private final String errorMessage;
16+
17+
public GenericOpenAPIException(ApiException apiException) {
18+
super(apiException.getMessage());
19+
this.statusCode = apiException.getCode();
20+
this.errorMessage = apiException.getMessage();
21+
}
22+
23+
public GenericOpenAPIException(int statusCode, String errorMessage) {
24+
this(statusCode, errorMessage, null);
25+
}
26+
27+
public GenericOpenAPIException(int statusCode, String errorMessage, byte[] body) {
28+
super(errorMessage);
29+
this.statusCode = statusCode;
30+
this.errorMessage = errorMessage;
31+
if (body != null) {
32+
this.body = Arrays.copyOf(body, body.length);
33+
}
34+
}
35+
36+
@Override
37+
public String getMessage() {
38+
// Prevent negative values
39+
if (apiErrorMaxCharacterLimit < 0) {
40+
apiErrorMaxCharacterLimit = 500;
41+
}
42+
43+
if (body == null) {
44+
return String.format("%s, status code %d", errorMessage, statusCode);
45+
}
46+
47+
String bodyStr = new String(body, StandardCharsets.UTF_8);
48+
49+
if (bodyStr.length() <= apiErrorMaxCharacterLimit) {
50+
return String.format("%s, status code %d, Body: %s", errorMessage, statusCode, bodyStr);
51+
}
52+
53+
int indexStart = apiErrorMaxCharacterLimit / 2;
54+
int indexEnd = bodyStr.length() - apiErrorMaxCharacterLimit / 2;
55+
int numberTruncatedCharacters = indexEnd - indexStart;
56+
57+
return String.format(
58+
"%s, status code %d, Body: %s [...truncated %d characters...] %s",
59+
errorMessage,
60+
statusCode,
61+
bodyStr.substring(0, indexStart),
62+
numberTruncatedCharacters,
63+
bodyStr.substring(indexEnd));
64+
}
65+
66+
public int getStatusCode() {
67+
return statusCode;
68+
}
69+
70+
public byte[] getBody() {
71+
if (body == null) {
72+
return new byte[0];
73+
}
74+
return Arrays.copyOf(body, body.length);
75+
}
76+
}
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
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+
// The linter is complaining about this but since we are using Java 8 the
35+
// possibilities are restricted.
36+
// @SuppressWarnings("PMD.DoNotUseThreads")
37+
// private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
38+
39+
public AsyncActionHandler(CheckFunction<AsyncActionResult<T>> checkFn) {
40+
this.checkFn = checkFn;
41+
this.sleepBeforeWaitMillis = 0;
42+
this.throttleMillis = TimeUnit.SECONDS.toMillis(5);
43+
this.timeoutMillis = TimeUnit.MINUTES.toMillis(30);
44+
this.tempErrRetryLimit = 5;
45+
}
46+
47+
/**
48+
* SetThrottle sets the time interval between each check of the async action.
49+
*
50+
* @param duration
51+
* @param unit
52+
*/
53+
public void setThrottle(long duration, TimeUnit unit) {
54+
this.throttleMillis = unit.toMillis(duration);
55+
}
56+
57+
/**
58+
* SetTimeout sets the duration for wait timeout.
59+
*
60+
* @param duration
61+
* @param unit
62+
*/
63+
public void setTimeout(long duration, TimeUnit unit) {
64+
this.timeoutMillis = unit.toMillis(duration);
65+
}
66+
67+
/**
68+
* SetSleepBeforeWait sets the duration for sleep before wait.
69+
*
70+
* @param duration
71+
* @param unit
72+
*/
73+
public void setSleepBeforeWait(long duration, TimeUnit unit) {
74+
this.sleepBeforeWaitMillis = unit.toMillis(duration);
75+
}
76+
77+
/**
78+
* SetTempErrRetryLimit sets the retry limit if a temporary error is found. The list of
79+
* temporary errors is defined in the RetryHttpErrorStatusCodes variable.
80+
*
81+
* @param limit
82+
*/
83+
public void setTempErrRetryLimit(int limit) {
84+
this.tempErrRetryLimit = limit;
85+
}
86+
87+
/**
88+
* Runnable task which is executed periodically.
89+
*
90+
* @param future
91+
* @param startTime
92+
* @param retryTempErrorCounter
93+
*/
94+
private void executeCheckTask(
95+
CompletableFuture<T> future, long startTime, AtomicInteger retryTempErrorCounter) {
96+
if (future.isDone()) {
97+
return;
98+
}
99+
if (System.currentTimeMillis() - startTime >= timeoutMillis) {
100+
future.completeExceptionally(new TimeoutException(TIMEOUT_ERROR_MESSAGE));
101+
}
102+
try {
103+
AsyncActionResult<T> result = checkFn.execute();
104+
if (result != null && result.isFinished()) {
105+
future.complete(result.getResponse());
106+
}
107+
} catch (ApiException e) {
108+
GenericOpenAPIException oapiErr = new GenericOpenAPIException(e);
109+
// Some APIs may return temporary errors and the request should be retried
110+
if (!RETRY_HTTP_ERROR_STATUS_CODES.contains(oapiErr.getStatusCode())) {
111+
return;
112+
}
113+
if (retryTempErrorCounter.incrementAndGet() == tempErrRetryLimit) {
114+
// complete the future with corresponding exception
115+
future.completeExceptionally(new Exception(TEMPORARY_ERROR_MESSAGE, oapiErr));
116+
}
117+
} catch (IllegalStateException e) {
118+
future.completeExceptionally(e);
119+
}
120+
}
121+
122+
/**
123+
* WaitWithContextAsync starts the wait until there's an error or wait is done
124+
*
125+
* @return
126+
*/
127+
public CompletableFuture<T> waitWithContextAsync() {
128+
if (throttleMillis <= 0) {
129+
throw new IllegalArgumentException("Throttle can't be 0 or less");
130+
}
131+
132+
CompletableFuture<T> future = new CompletableFuture<>();
133+
long startTime = System.currentTimeMillis();
134+
AtomicInteger retryTempErrorCounter = new AtomicInteger(0);
135+
136+
// This runnable is called periodically.
137+
Runnable checkTask = () -> executeCheckTask(future, startTime, retryTempErrorCounter);
138+
139+
// start the periodic execution
140+
ScheduledFuture<?> scheduledFuture =
141+
ScheduleExecutorSingleton.getInstance()
142+
.getScheduler()
143+
.scheduleAtFixedRate(
144+
checkTask,
145+
sleepBeforeWaitMillis,
146+
throttleMillis,
147+
TimeUnit.MILLISECONDS);
148+
149+
// stop task when future is completed
150+
future.whenComplete(
151+
(result, error) -> {
152+
scheduledFuture.cancel(true);
153+
// scheduler.shutdown();
154+
});
155+
156+
return future;
157+
}
158+
159+
// Helper class to encapsulate the result of the checkFn
160+
public static class AsyncActionResult<T> {
161+
private final boolean finished;
162+
private final T response;
163+
164+
public AsyncActionResult(boolean finished, T response) {
165+
this.finished = finished;
166+
this.response = response;
167+
}
168+
169+
public boolean isFinished() {
170+
return finished;
171+
}
172+
173+
public T getResponse() {
174+
return response;
175+
}
176+
}
177+
178+
/**
179+
* Helper function to check http status codes during deletion of a resource.
180+
*
181+
* @param e ApiException to check
182+
* @return true if resource is gone otherwise false
183+
*/
184+
public static boolean checkResourceGoneStatusCodes(ApiException apiException) {
185+
GenericOpenAPIException oapiErr = new GenericOpenAPIException(apiException);
186+
return oapiErr.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND
187+
|| oapiErr.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN;
188+
}
189+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package cloud.stackit.sdk.core.wait;
2+
3+
import cloud.stackit.sdk.core.exception.ApiException;
4+
5+
// Since the Callable FunctionalInterface throws a generic Exception
6+
// and the linter complains about catching a generic Exception this
7+
// FunctionalInterface is needed.
8+
@FunctionalInterface
9+
public interface CheckFunction<V> {
10+
V execute() throws ApiException;
11+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package cloud.stackit.sdk.core.wait;
2+
3+
import java.util.concurrent.Executors;
4+
import java.util.concurrent.ScheduledExecutorService;
5+
import java.util.concurrent.ThreadFactory;
6+
7+
@SuppressWarnings("PMD.DoNotUseThreads")
8+
public final class ScheduleExecutorSingleton {
9+
// Pool size for the thread pool
10+
private static final int POOL_SIZE = 1;
11+
private final ScheduledExecutorService scheduler;
12+
13+
private ScheduleExecutorSingleton() {
14+
// Use Daemon threads to prevent that the user need to call shutdown
15+
// even if its program was already terminated
16+
ThreadFactory daemonThreadFactory =
17+
runnable -> {
18+
Thread thread = new Thread(runnable);
19+
thread.setDaemon(true);
20+
return thread;
21+
};
22+
scheduler = Executors.newScheduledThreadPool(POOL_SIZE, daemonThreadFactory);
23+
}
24+
25+
public ScheduledExecutorService getScheduler() {
26+
return scheduler;
27+
}
28+
29+
// In order to make the Linter happy this is the only solution which is accepted.
30+
// Lock/ReentrantLock, synchronized and volatile are in general not accepted.
31+
private static final class SingletonHolder {
32+
public static final ScheduleExecutorSingleton INSTANCE = new ScheduleExecutorSingleton();
33+
}
34+
35+
public static ScheduleExecutorSingleton getInstance() {
36+
return SingletonHolder.INSTANCE;
37+
}
38+
}

0 commit comments

Comments
 (0)