diff --git a/README.md b/README.md index 1861c1a7..8fe3a36f 100644 --- a/README.md +++ b/README.md @@ -478,6 +478,40 @@ 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: @@ -485,7 +519,12 @@ You can provide your own `HttpClientBuilder` to customize HTTP connection proper ```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() @@ -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); @@ -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:** @@ -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 diff --git a/src/main/java/com/checkout/AbstractCheckoutSdkBuilder.java b/src/main/java/com/checkout/AbstractCheckoutSdkBuilder.java index 4bf2a958..de092be9 100644 --- a/src/main/java/com/checkout/AbstractCheckoutSdkBuilder.java +++ b/src/main/java/com/checkout/AbstractCheckoutSdkBuilder.java @@ -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 the type of API client this builder creates + */ public abstract class AbstractCheckoutSdkBuilder { - 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; @@ -17,11 +47,25 @@ public abstract class AbstractCheckoutSdkBuilder { 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 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 environmentSubdomain(final String subdomain) { this.subdomain = subdomain; return this; @@ -36,6 +80,7 @@ public AbstractCheckoutSdkBuilder environmentSubdomain(final String subdomain * merchant-specific subdomain cannot be used, and will be removed in a future release. * Call {@link #environmentSubdomain(String)} instead. * See Base URLs. + * @return this builder */ @Deprecated public AbstractCheckoutSdkBuilder useLegacyDomain() { @@ -43,25 +88,58 @@ public AbstractCheckoutSdkBuilder useLegacyDomain() { 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 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 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 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; } @@ -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 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 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 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"); @@ -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(); + } + } diff --git a/src/main/java/com/checkout/OAuthSdkCredentials.java b/src/main/java/com/checkout/OAuthSdkCredentials.java index c96ac89a..bae7157f 100644 --- a/src/main/java/com/checkout/OAuthSdkCredentials.java +++ b/src/main/java/com/checkout/OAuthSdkCredentials.java @@ -31,6 +31,10 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static com.checkout.common.CheckoutUtils.validateParams; @@ -56,7 +60,22 @@ final class OAuthSdkCredentials extends SdkCredentials { "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", "invalid_scope"))); + /** + * The longest a token request can take, in milliseconds, when the client configuration does not bound every wait + * itself (a connect, connection request or socket timeout that is not positive): 60 seconds. The abort does not + * interrupt a DNS lookup that is still running. + */ + private static final long TOKEN_REQUEST_DEADLINE_MILLIS = 60_000; + + /** + * Aborts the token requests that reach their deadline. At most one daemon thread, shared by every instance, which + * ends 5 seconds after the last pending deadline. + */ + private static final ScheduledThreadPoolExecutor DEADLINES = deadlineScheduler(); + private final URI authorizationUri; + private final long tokenRequestDeadlineMillis; + private final ScheduledExecutorService deadlines; private final String clientId; private final String clientSecret; private final Set scopes; @@ -81,6 +100,33 @@ final class OAuthSdkCredentials extends SdkCredentials { final String clientId, final String clientSecret, final Set scopes) { + this(httpClientBuilder, authorizationUri, clientId, clientSecret, scopes, TOKEN_REQUEST_DEADLINE_MILLIS); + } + + /** + * Creates the credentials with the given token request deadline. Package-private so tests can use a short bound + * on the same path. + */ + OAuthSdkCredentials(final HttpClientBuilder httpClientBuilder, + final URI authorizationUri, + final String clientId, + final String clientSecret, + final Set scopes, + final long tokenRequestDeadlineMillis) { + this(httpClientBuilder, authorizationUri, clientId, clientSecret, scopes, tokenRequestDeadlineMillis, DEADLINES); + } + + /** + * Creates the credentials with the given token request deadline and the scheduler that runs it. Package-private + * so a test can read the pending deadlines of its own scheduler. + */ + OAuthSdkCredentials(final HttpClientBuilder httpClientBuilder, + final URI authorizationUri, + final String clientId, + final String clientSecret, + final Set scopes, + final long tokenRequestDeadlineMillis, + final ScheduledExecutorService deadlines) { super(PlatformType.DEFAULT_OAUTH); validateParams("httpClientBuilder", httpClientBuilder, "authorizationUri", authorizationUri, "clientId", clientId, "clientSecret", clientSecret, "scopes", scopes); @@ -90,6 +136,8 @@ final class OAuthSdkCredentials extends SdkCredentials { this.clientSecret = clientSecret; this.scopes = scopes; this.serializer = new GsonSerializer(); + this.tokenRequestDeadlineMillis = tokenRequestDeadlineMillis; + this.deadlines = deadlines; } /** @@ -134,7 +182,8 @@ private synchronized OAuthAccessToken getAccessToken() { return accessToken; } final HttpPost httpPost = new HttpPost(authorizationUri); - httpPost.setConfig(withoutRedirects(client)); + final RequestConfig requestConfig = withoutRedirects(client); + httpPost.setConfig(requestConfig); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); try { final List data = Arrays.asList( @@ -147,6 +196,10 @@ private synchronized OAuthAccessToken getAccessToken() { throw new CheckoutException("failed to encode oAuth URI"); } log.debug("requesting OAuth token using client_credentials flow"); + // A client that does not bound every wait gets a deadline for the whole request; its own timeouts, including + // a socket timeout set through a SocketConfig, still apply and end the request first when they are shorter. + final ScheduledFuture deadline = boundsEveryWait(requestConfig) ? null + : deadlines.schedule(httpPost::abort, tokenRequestDeadlineMillis, TimeUnit.MILLISECONDS); try (final CloseableHttpResponse response = client.execute(httpPost)) { final int statusCode = response.getStatusLine().getStatusCode(); final String json = readBody(response); @@ -183,12 +236,46 @@ private synchronized OAuthAccessToken getAccessToken() { throw new CheckoutAuthorizationException(INVALID_TOKEN_RESPONSE); } catch (final IOException e) { throw new CheckoutAuthorizationException("OAuth client_credentials authentication failed", e); + } finally { + if (deadline != null) { + deadline.cancel(false); + } } } + /** + * Whether the connect, connection request and socket timeouts are all positive, so the client bounds every wait + * of the request itself. + */ + private static boolean boundsEveryWait(final RequestConfig config) { + return config.getConnectTimeout() > 0 + && config.getConnectionRequestTimeout() > 0 + && config.getSocketTimeout() > 0; + } + + /** + * The scheduler of the token request deadlines: one daemon thread without a context class loader that ends 5 + * seconds after the last pending deadline, so it does not outlive a redeployed application; cancelled deadlines + * removed at once. Package-private so a test can create its own with the same settings. + */ + static ScheduledThreadPoolExecutor deadlineScheduler() { + final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, runnable -> { + final Thread thread = new Thread(runnable, "checkout-sdk-oauth-token-deadline"); + thread.setDaemon(true); + thread.setContextClassLoader(null); + return thread; + }); + scheduler.setRemoveOnCancelPolicy(true); + scheduler.setKeepAliveTime(5, TimeUnit.SECONDS); + scheduler.allowCoreThreadTimeOut(true); + return scheduler; + } + /** * Reads the token endpoint response body. A body that cannot be read or decoded is an invalid token response. + * A token request aborted at its deadline while the body is being read also ends here, as an invalid token + * response without a cause. */ private static String readBody(final CloseableHttpResponse response) { if (response.getEntity() == null) { diff --git a/src/test/java/com/checkout/DefaultHttpClientTimeoutsTest.java b/src/test/java/com/checkout/DefaultHttpClientTimeoutsTest.java new file mode 100644 index 00000000..79055764 --- /dev/null +++ b/src/test/java/com/checkout/DefaultHttpClientTimeoutsTest.java @@ -0,0 +1,469 @@ +package com.checkout; + +import static com.checkout.TestHelper.VALID_DEFAULT_SK; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.concurrent.ScheduledThreadPoolExecutor; + +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.Configurable; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.config.SocketConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.Mockito; + +import com.sun.net.httpserver.HttpServer; + +/** + * Timeouts of the HTTP client: the builder the SDK creates has bounded connect, connection request and socket + * timeouts, used by the API and the OAuth token requests; a builder given through + * {@link AbstractCheckoutSdkBuilder#httpClientBuilder(HttpClientBuilder)} is used unchanged, and an OAuth token request + * with a client that does not bound every wait is aborted at its deadline. + */ +class DefaultHttpClientTimeoutsTest { + + private static final int CONNECT_TIMEOUT = 10_000; + private static final int CONNECTION_REQUEST_TIMEOUT = 60_000; + private static final int SOCKET_TIMEOUT = 60_000; + + private static RequestConfig configOf(final HttpClientBuilder httpClientBuilder) throws IOException { + try (CloseableHttpClient client = httpClientBuilder.build()) { + return ((Configurable) client).getConfig(); + } + } + + private static void assertDefaultTimeouts(final RequestConfig config) { + assertEquals(CONNECT_TIMEOUT, config.getConnectTimeout()); + assertEquals(CONNECTION_REQUEST_TIMEOUT, config.getConnectionRequestTimeout()); + assertEquals(SOCKET_TIMEOUT, config.getSocketTimeout()); + } + + @Test + void shouldSetTheDefaultTimeoutsOnTheHttpClientTheSdkCreates() throws IOException { + assertDefaultTimeouts(configOf(CheckoutSdk.builder().staticKeys().httpClientBuilder)); + assertDefaultTimeouts(configOf(CheckoutSdk.builder().oAuth().httpClientBuilder)); + assertDefaultTimeouts(configOf(new CheckoutPreviousSdkBuilder().staticKeys().httpClientBuilder)); + } + + @Test + void shouldKeepTheDefaultTimeoutsAfterTheSdkIsBuilt() throws IOException { + final CheckoutSdkBuilder.CheckoutStaticKeysSdkBuilder builder = CheckoutSdk.builder().staticKeys(); + builder.secretKey(VALID_DEFAULT_SK) + .environment(Environment.SANDBOX) + .environmentSubdomain("123dmain") + .build(); + + assertDefaultTimeouts(configOf(builder.httpClientBuilder)); + } + + @Test + void shouldUseACustomHttpClientBuilderWithoutTheDefaultTimeouts() throws IOException { + final HttpClientBuilder custom = HttpClientBuilder.create(); + final CheckoutSdkBuilder.CheckoutStaticKeysSdkBuilder builder = CheckoutSdk.builder().staticKeys(); + builder.secretKey(VALID_DEFAULT_SK) + .environment(Environment.SANDBOX) + .environmentSubdomain("123dmain") + .httpClientBuilder(custom) + .build(); + + assertSame(custom, builder.httpClientBuilder); + final RequestConfig config = configOf(custom); + assertEquals(RequestConfig.DEFAULT.getConnectTimeout(), config.getConnectTimeout()); + assertEquals(RequestConfig.DEFAULT.getConnectionRequestTimeout(), config.getConnectionRequestTimeout()); + assertEquals(RequestConfig.DEFAULT.getSocketTimeout(), config.getSocketTimeout()); + } + + @Test + void shouldKeepTheRequestConfigurationOfACustomHttpClientBuilder() throws IOException { + final RequestConfig merchantConfig = RequestConfig.custom().setSocketTimeout(1234).build(); + final HttpClientBuilder custom = HttpClientBuilder.create().setDefaultRequestConfig(merchantConfig); + final CheckoutSdkBuilder.CheckoutStaticKeysSdkBuilder builder = CheckoutSdk.builder().staticKeys(); + builder.secretKey(VALID_DEFAULT_SK) + .environment(Environment.SANDBOX) + .environmentSubdomain("123dmain") + .httpClientBuilder(custom) + .build(); + + final RequestConfig config = configOf(builder.httpClientBuilder); + assertEquals(1234, config.getSocketTimeout()); + assertEquals(RequestConfig.DEFAULT.getConnectTimeout(), config.getConnectTimeout()); + assertEquals(RequestConfig.DEFAULT.getConnectionRequestTimeout(), config.getConnectionRequestTimeout()); + } + + // Builds against a local server without a subdomain, so the legacy domain switch is needed here. + @Test + @SuppressWarnings("deprecation") + void shouldSendTheOAuthTokenAndApiRequestsWithTheDefaultTimeouts() throws IOException { + final HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + final String body = exchange.getRequestURI().getPath().endsWith("/connect/token") + ? "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":3600}" + : "{}"; + final byte[] response = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(response); + } + }); + server.start(); + try { + final URI base = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/"); + final List paths = Collections.synchronizedList(new ArrayList<>()); + final List configs = Collections.synchronizedList(new ArrayList<>()); + final CheckoutSdkBuilder.CheckoutOAuthSdkBuilder builder = CheckoutSdk.builder().oAuth(); + builder.httpClientBuilder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> { + paths.add(((HttpUriRequest) request).getURI().getPath()); + configs.add(HttpClientContext.adapt(context).getRequestConfig()); + }); + + final CheckoutApi checkoutApi = builder + .clientCredentials("client_id", "client_secret") + .environment(CustomEnvironment.builder() + .checkoutApi(base) + .filesApi(base) + .transfersApi(base) + .balancesApi(base) + .forwardApi(base) + .identityApi(base) + .oAuthAuthorizationApi(base.resolve("connect/token")) + .sandbox(true) + .build()) + .useLegacyDomain() + .recordTelemetry(false) + .build(); + checkoutApi.customersClient().getSync("cus_123"); + + assertEquals(2, configs.size()); + assertEquals("/connect/token", paths.get(0)); + assertEquals("/customers/cus_123", paths.get(1)); + assertDefaultTimeouts(configs.get(0)); + assertFalse(configs.get(0).isRedirectsEnabled()); + assertDefaultTimeouts(configs.get(1)); + } finally { + server.stop(0); + } + } + + // A socket that accepts the connection and never answers: the builder the SDK creates, with a short socket + // timeout to keep the test fast, fails the request within the bound. + @Test + @SuppressWarnings("deprecation") + void shouldFailWithAnApiExceptionWhenTheServerNeverAnswers() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final URI base = URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/"); + final CheckoutApi checkoutApi = CheckoutSdk.builder().staticKeys() + .secretKey(VALID_DEFAULT_SK) + .environment(localEnvironment(base)) + .useLegacyDomain() + .httpClientBuilder(AbstractCheckoutSdkBuilder.defaultHttpClientBuilder(shortSocketTimeout())) + .recordTelemetry(false) + .build(); + + final CheckoutException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutException.class, + () -> checkoutApi.customersClient().getSync("cus_123"))); + assertInstanceOf(CheckoutApiException.class, exception); + } + } + + /** + * The deadline aborts the request while it waits for the response: the connection is shut down and the read fails + * with a {@link SocketException}, unlike the client's own socket timeout ({@link SocketTimeoutException}). + */ + private static void assertAbortedAtTheDeadline(final CheckoutAuthorizationException exception) { + assertInstanceOf(SocketException.class, exception.getCause()); + } + + static RequestConfig shortSocketTimeout() { + return AbstractCheckoutSdkBuilder.timeouts(CONNECT_TIMEOUT, CONNECTION_REQUEST_TIMEOUT, 300); + } + + static CustomEnvironment localEnvironment(final URI base) { + return CustomEnvironment.builder() + .checkoutApi(base) + .filesApi(base) + .transfersApi(base) + .balancesApi(base) + .forwardApi(base) + .identityApi(base) + .oAuthAuthorizationApi(base.resolve("connect/token")) + .sandbox(true) + .build(); + } + + // OAuth: a token endpoint that accepts the connection and never answers. The token request deadline is 60 s, so + // the tests that need it to fire pass a short one through the package-private constructor; the code is the same. + + // Case 1: the builder the SDK creates bounds every wait itself (short socket timeout to keep the test fast). + @Test + void shouldFailTheTokenRequestWithinTheBoundOfTheBuilderTheSdkCreates() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + AbstractCheckoutSdkBuilder.defaultHttpClientBuilder(shortSocketTimeout()), + tokenUri(socket), "client_id", "client_secret", EnumSet.of(OAuthScope.ACCOUNTS)); + + assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess)); + } + } + + // Case 2: a merchant builder without timeouts: the token request deadline aborts the request. + @Test + void shouldAbortTheTokenRequestAtTheDeadlineWithACustomHttpClientBuilderWithoutTimeouts() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = new OAuthSdkCredentials(HttpClientBuilder.create(), + tokenUri(socket), "client_id", "client_secret", EnumSet.of(OAuthScope.ACCOUNTS), 300); + + final CheckoutAuthorizationException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess)); + assertAbortedAtTheDeadline(exception); + } + } + + // A timeout of 0 means no limit, so the deadline applies as well. + @Test + void shouldAbortTheTokenRequestAtTheDeadlineWithZeroTimeouts() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + HttpClientBuilder.create().setDefaultRequestConfig(AbstractCheckoutSdkBuilder.timeouts(0, 0, 0)), + tokenUri(socket), "client_id", "client_secret", EnumSet.of(OAuthScope.ACCOUNTS), 300); + + final CheckoutAuthorizationException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess)); + assertAbortedAtTheDeadline(exception); + } + } + + // A timeout above the deadline does not lift it while another timeout is unset: the deadline aborts the request + // before the 120 s socket timeout. + @Test + void shouldAbortTheTokenRequestAtTheDeadlineWhenATimeoutIsUnsetAndAnotherIsLonger() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + HttpClientBuilder.create().setDefaultRequestConfig( + RequestConfig.custom().setSocketTimeout(120_000).build()), + tokenUri(socket), "client_id", "client_secret", EnumSet.of(OAuthScope.ACCOUNTS), 300); + + final CheckoutAuthorizationException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess)); + assertAbortedAtTheDeadline(exception); + } + } + + // Each of the three timeouts is checked: with exactly one unset and the other two at 120 s, the deadline aborts the + // request before them. + @ParameterizedTest + @CsvSource({"-1, 120000, 120000", "120000, -1, 120000", "120000, 120000, -1"}) + void shouldAbortTheTokenRequestAtTheDeadlineWhenOneTimeoutIsUnset(final int connectMillis, + final int connectionRequestMillis, + final int socketMillis) throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + HttpClientBuilder.create().setDefaultRequestConfig( + AbstractCheckoutSdkBuilder.timeouts(connectMillis, connectionRequestMillis, socketMillis)), + tokenUri(socket), "client_id", "client_secret", EnumSet.of(OAuthScope.ACCOUNTS), 300); + + final CheckoutAuthorizationException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess)); + assertAbortedAtTheDeadline(exception); + } + } + + // The deadline thread does not keep the JVM or a redeployed application alive: it is a daemon without a context + // class loader, and it ends when no deadline is pending. + @Test + void shouldCreateADeadlineSchedulerThatDoesNotOutliveTheApplication() { + final ScheduledThreadPoolExecutor deadlines = OAuthSdkCredentials.deadlineScheduler(); + try { + assertTrue(deadlines.allowsCoreThreadTimeOut()); + assertTrue(deadlines.getRemoveOnCancelPolicy()); + final Thread thread = deadlines.getThreadFactory().newThread(() -> { + }); + assertTrue(thread.isDaemon()); + assertNull(thread.getContextClassLoader()); + } finally { + deadlines.shutdownNow(); + } + } + + // A client that bounds every wait gets no deadline: with a 100 ms deadline the request still ends on its own + // 300 ms socket timeout, not on an abort. + @Test + void shouldNotSetADeadlineWhenTheClientBoundsEveryWait() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + HttpClientBuilder.create().setDefaultRequestConfig(shortSocketTimeout()), + tokenUri(socket), "client_id", "client_secret", EnumSet.of(OAuthScope.ACCOUNTS), 100); + + final CheckoutAuthorizationException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess)); + assertInstanceOf(SocketTimeoutException.class, exception.getCause()); + } + } + + // A deadline is cancelled when the token request ends first, so it does not keep the request until it expires. + @Test + void shouldCancelTheDeadlineWhenTheTokenRequestEnds() throws IOException { + final HttpServer server = tokenServer(); + final ScheduledThreadPoolExecutor deadlines = OAuthSdkCredentials.deadlineScheduler(); + server.start(); + try { + final URI tokenUri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/connect/token"); + new OAuthSdkCredentials(HttpClientBuilder.create(), tokenUri, "client_id", "client_secret", + EnumSet.of(OAuthScope.ACCOUNTS), 60_000, deadlines).initOAuthAccess(); + + assertEquals(0, deadlines.getQueue().size()); + } finally { + deadlines.shutdownNow(); + server.stop(0); + } + } + + // Case 3: a merchant timeout is kept (shorter than the real 60 s deadline, so the test would hang otherwise). + @Test + void shouldKeepTheMerchantTimeoutWhenTheTokenEndpointNeverAnswers() throws IOException { + assertTokenRequestFailsFastWith(HttpClientBuilder.create().setDefaultRequestConfig( + RequestConfig.custom().setSocketTimeout(300).build())); + } + + // A socket timeout set only through SocketConfig is kept too (the request configuration is not changed). + @Test + void shouldKeepASocketConfigTimeoutWhenTheTokenEndpointNeverAnswers() throws IOException { + assertTokenRequestFailsFastWith(HttpClientBuilder.create() + .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(300).build())); + } + + // The token request is sent with the merchant configuration unchanged, redirects off. + @Test + void shouldSendTheOAuthTokenRequestWithTheConfigurationOfACustomHttpClientBuilder() throws IOException { + final HttpClientBuilder custom = HttpClientBuilder.create() + .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(1234).build()); + final List configs = recordTokenRequestConfigs(custom); + + assertEquals(1, configs.size()); + assertEquals(1234, configs.get(0).getSocketTimeout()); + assertEquals(RequestConfig.DEFAULT.getConnectTimeout(), configs.get(0).getConnectTimeout()); + assertEquals(RequestConfig.DEFAULT.getConnectionRequestTimeout(), configs.get(0).getConnectionRequestTimeout()); + assertFalse(configs.get(0).isRedirectsEnabled()); + } + + // A client that does not expose its configuration: the request falls back to the default one, redirects off. + @Test + void shouldSendTheOAuthTokenRequestWithoutRedirectsWhenTheClientHasNoConfiguration() throws IOException { + final CloseableHttpClient client = Mockito.mock(CloseableHttpClient.class); + final List configs = Collections.synchronizedList(new ArrayList<>()); + Mockito.when(client.execute(Mockito.any(HttpUriRequest.class))).thenAnswer(invocation -> { + configs.add(((HttpPost) invocation.getArgument(0)).getConfig()); + throw new IOException("no answer"); + }); + final HttpClientBuilder custom = new HttpClientBuilder() { + @Override + public CloseableHttpClient build() { + return client; + } + }; + final OAuthSdkCredentials credentials = new OAuthSdkCredentials(custom, + URI.create("https://access.sandbox.checkout.com/connect/token"), "client_id", "client_secret", + EnumSet.of(OAuthScope.ACCOUNTS)); + + assertThrows(CheckoutAuthorizationException.class, credentials::initOAuthAccess); + assertEquals(1, configs.size()); + assertEquals(RequestConfig.DEFAULT.getSocketTimeout(), configs.get(0).getSocketTimeout()); + assertFalse(configs.get(0).isRedirectsEnabled()); + } + + @SuppressWarnings("deprecation") + private static void assertTokenRequestFailsFastWith(final HttpClientBuilder custom) throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final URI base = URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/"); + final CheckoutSdkBuilder.CheckoutOAuthSdkBuilder builder = CheckoutSdk.builder().oAuth(); + builder.clientCredentials("client_id", "client_secret") + .environment(localEnvironment(base)) + .useLegacyDomain() + .httpClientBuilder(custom) + .recordTelemetry(false); + + assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutAuthorizationException.class, builder::build)); + } + } + + /** + * A local server that answers every request with a valid token response; not started. + */ + private static HttpServer tokenServer() throws IOException { + final HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + final byte[] response = "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":3600}" + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(response); + } + }); + return server; + } + + private static URI tokenUri(final ServerSocket socket) { + return URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/connect/token"); + } + + /** + * Builds an OAuth SDK with the given builder against a local token endpoint and returns the request + * configuration of each token request sent. + */ + @SuppressWarnings("deprecation") + private static List recordTokenRequestConfigs(final HttpClientBuilder custom) throws IOException { + final HttpServer server = tokenServer(); + server.start(); + try { + final URI base = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/"); + final List configs = Collections.synchronizedList(new ArrayList<>()); + custom.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> { + if (((HttpUriRequest) request).getURI().getPath().endsWith("/connect/token")) { + configs.add(HttpClientContext.adapt(context).getRequestConfig()); + } + }); + CheckoutSdk.builder().oAuth() + .clientCredentials("client_id", "client_secret") + .environment(localEnvironment(base)) + .useLegacyDomain() + .httpClientBuilder(custom) + .recordTelemetry(false) + .build(); + return configs; + } finally { + server.stop(0); + } + } +}