Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
## Release (2025-xx-xx)
- `core`: [v0.4.0](core/CHANGELOG.md#v040)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick, but please combine the changelogs for the core module with the entry from below 😄

- **Feature:** Added core wait handler structure which can be used by every service waiter implementation.
- `resourcemanager`: [v0.3.0](services/resourcemanager/CHANGELOG.md#v030)
- **Feature:** Added waiter for project creation and project deletion
- `core`: [v0.3.0](core/CHANGELOG.md#v030)
- **Feature:** New exception types for better error handling
- `AuthenticationException`: New exception for authentication-related failures (token generation, refresh, validation)
Expand Down
26 changes: 26 additions & 0 deletions CONTRIBUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ We greatly value your feedback, feature requests, additions to the code, bug rep

- [Developer Guide](#developer-guide)
- [Repository structure](#repository-structure)
- [Implementing a module waiter](#implementing-a-module-waiter)
- [Waiter structure](#waiter-structure)
- [Notes](#notes)
- [Code Contributions](#code-contributions)
- [Bug Reports](#bug-reports)

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

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.

### Implementing a service waiter

Waiters are routines that wait for the completion of asynchronous operations. They are located in a package named `wait` inside each service project.

Let's suppose you want to implement the waiters for the `Create`, `Update` and `Delete` operations of a resource `bar` of service `foo`:

1. Start by creating a new Java package `cloud.stackit.sdk.<service>.wait` inside `services/foo/` project, if it doesn't exist yet
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`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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`.
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`.

3. Refer to the [Waiter structure](./CONTRIBUTION.md/#waiter-structure) section for details on the structure of the file and the methods
4. Add unit tests to the wait functions

#### Waiter structure

You can find a typical waiter structure here: [Example](./services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/wait/ResourcemanagerWait.java)

#### Notes

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

## Code Contributions

To make your contribution, follow these steps:
Expand Down
3 changes: 3 additions & 0 deletions core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## v0.4.0
- **Feature:** Added core wait handler structure which can be used by every service waiter implementation.

## v0.3.0
- **Feature:** New exception types for better error handling
- `AuthenticationException`: New exception for authentication-related failures (token generation, refresh, validation)
Expand Down
2 changes: 1 addition & 1 deletion core/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.3.0
0.4.0
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);
}
}
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;
}
}
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;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package cloud.stackit.sdk.core.wait;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@SuppressWarnings({
"PMD.DoNotUseThreads",
"PMD.SingleMethodSingleton",
"PMD.NonThreadSafeSingleton"
})
public final class ScheduleExecutorSingleton {
// Default pool size for the thread pool
private static final int DEFAULT_POOL_SIZE = 1;
private static ScheduleExecutorSingleton instance;
private static final Lock LOCK = new ReentrantLock();
private final ScheduledExecutorService scheduler;

/** Default constructor which takes the default pool size */
private ScheduleExecutorSingleton() {
this(DEFAULT_POOL_SIZE);
}

/**
* Constructor to set a different pool size
*
* @param poolSize
*/
private ScheduleExecutorSingleton(int poolSize) {
// Use Daemon threads to prevent that the user need to call shutdown
// even if its program was already terminated
ThreadFactory daemonThreadFactory =
runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
};
this.scheduler = Executors.newScheduledThreadPool(poolSize, daemonThreadFactory);
}

public static ScheduleExecutorSingleton getInstance() {
return getInstance(DEFAULT_POOL_SIZE);
}

public static ScheduleExecutorSingleton getInstance(int poolSize) {
if (instance == null) {
LOCK.lock();
try {
if (instance == null) {
instance = new ScheduleExecutorSingleton(poolSize);
}
} finally {
LOCK.unlock();
}
}
return instance;
}

public ScheduledExecutorService getScheduler() {
return scheduler;
}
}
Loading