Skip to content
Draft
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
42 changes: 41 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,50 @@ client.charts.updateCategory("the chart key", CategoryKey.of("the category key")

When an API call results in a 4xx or 5xx error (e.g. when a chart could not be found), a SeatsioException is thrown.

This exception contains a message string describing what went wrong, and also two other properties:
This exception contains a message string describing what went wrong, and also these properties:

- `errors`: a list of errors that the server returned. In most cases, this array will contain only one element, an instance of ApiError, containing an error code and a message.
- `requestId`: the identifier of the request you made. Please mention this to us when you have questions, as it will make debugging easier.
- `idempotencyKey`: the `Idempotency-Key` sent with a `POST`, `PUT` or `DELETE` request (see [Idempotency](#idempotency)), or `null` for other requests.

`outcomeIsUnknown()` tells you whether the request may or may not have been executed: it's `true` when the connection failed or the server answered with a 5xx, and `false` for a 4xx.

If the server returns an error response without an error code (for example, an empty `errors` array), `errors` and `requestId` are `null`, and the message contains the HTTP status and the response body.

## Idempotency

**NOTE**: Idempotency is currently in a soft launch: it is enabled per company and not yet publicly available. Contact seats.io support to have it enabled for your company.

Every `POST`, `PUT` and `DELETE` request is sent with an `Idempotency-Key` header (a v4 UUID, generated by the client). If idempotency is enabled for your company, the server executes a request with a given key only once, and replays the original response (with the header `Idempotent-Replayed: true`) when it receives the same request again. If it isn't enabled, the server ignores the key.

If the connection fails after the server executed a request but before you received the response, you don't know whether the operation succeeded. The exception contains the key, so you can retry the operation with the same key:

```java
try {
client.events.create(chartKey);
} catch (SeatsioException e) {
// only retry when the outcome is unknown (a connection error, a timeout or a 5xx); retrying a 4xx can never succeed
if (e.idempotencyKey != null && e.outcomeIsUnknown()) {
client.withIdempotencyKey(e.idempotencyKey).events.create(chartKey);
}
}
```

The retried request must be identical to the original one, otherwise the server returns an error `422`. Every `POST`, `PUT` and `DELETE` made with the client returned by `withIdempotencyKey()` sends that key, so use it for one operation only. You can also supply your own key; it must be a v4 UUID, otherwise `withIdempotencyKey()` throws an `IllegalArgumentException`.

### Automatic retries

If the server answers `409` because an earlier request with the same key is still being processed, the client waits and retries it with the same key, like it does for `429`.

By default, the client doesn't retry `POST`, `PUT` and `DELETE` requests when the connection fails. To retry them (with the same key), enable it **only if idempotency is enabled for your company**. Otherwise, a retry could execute an operation that already succeeded a second time:

```java
SeatsioClient client = new SeatsioClient(Region.EU, <WORKSPACE SECRET KEY>).retryNonIdempotentRequests(true);
```

This setting also applies to the clients returned by `withIdempotencyKey()`, and the number of retries is limited by `maxRetries()`.

The client stops retrying when its thread is interrupted (the interrupt flag stays set). This applies to all retries, including those after a `429`.

## Rate limiting - exponential backoff

Expand Down
25 changes: 23 additions & 2 deletions src/main/java/seatsio/SeatsioClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

public class SeatsioClient {

public static final String IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";

private final String baseUrl;
private final UnirestWrapper unirest;

Expand All @@ -29,8 +31,12 @@ public class SeatsioClient {
public final TicketBuyers ticketBuyers;

public SeatsioClient(String secretKey, String workspaceKey, String baseUrl) {
this(baseUrl, new UnirestWrapper(secretKey, workspaceKey));
}

private SeatsioClient(String baseUrl, UnirestWrapper unirest) {
this.baseUrl = baseUrl;
this.unirest = new UnirestWrapper(secretKey, workspaceKey);
this.unirest = unirest;
this.workspaces = new Workspaces(baseUrl, unirest);
this.holdTokens = new HoldTokens(baseUrl, unirest);
this.charts = new Charts(baseUrl, unirest);
Expand All @@ -56,12 +62,27 @@ public SeatsioClient maxRetries(int maxRetries) {
return this;
}

public SeatsioClient retryNonIdempotentRequests(boolean retryNonIdempotentRequests) {
unirest.retryNonIdempotentRequests(retryNonIdempotentRequests);
return this;
}

/**
* Returns a client that sends the given Idempotency-Key with every POST, PUT and DELETE request.
* Use it to retry an operation whose outcome is unknown: take the key from SeatsioException.idempotencyKey and
* make the same call again on the returned client. Use the returned client for that one operation only.
*
* @throws IllegalArgumentException if the key is not a v4 UUID
*/
public SeatsioClient withIdempotencyKey(String idempotencyKey) {
return new SeatsioClient(baseUrl, unirest.withIdempotencyKey(idempotencyKey));
}

public String getBaseUrl() {
return baseUrl;
}

public void reinitializeHttpConnectionPool() {
this.unirest.reinitializeHttpConnectionPool();
}

}
67 changes: 42 additions & 25 deletions src/main/java/seatsio/SeatsioException.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,29 @@
import kong.unirest.RawResponse;
import seatsio.events.BestAvailableObjectsNotFoundException;
import seatsio.exceptions.RateLimitExceededException;
import seatsio.util.ErrorResponse;
import seatsio.util.UnirestWrapper;

import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static seatsio.json.SeatsioGson.gson;

public class SeatsioException extends RuntimeException {

public List<ApiError> errors;
public String requestId;
public String idempotencyKey;
private boolean outcomeIsUnknown;

public SeatsioException(String message) {
super(message);
}

public SeatsioException(Throwable t, HttpRequest request) {
super("Error while executing " + request.getHttpMethod() + " " + request.getUrl(), t);
this.idempotencyKey = idempotencyKey(request);
this.outcomeIsUnknown = true;
}

protected SeatsioException(List<ApiError> errors, String requestId) {
Expand All @@ -30,43 +35,55 @@ protected SeatsioException(List<ApiError> errors, String requestId) {
this.requestId = requestId;
}

private SeatsioException(HttpRequest request, RawResponse response) {
super(exceptionMessage(request, response));
private SeatsioException(HttpRequest request, RawResponse response, byte[] responseBody) {
super(exceptionMessage(request, response, responseBody));
}

public static SeatsioException from(HttpRequest request, RawResponse response, byte[] responseBody) {
if (response.getHeaders().getFirst("Content-Type").contains("application/json")) {
SeatsioExceptionTO parsedException = fromJson(responseBody);
if (response.getStatus() == 429) {
return new RateLimitExceededException(parsedException.errors, parsedException.requestId);
} else if (isBestAvailableObjectsNotFound(parsedException)) {
return new BestAvailableObjectsNotFoundException(parsedException.errors, parsedException.requestId);
}
return new SeatsioException(parsedException.errors, parsedException.requestId);
}
return new SeatsioException(request, response);
SeatsioException exception = create(request, response, responseBody);
exception.idempotencyKey = idempotencyKey(request);
exception.outcomeIsUnknown = response.getStatus() >= 500 || UnirestWrapper.isIdempotencyKeyInUse(response, responseBody);
return exception;
}

private static boolean isBestAvailableObjectsNotFound(SeatsioExceptionTO parsedException) {
return parsedException.errors.stream().anyMatch(e -> "BEST_AVAILABLE_OBJECTS_NOT_FOUND".equals(e.getCode()));
/**
* True if the request may or may not have been executed: the connection failed, the server answered with a 5xx, or the key was still in use after all retries (the first request may still succeed).
* Only then can retrying the same operation (with the same idempotencyKey) give a different result.
*/
public boolean outcomeIsUnknown() {
return outcomeIsUnknown;
}

private static String exceptionMessage(List<ApiError> errors) {
return errors.stream().map(ApiError::getMessage).collect(joining(", "));
private static String idempotencyKey(HttpRequest request) {
String key = request.getHeaders().getFirst(SeatsioClient.IDEMPOTENCY_KEY_HEADER);
return key.isEmpty() ? null : key;
}

private static String exceptionMessage(HttpRequest request, RawResponse response) {
return request.getHttpMethod() + " " + request.getUrl() + " resulted in a " + response.getStatus() + " " + response.getStatusText() + " response. Body: " + response.getContentAsString();
private static SeatsioException create(HttpRequest request, RawResponse response, byte[] responseBody) {
ErrorResponse errorResponse = ErrorResponse.parseIfAny(response, responseBody);
if (errorResponse == null) {
if (response.getStatus() == 429) {
return new RateLimitExceededException(exceptionMessage(request, response, responseBody));
}
return new SeatsioException(request, response, responseBody);
}
if (response.getStatus() == 429) {
return new RateLimitExceededException(errorResponse.errors, errorResponse.requestId);
} else if (isBestAvailableObjectsNotFound(errorResponse)) {
return new BestAvailableObjectsNotFoundException(errorResponse.errors, errorResponse.requestId);
}
return new SeatsioException(errorResponse.errors, errorResponse.requestId);
}

private static SeatsioExceptionTO fromJson(byte[] responseBody) {
return gson().fromJson(new String(responseBody, UTF_8), SeatsioExceptionTO.class);
private static boolean isBestAvailableObjectsNotFound(ErrorResponse errorResponse) {
return errorResponse.errors.stream().anyMatch(e -> "BEST_AVAILABLE_OBJECTS_NOT_FOUND".equals(e.getCode()));
}

private static class SeatsioExceptionTO {

public List<ApiError> errors;
public String requestId;
private static String exceptionMessage(List<ApiError> errors) {
return errors.stream().map(ApiError::getMessage).collect(joining(", "));
}

private static String exceptionMessage(HttpRequest request, RawResponse response, byte[] responseBody) {
return request.getHttpMethod() + " " + request.getUrl() + " resulted in a " + response.getStatus() + " " + response.getStatusText() + " response. Body: " + new String(responseBody, UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ public class RateLimitExceededException extends SeatsioException {
public RateLimitExceededException(List<ApiError> errors, String requestId) {
super(errors, requestId);
}

public RateLimitExceededException(String message) {
super(message);
}
}
35 changes: 35 additions & 0 deletions src/main/java/seatsio/util/ErrorResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package seatsio.util;

import com.google.gson.JsonParseException;
import kong.unirest.RawResponse;
import seatsio.ApiError;

import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static seatsio.json.SeatsioGson.gson;

public class ErrorResponse {

public List<ApiError> errors;
public String requestId;

public static ErrorResponse parseIfAny(RawResponse response, byte[] responseBody) {
if (!response.getHeaders().getFirst("Content-Type").contains("application/json")) {
return null;
}
try {
ErrorResponse errorResponse = gson().fromJson(new String(responseBody, UTF_8), ErrorResponse.class);
if (errorResponse == null || errorResponse.errors == null || errorResponse.errors.isEmpty() || errorResponse.errors.contains(null)) {
return null;
}
return errorResponse;
} catch (JsonParseException e) {
return null;
}
}

public String firstErrorCode() {
return errors.get(0).getCode();
}
}
Loading
Loading