Skip to content

Commit c54b20c

Browse files
authored
feature(core): Add wait handler structure (#19)
* feature(core): Add wait handler structure Signed-off-by: Alexander Dahmen <[email protected]> * chore(core): Make SchedulerExecutor thread pool size configurable Signed-off-by: Alexander Dahmen <[email protected]> * Add changelogs Signed-off-by: Alexander Dahmen <[email protected]> --------- Signed-off-by: Alexander Dahmen <[email protected]>
1 parent 83e503a commit c54b20c

File tree

16 files changed

+1062
-79
lines changed

16 files changed

+1062
-79
lines changed

CHANGELOG.md

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
## Release (2025-xx-xx)
2-
- `core`: [v0.3.0](core/CHANGELOG.md#v030)
3-
- **Feature:** New exception types for better error handling
4-
- `AuthenticationException`: New exception for authentication-related failures (token generation, refresh, validation)
5-
- `resourcemanager`: [v0.3.0](services/resourcemanager/CHANGELOG.md#v030)
6-
- **Feature:** Add `ContainerSearchResult` model class for container search functionality
2+
- `core`:
3+
- [v0.4.0](core/CHANGELOG.md#v040)
4+
- **Feature:** Added core wait handler structure which can be used by every service waiter implementation.
5+
- [v0.3.0](core/CHANGELOG.md#v030)
6+
- **Feature:** New exception types for better error handling
7+
- `AuthenticationException`: New exception for authentication-related failures (token generation, refresh, validation)
8+
- `resourcemanager`:
9+
- [v0.4.0](services/resourcemanager/CHANGELOG.md#v040)
10+
- **Feature:** Added waiter for project creation and project deletion
11+
- [v0.3.0](services/resourcemanager/CHANGELOG.md#v030)
12+
- **Feature:** Add `ContainerSearchResult` model class for container search functionality
13+
714

815
## Release (2025-09-30)
916
- `core`: [v0.2.0](core/CHANGELOG.md#v020)

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.<service>.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)

core/VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0.3.0
1+
0.4.0
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: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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+
}
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+
}

0 commit comments

Comments
 (0)