Skip to content
Merged
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
51 changes: 48 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -478,14 +478,53 @@ missing or invalid URI fails `build()` with a `CheckoutArgumentException` that n

The SDK allows you to customize the underlying HTTP client and executor configurations to meet your specific needs, such as custom connection pooling, proxy settings, timeout configurations, or multithreaded operations.

### Default timeouts

When no `HttpClientBuilder` is given, the SDK creates one with these timeouts, used for the API requests and, with
OAuth, for the token requests:

- **Connect timeout**: 10 seconds to open the connection.
- **Connection request timeout**: 60 seconds to get a connection from the pool.
- **Socket timeout**: 60 seconds without data from the server (between two packets, not a limit on the whole request).

A request that times out no longer waits with no limit. A token request fails with a `CheckoutAuthorizationException`.
An API request is reported like any other transport failure, with the default status of the transport configuration:
with the default one it fails with a `CheckoutApiException` with status 400; a `transportConfiguration(...)` with a 2xx
default status returns an empty response instead. A builder passed to `httpClientBuilder(...)` is used as given, without
these defaults, so set the timeouts you need on it. With OAuth, the token requests use your timeouts too; when your
builder does not set a positive connect, connection request and socket timeout with `setDefaultRequestConfig`, a token
request is also aborted after 60 seconds in total (a DNS lookup still running is not interrupted), even when one of the
timeouts you set is longer. Set all three to bound the token requests with your own values:

```java
final RequestConfig timeouts = RequestConfig.custom()
.setConnectTimeout(5_000) // milliseconds
.setConnectionRequestTimeout(5_000)
.setSocketTimeout(30_000)
.build();

final CheckoutApi checkoutApi = CheckoutSdk.builder()
.staticKeys()
.secretKey("secret_key")
.environment(Environment.PRODUCTION) // required
.environmentSubdomain("subdomain") // required, Merchant-specific DNS name, the first 8 characters of your client ID
.httpClientBuilder(HttpClientBuilder.create().setDefaultRequestConfig(timeouts))
.build();
```

### Basic HttpClient Configuration

You can provide your own `HttpClientBuilder` to customize HTTP connection properties:

```java
final HttpClientBuilder customHttpClient = HttpClientBuilder.create()
.setProxy(HttpHost.create("https://proxy"))
.setConnectionTimeToLive(3, TimeUnit.SECONDS);
.setConnectionTimeToLive(3, TimeUnit.SECONDS)
.setDefaultRequestConfig(RequestConfig.custom() // a builder you pass gets no default timeouts
.setConnectTimeout(10_000)
.setConnectionRequestTimeout(60_000)
.setSocketTimeout(60_000)
.build());

final CheckoutApi checkoutApi = CheckoutSdk.builder()
.staticKeys()
Expand Down Expand Up @@ -521,7 +560,12 @@ final HttpClientBuilder multithreadedHttpClient = HttpClientBuilder.create()
.setMaxConnTotal(200) // Maximum total connections
.setMaxConnPerRoute(100) // Maximum connections per route/destination
.setConnectionTimeToLive(60, TimeUnit.SECONDS) // Connection time-to-live
.evictIdleConnections(30, TimeUnit.SECONDS); // Evict idle connections after 30 seconds
.evictIdleConnections(30, TimeUnit.SECONDS) // Evict idle connections after 30 seconds
.setDefaultRequestConfig(RequestConfig.custom() // a builder you pass gets no default timeouts
.setConnectTimeout(10_000)
.setConnectionRequestTimeout(60_000)
.setSocketTimeout(60_000)
.build());

// Configure a fixed thread pool executor
final Executor multithreadedExecutor = Executors.newFixedThreadPool(100);
Expand All @@ -538,7 +582,7 @@ final CheckoutApi checkoutApi = CheckoutSdk.builder()
**Configuration Options Explained:**

- **`executor(Executor)`**: Configures the executor service for handling asynchronous operations. Default is `ForkJoinPool.commonPool()`.
- **`httpClientBuilder(HttpClientBuilder)`**: Configures the Apache HttpClient settings. Default is `HttpClientBuilder.create()`.
- **`httpClientBuilder(HttpClientBuilder)`**: Configures the Apache HttpClient settings. Default is `HttpClientBuilder.create()` with the [default timeouts](#default-timeouts); a builder you pass is used without them.

**Common HttpClient Settings:**

Expand All @@ -549,6 +593,7 @@ final CheckoutApi checkoutApi = CheckoutSdk.builder()
- **`setProxy(HttpHost)`**: Configure HTTP proxy server
- **`setDefaultConnectionConfig(ConnectionConfig)`**: Set default connection configuration
- **`setDefaultSocketConfig(SocketConfig)`**: Set socket configuration including timeouts
- **`setDefaultRequestConfig(RequestConfig)`**: Set the connect, connection request and socket timeouts of each request

## Advanced Customization for Different Throughput Requirements

Expand Down
157 changes: 156 additions & 1 deletion src/main/java/com/checkout/AbstractCheckoutSdkBuilder.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,43 @@
package com.checkout;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;

import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;

/**
* Common settings of the SDK builders: environment, merchant-specific subdomain, HTTP client, executor, transport,
* telemetry, operation mode and resilience. The credentials are set by each concrete builder.
*
* @param <T> the type of API client this builder creates
*/
public abstract class AbstractCheckoutSdkBuilder<T extends CheckoutApiClient> {

protected HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
/**
* Connect timeout of the HTTP client the SDK creates: 10 seconds, in milliseconds.
*/
private static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 10_000;

/**
* Timeout to obtain a connection from the pool of the HTTP client the SDK creates: 60 seconds, in milliseconds, the
* same as the socket timeout, so a request queued behind slow requests for a free connection is not failed sooner
* than one that is already waiting for the server.
*/
private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS = 60_000;

/**
* Socket (read) timeout of the HTTP client the SDK creates, the longest wait between two data packets: 60 seconds,
* in milliseconds.
*/
private static final int DEFAULT_SOCKET_TIMEOUT_MILLIS = 60_000;

/**
* The builder of the HTTP client used for the API requests and, with OAuth, for the token requests. Unless
* {@link #httpClientBuilder(HttpClientBuilder)} replaces it, it is created by the SDK with a connect timeout of
* 10 seconds, a connection request timeout of 60 seconds and a socket timeout of 60 seconds.
*/
protected HttpClientBuilder httpClientBuilder = defaultHttpClientBuilder();
private IEnvironment environment;
private String subdomain;
private boolean useLegacyDomain;
Expand All @@ -17,11 +47,25 @@ public abstract class AbstractCheckoutSdkBuilder<T extends CheckoutApiClient> {
private Boolean synchronous = false;
private Resilience4jConfiguration resilience4jConfiguration;

/**
* Sets the environment (sandbox, production or a custom one) whose base URIs the requests use. Required.
*
* @param environment the environment
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> environment(final IEnvironment environment) {
this.environment = environment;
return this;
}

/**
* Sets the merchant-specific subdomain the base URIs of the environment are moved to (the first 8 characters of
* the client ID, excluding {@code cli_}). Required unless {@link #useLegacyDomain()} is called or the builder is for the
* Previous platform.
*
* @param subdomain the merchant-specific subdomain
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> environmentSubdomain(final String subdomain) {
this.subdomain = subdomain;
return this;
Expand All @@ -36,32 +80,66 @@ public AbstractCheckoutSdkBuilder<T> environmentSubdomain(final String subdomain
* merchant-specific subdomain cannot be used, and will be removed in a future release.
* Call {@link #environmentSubdomain(String)} instead.
* See <a href="https://api-reference.checkout.com/#section/Base-URLs">Base URLs</a>.
* @return this builder
*/
@Deprecated
public AbstractCheckoutSdkBuilder<T> useLegacyDomain() {
this.useLegacyDomain = true;
return this;
}

/**
* Replaces the HTTP client builder the SDK creates. The builder is used as given: the SDK default timeouts
* (connect 10 seconds, connection request 60 seconds, socket 60 seconds) are not applied to it, so set your own
* with {@link HttpClientBuilder#setDefaultRequestConfig(RequestConfig)}; without them a request can wait for a
* response with no limit. With OAuth, the token requests use the same builder and its timeouts; when it does not
* set a positive connect, connection request and socket timeout, a token request is also aborted after 60 seconds
* in total (a DNS lookup still running is not interrupted), even when one of the timeouts it sets is longer.
*
* @param httpClientBuilder the builder of the HTTP client for the API and OAuth token requests
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> httpClientBuilder(final HttpClientBuilder httpClientBuilder) {
this.httpClientBuilder = httpClientBuilder;
return this;
}

/**
* Sets the executor that runs the asynchronous requests. Defaults to {@link ForkJoinPool#commonPool()}.
*
* @param executor the executor
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> executor(final Executor executor) {
this.executor = executor;
return this;
}

/**
* Sets the transport configuration. Defaults to {@link DefaultTransportConfiguration}.
*
* @param transportConfiguration the transport configuration
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> transportConfiguration(final TransportConfiguration transportConfiguration) {
this.transportConfiguration = transportConfiguration;
return this;
}

/**
* The environment set with {@link #environment(IEnvironment)}.
*
* @return the environment, or {@code null} when none is set
*/
protected IEnvironment getEnvironment() {
return environment;
}

/**
* The merchant-specific subdomain set with {@link #environmentSubdomain(String)}, applied to the environment.
*
* @return the environment subdomain, or {@code null} when no subdomain is set
*/
protected EnvironmentSubdomain getEnvironmentSubdomain() {
return subdomain != null ? new EnvironmentSubdomain(environment, subdomain) : null;
}
Expand All @@ -70,28 +148,62 @@ protected EnvironmentSubdomain getEnvironmentSubdomain() {
* Whether this builder requires the merchant-specific subdomain to be configured.
* The Previous (ABC) platform predates merchant-specific subdomains, so it overrides
* this to {@code false}.
*
* @return {@code true} when the subdomain is required
*/
protected boolean requiresEnvironmentSubdomain() {
return true;
}

/**
* Sets whether request telemetry (including request latency) is sent to Checkout.com. Enabled by default.
*
* @param recordTelemetry {@code false} to opt out of request telemetry
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> recordTelemetry(final Boolean recordTelemetry) {
this.recordTelemetry = recordTelemetry;
return this;
}

/**
* Sets the operation mode. Asynchronous by default; in synchronous mode every operation, including the asynchronous
* ones, sends its request through the blocking path, where the Resilience4j configuration applies, on the executor
* of {@link #executor(Executor)}; the methods still return a {@link java.util.concurrent.CompletableFuture}.
*
* @param synchronous {@code true} for synchronous mode
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> synchronous(final Boolean synchronous) {
this.synchronous = synchronous;
return this;
}

/**
* Sets the Resilience4j configuration (retry, rate limiter, circuit breaker) used in synchronous mode. None by
* default.
*
* @param resilience4jConfiguration the Resilience4j configuration
* @return this builder
*/
public AbstractCheckoutSdkBuilder<T> resilience4jConfiguration(final Resilience4jConfiguration resilience4jConfiguration) {
this.resilience4jConfiguration = resilience4jConfiguration;
return this;
}

/**
* The credentials of the concrete builder (static keys or OAuth).
*
* @return the SDK credentials
*/
protected abstract SdkCredentials getSdkCredentials();

/**
* Validates the settings and builds the configuration the API clients use.
*
* @return the checkout configuration
* @throws CheckoutArgumentException if the environment is missing or the subdomain settings are invalid
*/
protected CheckoutConfiguration getCheckoutConfiguration() {
if (environment == null) {
throw new CheckoutArgumentException("environment must be specified");
Expand All @@ -117,6 +229,49 @@ private CheckoutConfiguration buildCheckoutConfiguration(final SdkCredentials sd
return new DefaultCheckoutConfiguration(sdkCredentials, getEnvironment(), getEnvironmentSubdomain(), httpClientBuilder, executor, transportConfiguration, recordTelemetry, synchronous, resilience4jConfiguration);
}

/**
* Builds the API client with the settings of this builder.
*
* @return the API client
* @throws CheckoutArgumentException if a required setting is missing or invalid
* @throws CheckoutAuthorizationException with OAuth, if the first token request, sent while building, fails or
* its response is invalid
*/
public abstract T build();

/**
* The HTTP client builder the SDK creates when none is given, with bounded connect, connection request and socket
* timeouts so a request that gets no response fails instead of waiting with no limit.
*/
private static HttpClientBuilder defaultHttpClientBuilder() {
return defaultHttpClientBuilder(defaultTimeouts());
}

/**
* The HTTP client builder the SDK creates, with the given timeouts. Package-private so tests can use a short
* bound on the same path.
*/
static HttpClientBuilder defaultHttpClientBuilder(final RequestConfig timeouts) {
return HttpClientBuilder.create().setDefaultRequestConfig(timeouts);
}

/**
* The default connect, connection request and socket timeouts of the HTTP client the SDK creates.
*/
private static RequestConfig defaultTimeouts() {
return timeouts(DEFAULT_CONNECT_TIMEOUT_MILLIS, DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS,
DEFAULT_SOCKET_TIMEOUT_MILLIS);
}

/**
* A request configuration with the given connect, connection request and socket timeouts, in milliseconds.
*/
static RequestConfig timeouts(final int connectMillis, final int connectionRequestMillis, final int socketMillis) {
return RequestConfig.custom()
.setConnectTimeout(connectMillis)
.setConnectionRequestTimeout(connectionRequestMillis)
.setSocketTimeout(socketMillis)
.build();
}

}
Loading
Loading