fix(cloudfront): honor origin connection timeouts and attempts, answer 504 (#5802)

* fix(cloudfront): honor origin connection timeouts and attempts, answer 504

CloudFront ignored a custom origin's ConnectionTimeout, OriginReadTimeout and
ConnectionAttempts and answered 502 for any origin failure. Apply the origin's
connect and read timeouts to the origin request, retry a timed-out GET/HEAD up
to ConnectionAttempts, and answer 504 with the AWS message when the last
attempt times out. A refused connection or an unknown host still answers 502.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(cloudfront): retry a connect timeout for every origin method

Review follow-ups on the origin timeout work:

- Connection attempts count for every method, not only GET and HEAD: a
  connect timeout or a refused connection is retried up to the configured
  ConnectionAttempts whatever the method is. Apache HttpClient 5's
  ConnectTimeoutException extends SocketTimeoutException, so it is caught
  first to keep the split: a response timeout is still retried only for an
  idempotent method and still answers 504, while a refused connection
  propagates unchanged as a bad gateway.
- The origin read and connection timeout bounds moved into
  CloudFrontOriginTimeouts, shared by CloudFrontController,
  CloudFrontServingController and CloudFrontOriginHttpClient instead of
  being repeated in each.
- The slow-origin tests hold the origin open on a CountDownLatch with
  millisecond client timeouts rather than sleeping out a fixed delay, so an
  attempt ends by the client's own timeout and the suite finishes in
  seconds.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-18 20:56:42 -04:00
1 parent 916e72570e
commit 5306e0e470
7 files changed
+497 -22

No files matched your search

@@ -45,6 +45,7 @@ import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -82,9 +83,14 @@ class CloudFrontCustomOriginServingTest {
final PartitionCleanup cleanup = new PartitionCleanup();
private HttpServer originServer;
private CountDownLatch originRelease;
@AfterEach
void stopOrigin() {
if (originRelease != null) {
originRelease.countDown();
originRelease = null;
}
if (originServer != null) {
originServer.stop(0);
}
@@ -340,6 +346,56 @@ class CloudFrontCustomOriginServingTest {
assertEquals(5, hits.get());
}
@Test
void answers504AndStopsWaitingWhenTheOriginExceedsTheReadTimeout() throws Exception {
AtomicInteger hits = new AtomicInteger();
startHoldingOrigin(hits);
Distribution created = cloudFrontService.createDistribution(
customOriginDistribution(allMethodsBehavior(), null, 1, 1), Map.of());
long started = System.nanoTime();
given().header("Host", created.getDomainName()).when().get("/page")
.then().statusCode(504)
.body(equalTo(CloudFrontServingController.ORIGIN_TIMEOUT_MESSAGE));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertEquals(1, hits.get());
assertTrue(elapsedMillis < 10000,
"expected the 1 s origin read timeout to end the request, took " + elapsedMillis + " ms");
}
@Test
void retriesTheReadTimeoutForGetUpToConnectionAttempts() throws Exception {
AtomicInteger hits = new AtomicInteger();
startHoldingOnlyTheFirstRequest(hits);
Distribution created = cloudFrontService.createDistribution(
customOriginDistribution(allMethodsBehavior(), null, 1, 2), Map.of());
given().header("Host", created.getDomainName()).when().get("/page")
.then().statusCode(200)
.body(equalTo("origin-body"));
assertEquals(2, hits.get(), "a GET that timed out should be retried once");
}
@Test
void doesNotRetryTheReadTimeoutForPost() throws Exception {
AtomicInteger hits = new AtomicInteger();
startHoldingOrigin(hits);
Distribution created = cloudFrontService.createDistribution(
customOriginDistribution(allMethodsBehavior(), null, 1, 2), Map.of());
long started = System.nanoTime();
given().header("Host", created.getDomainName()).when().post("/page")
.then().statusCode(504)
.body(equalTo(CloudFrontServingController.ORIGIN_TIMEOUT_MESSAGE));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertEquals(1, hits.get(), "a POST that hit a read timeout must not be retried");
assertTrue(elapsedMillis < 10000,
"expected the 1 s origin read timeout to end the request, took " + elapsedMillis + " ms");
}
@Test
void streamsALargeOriginResponseWithItsLength() throws Exception {
byte[] video = randomBytes(3 * 1024 * 1024 + 1);
@@ -932,6 +988,64 @@ class CloudFrontCustomOriginServingTest {
originServer.start();
}
/**
* An origin that counts its hits and holds every request open until the test releases it, so an
* attempt ends only by the client's own read timeout rather than by racing a fixed origin delay.
*/
private void startHoldingOrigin(AtomicInteger hits) throws IOException {
originRelease = new CountDownLatch(1);
CountDownLatch release = originRelease;
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
originServer.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
originServer.createContext("/", exchange -> {
hits.incrementAndGet();
holdUntilReleased(release);
answerOriginBody(exchange);
});
originServer.start();
}
/** An origin that holds its first request until the retry arrives, then answers that one. */
private void startHoldingOnlyTheFirstRequest(AtomicInteger hits) throws IOException {
originRelease = new CountDownLatch(1);
CountDownLatch retryArrived = originRelease;
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
originServer.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
originServer.createContext("/", exchange -> {
if (hits.incrementAndGet() == 1) {
holdUntilReleased(retryArrived);
} else {
retryArrived.countDown();
}
answerOriginBody(exchange);
});
originServer.start();
}
/**
* Holds the request open until {@code release} opens, with a generous cap so a client that never
* times out fails the assertion instead of hanging the suite.
*/
private static void holdUntilReleased(CountDownLatch release) {
try {
release.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private static void answerOriginBody(HttpExchange exchange) {
byte[] body = "origin-body".getBytes(StandardCharsets.UTF_8);
try {
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} catch (IOException expected) {
// The viewer gave up on this attempt after its read timeout, which the test triggers.
} finally {
exchange.close();
}
}
/** An origin that answers every GET with {@code body}, with its length or chunked. */
private void startServingOrigin(byte[] body, boolean withLength) throws IOException {
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
@@ -1007,11 +1121,25 @@ class CloudFrontCustomOriginServingTest {
private Distribution customOriginDistribution(DefaultCacheBehavior behavior,
List<Map<String, String>> customHeaders) {
return customOriginDistribution(behavior, customHeaders, null, null);
}
private Distribution customOriginDistribution(DefaultCacheBehavior behavior,
List<Map<String, String>> customHeaders,
Integer readTimeoutSeconds,
Integer connectionAttempts) {
Map<String, Object> originConfig = customOriginConfig(originServer.getAddress().getPort());
if (readTimeoutSeconds != null) {
originConfig.put("OriginReadTimeout", readTimeoutSeconds);
}
Origin customOrigin = new Origin();
customOrigin.setId("custom-origin");
customOrigin.setDomainName("127.0.0.1");
customOrigin.setCustomOriginConfig(customOriginConfig(originServer.getAddress().getPort()));
customOrigin.setCustomOriginConfig(originConfig);
customOrigin.setCustomHeaders(customHeaders);
if (connectionAttempts != null) {
customOrigin.setConnectionAttempts(connectionAttempts);
}
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setOrigins(List.of(customOrigin));
@@ -21,8 +21,10 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.net.UnknownHostException;
import java.net.http.HttpRequest;
@@ -36,6 +38,7 @@ import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -361,6 +364,185 @@ class CloudFrontOriginHttpClientTest {
}
}
@Test
void retriesAnIdempotentRequestUntilTheAttemptsAreExhausted() throws Exception {
AtomicInteger hits = new AtomicInteger();
CountDownLatch release = new CountDownLatch(1);
HttpServer server = holdingServer(hits, release);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(200), 3);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertEquals(3, hits.get());
assertTrue(elapsedMillis < 5000,
"expected the 200 ms read timeout to end every attempt on an origin that never "
+ "answers, took " + elapsedMillis + " ms");
} finally {
release.countDown();
server.stop(0);
}
}
@Test
void doesNotRetryAnIdempotentRequestWhenOnlyOneAttemptIsConfigured() throws Exception {
AtomicInteger hits = new AtomicInteger();
CountDownLatch release = new CountDownLatch(1);
HttpServer server = holdingServer(hits, release);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(200), 1);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
assertEquals(1, hits.get());
} finally {
release.countDown();
server.stop(0);
}
}
@Test
void doesNotRetryAResponseTimeoutForANonIdempotentRequest() throws Exception {
AtomicInteger hits = new AtomicInteger();
CountDownLatch release = new CountDownLatch(1);
HttpServer server = holdingServer(hits, release);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(200), 3);
HttpRequest request = HttpRequest.newBuilder(URI.create(
"http://origin.invalid:" + server.getAddress().getPort() + "/"))
.method("POST", HttpRequest.BodyPublishers.noBody())
.build();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
assertEquals(1, hits.get(), "a POST that hit a response timeout must not be retried");
} finally {
release.countDown();
server.stop(0);
}
}
@Test
void retriesAConnectTimeoutForANonIdempotentRequest() throws Exception {
AtomicInteger resolutions = new AtomicInteger();
DnsResolver resolver = countingResolver(resolutions, InetAddress.getByName("192.0.2.1"));
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver, List.of("blackhole.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofMillis(100), Duration.ofSeconds(5), 3);
HttpRequest request = HttpRequest.newBuilder(URI.create("http://blackhole.invalid:81/"))
.method("POST", HttpRequest.BodyPublishers.noBody())
.build();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
assertEquals(3, resolutions.get(),
"a POST whose connect times out counts as a connection attempt and is retried");
}
}
@Test
void retriesARefusedConnectionForANonIdempotentRequest() throws Exception {
int refusedPort;
try (ServerSocket socket = new ServerSocket(0)) {
refusedPort = socket.getLocalPort();
}
AtomicInteger resolutions = new AtomicInteger();
DnsResolver resolver = countingResolver(resolutions, InetAddress.getByName("127.0.0.1"));
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver, List.of("refused.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(5), 3);
HttpRequest request = HttpRequest.newBuilder(URI.create(
"http://refused.invalid:" + refusedPort + "/"))
.method("POST", HttpRequest.BodyPublishers.noBody())
.build();
assertThrows(ConnectException.class, () -> get(client, request, timeouts));
assertEquals(3, resolutions.get(),
"a POST whose connection is refused counts as a connection attempt and is retried");
}
}
@Test
void honorsTheConfiguredReadTimeout() throws Exception {
AtomicInteger hits = new AtomicInteger();
CountDownLatch release = new CountDownLatch(1);
HttpServer server = holdingServer(hits, release);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(150), 1);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(elapsedMillis < 5000,
"expected the configured 150 ms read timeout to end the request, not the 30 s "
+ "default, took " + elapsedMillis + " ms");
} finally {
release.countDown();
server.stop(0);
}
}
private static CloudFrontOriginHttpClient.OpenResponse get(
CloudFrontOriginHttpClient client, HttpRequest request,
CloudFrontOriginHttpClient.OriginTimeouts timeouts) throws Exception {
return client.open(request, List.of(), Map.of(), null, -1, timeouts);
}
/**
* An origin that counts its hits and holds every request open until {@code release} opens, so a
* client that answers nothing never races a fixed origin delay: only the client's own timeout
* can end an attempt.
*/
private static HttpServer holdingServer(AtomicInteger hits, CountDownLatch release) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/", exchange -> {
hits.incrementAndGet();
try {
exchange.getRequestBody().readAllBytes();
release.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException expected) {
// The client gave up on the attempt, which is what the read timeout under test causes.
}
try {
byte[] body = "origin-ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} catch (IOException expected) {
// The client is gone, so there is nobody left to answer.
} finally {
exchange.close();
}
});
server.start();
return server;
}
private static CloudFrontOriginHttpClient.OpenResponse get(CloudFrontOriginHttpClient client,
HttpRequest request) throws Exception {
return client.open(request, List.of(), Map.of(), null, -1);
@@ -404,6 +586,22 @@ class CloudFrontOriginHttpClientTest {
};
}
/** A resolver that answers every lookup with {@code address}, counting the lookups. */
private static DnsResolver countingResolver(AtomicInteger resolutions, InetAddress address) {
return new DnsResolver() {
@Override
public InetAddress[] resolve(String host) {
resolutions.incrementAndGet();
return new InetAddress[] { address };
}
@Override
public String resolveCanonicalHostname(String host) {
return host;
}
};
}
private static SSLContext serverSslContext(
X509Certificate certificate, java.security.PrivateKey privateKey) throws Exception {
char[] password = "changeit".toCharArray();