feat(elbv2): make backend HTTP connection reuse configurable (#7557)

Expose backend keep-alive and idle-pool timeout controls while retaining the existing defaults. Preserve target failures without replaying uncertain requests, and document target timeout hints and local transport limits.

Validate negative idle timeouts with a Floci-specific error before creating clients, and attempt every fixture cleanup step while preserving aggregated failures. Cover negative, zero and positive configuration values and real-listener connection behavior.

Closes #7524

test(elbv2): replace timer-dependent backend checks
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-06 19:11:17 -04:00
1 parent 2df2a1e149
commit 983fdecc79
10 files changed
+313

No files matched your search

@@ -611,6 +611,8 @@ See [Web Console](../ui/index.md) for running the console and swapping in a thir
| `FLOCI_SERVICES_ROUTE53_VPC_ASSOCIATION_CONTROL_PLANE_DELAY_MS` | `0` | Simulated processing window for Route 53 VPC association/auth mutations; positive values make documented overlap errors (`PriorRequestNotComplete` / `ConcurrentModification`) reproducible for retry tests |
| `FLOCI_SERVICES_ELBV2_ENABLED` | `true` | Enable the ELBv2 (ALB/NLB) service |
| `FLOCI_SERVICES_ELBV2_MOCK` | `false` | When `true`, load balancers are registered but no containers are spawned |
| `FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE` | `true` | Reuse backend HTTP/1.x connections for ordinary HTTP forwarding. Set to `false` for fresh connections per request; WebSocket and TCP transports are unaffected. See [backend connection reuse](../services/elb.md#backend-connection-reuse) |
| `FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE_TIMEOUT_SECONDS` | `60` | Default idle-pool timeout for backend HTTP/1.x connections, in non-negative seconds; `0` disables expiry. A target's advertised `Keep-Alive` timeout overrides it. Does not time out active responses or WebSockets |
| `FLOCI_SERVICES_AUTOSCALING_ENABLED` | `true` | Enable the Auto Scaling service |
| `FLOCI_SERVICES_CODEBUILD_ENABLED` | `true` | Enable the CodeBuild service |
| `FLOCI_SERVICES_CODEBUILD_DOCKER_NETWORK` | _(none)_ | Docker network for CodeBuild build containers |
+29
View File
@@ -309,6 +309,35 @@ aws elbv2 delete-target-group \
| Environment variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_ELBV2_ENABLED` | `true` | Enable or disable the ELBv2 service |
| `FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE` | `true` | Reuse backend connections for ordinary HTTP forwarding. Set to `false` to open a fresh connection per request. |
| `FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE_TIMEOUT_SECONDS` | `60` | Default timeout for unused backend HTTP/1.x connections in the pool, in seconds. Non-negative; `0` disables expiry. A target's `Keep-Alive: timeout=...` overrides this value. |
### Backend connection reuse
Ordinary HTTP forwarding reuses backend HTTP/1.x connections by default. For local
targets that cannot reliably serve multiple requests on one connection, set
`FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE=false` before starting Floci. This applies
to ordinary requests to HTTP and HTTPS targets, independently of client-to-listener
keep-alive. WebSocket upgrades keep their dedicated connection, and TCP forwarding
is unaffected.
To expire unused pooled connections sooner, set
`FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE_TIMEOUT_SECONDS` below the target's idle
deadline. The default remains 60 seconds, matching the existing Vert.x client
default. This is the [Vert.x HTTP/1.x keep-alive timeout](https://vertx.io/docs/4.5.35/apidocs/io/vertx/core/http/HttpClientOptions.html#setKeepAliveTimeout-int-),
not a request timeout or a maximum connection age: it does not interrupt an active
response. Vert.x honors a target's advertised `Keep-Alive` timeout in preference to
this default. Choose consistent target settings, or disable reuse if a fresh
connection is required for every request. The pool's periodic cleanup can delay
physical closure of an unused connection. This setting is unused when reuse is off
and is separate from the ALB `idle_timeout.timeout_seconds` attribute.
These are local transport controls, not AWS load-balancer attributes. Disabling
reuse is a mitigation, not evidence of an AWS compatibility defect. A target that
closes its connection while a request is outstanding can still produce a 502,
as described in [AWS's ALB troubleshooting guide](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html#http-502-issues).
Floci does not retry forwarded requests when the target's outcome is uncertain,
including a POST whose body the target consumed before closing.
## Listener Ports
@@ -3700,6 +3700,14 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean mock();
/** Reuse backend HTTP/1.x connections between ordinary forwarded requests. */
@WithDefault("true")
boolean backendKeepAlive();
/** Default idle-pool timeout in seconds; zero disables expiry. Target Keep-Alive may override it. */
@WithDefault("60")
int backendKeepAliveTimeoutSeconds();
}
interface EksServiceConfig {
@@ -237,6 +237,11 @@ public class ElbV2DataPlane {
@PostConstruct
void init() {
int keepAliveTimeoutSeconds = config.services().elbv2().backendKeepAliveTimeoutSeconds();
if (keepAliveTimeoutSeconds < 0) {
throw new IllegalArgumentException(
"floci.services.elbv2.backend-keep-alive-timeout-seconds must be non-negative");
}
proxyClient = vertx.createHttpClient(new HttpClientOptions()
.setTrustAll(true)
.setVerifyHost(false)
@@ -245,6 +250,7 @@ public class ElbV2DataPlane {
.setSslHandshakeTimeout(10)
.setSslHandshakeTimeoutUnit(TimeUnit.SECONDS)
.setKeepAlive(true)
.setKeepAliveTimeout(keepAliveTimeoutSeconds)
.setMaxHeaderSize(MAX_RESPONSE_HEADER_SIZE));
tcpClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(5000)
.setTcpKeepAlive(true));
@@ -1470,6 +1476,9 @@ public class ElbV2DataPlane {
if (hostHeader != null) {
clientReq.putHeader("Host", hostHeader);
}
if (!config.services().elbv2().backendKeepAlive()) {
clientReq.putHeader("Connection", "close");
}
AtomicBoolean responseStarted = new AtomicBoolean();
AtomicBoolean requestFailed = new AtomicBoolean();
clientReq.response().onSuccess(resp -> {
+2
View File
@@ -888,6 +888,8 @@ floci:
elbv2:
enabled: true
mock: false
backend-keep-alive: true
backend-keep-alive-timeout-seconds: 60
codebuild:
enabled: true
# docker-network: floci-network
@@ -0,0 +1,95 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.testutil.FreePorts;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.net.Socket;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.floci.aws.testing.AlbFixtures.createListener;
import static io.floci.aws.testing.AlbFixtures.createLoadBalancer;
import static io.floci.aws.testing.AlbFixtures.createTargetGroup;
import static io.floci.aws.testing.AlbFixtures.deleteListener;
import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer;
import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup;
import static io.floci.aws.testing.AlbFixtures.registerTarget;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
abstract class ElbV2BackendConnectionTestSupport {
@Inject
Vertx vertx;
int listenerPort;
HttpServer backend;
private String loadBalancerArn;
private String targetGroupArn;
private String listenerArn;
void startBackend(Handler<HttpServerRequest> handler) throws Exception {
backend = vertx.createHttpServer().requestHandler(handler)
.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
listenerPort = FreePorts.anyInterfacePort();
loadBalancerArn = createLoadBalancer("backend-connection-lb");
targetGroupArn = createTargetGroup("backend-connection-tg", "ip", backend.actualPort());
registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort());
listenerArn = createListener(loadBalancerArn, targetGroupArn, listenerPort);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
try (Socket socket = new Socket("127.0.0.1", listenerPort)) {
// Probe only the listener socket, without sending a request to the target.
socket.setSoTimeout(1000);
}
});
}
@Test
void returnsBadGatewayWhenTargetClosesOnItsFirstRequest() throws Exception {
AtomicInteger requests = new AtomicInteger();
startBackend(request -> {
requests.incrementAndGet();
request.connection().close();
});
assertEquals(502, given().baseUri("http://127.0.0.1").port(listenerPort).get("/close").statusCode());
assertEquals(1, requests.get());
}
@Test
void neverReplaysPostAfterTheTargetConsumesItsBodyAndCloses() throws Exception {
List<String> consumed = new CopyOnWriteArrayList<>();
startBackend(request -> request.bodyHandler(body -> {
consumed.add(body.toString());
request.connection().close();
}));
assertEquals(502, given().baseUri("http://127.0.0.1").port(listenerPort)
.body("charge-once").post("/charge").statusCode());
assertEquals(List.of("charge-once"), consumed);
}
@AfterEach
void stopBackend() {
assertAll("Clean up every backend connection fixture resource after any failure",
() -> deleteListener(listenerArn),
() -> deleteLoadBalancer(loadBalancerArn),
() -> deleteTargetGroup(targetGroupArn),
() -> {
if (backend != null) {
backend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
});
}
}
@@ -0,0 +1,38 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.testing.RealElbV2DataPlaneProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
@TestProfile(RealElbV2DataPlaneProfile.class)
class ElbV2BackendKeepAliveIntegrationTest extends ElbV2BackendConnectionTestSupport {
@Test
void reusesBackendConnectionsByDefaultAndRetainsTargetCloseErrors() throws Exception {
AtomicInteger requests = new AtomicInteger();
startBackend(request -> {
if (requests.incrementAndGet() == 3) {
request.connection().close();
} else {
request.response().putHeader("X-Backend-Connection",
Integer.toString(request.remoteAddress().port())).end("ok");
}
});
Response first = given().baseUri("http://127.0.0.1").port(listenerPort).get("/first");
assertEquals(200, first.statusCode());
Response second = given().baseUri("http://127.0.0.1").port(listenerPort).get("/second");
assertEquals(200, second.statusCode());
assertEquals(first.header("X-Backend-Connection"), second.header("X-Backend-Connection"));
assertEquals(502, given().baseUri("http://127.0.0.1").port(listenerPort).get("/third").statusCode());
assertEquals(3, requests.get());
}
}
@@ -0,0 +1,76 @@
package io.floci.aws.services.elbv2;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpConnection;
import io.vertx.core.http.WebSocket;
import io.vertx.core.http.WebSocketConnectOptions;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.floci.aws.testing.AlbFixtures.exchange;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@QuarkusTest
@TestProfile(ElbV2BackendNoKeepAliveIntegrationTest.NoKeepAliveProfile.class)
class ElbV2BackendNoKeepAliveIntegrationTest extends ElbV2BackendConnectionTestSupport {
public static class NoKeepAliveProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.elbv2.mock", "false",
"floci.services.elbv2.backend-keep-alive", "false");
}
}
@Test
void disablingKeepAliveUsesFreshConnectionsForSequentialRequests() throws Exception {
Map<HttpConnection, AtomicInteger> requests = new ConcurrentHashMap<>();
startBackend(request -> {
int count = requests.computeIfAbsent(request.connection(), ignored -> new AtomicInteger())
.incrementAndGet();
if (count > 1) {
request.connection().close();
} else {
request.response().putHeader("X-Backend-Connection",
Integer.toString(request.remoteAddress().port())).end("ok");
}
});
Response first = given().baseUri("http://127.0.0.1").port(listenerPort).get("/first");
assertEquals(200, first.statusCode());
Response second = given().baseUri("http://127.0.0.1").port(listenerPort).get("/second");
assertEquals(200, second.statusCode());
assertEquals("ok", second.asString());
assertNotEquals(first.header("X-Backend-Connection"), second.header("X-Backend-Connection"));
assertEquals(2, requests.size());
assertEquals(2, requests.values().stream().mapToInt(AtomicInteger::get).sum());
}
@Test
void disablingKeepAlivePreservesWebSocketUpgrades() throws Exception {
startBackend(request -> request.toWebSocket().onSuccess(socket ->
socket.textMessageHandler(socket::writeTextMessage)));
HttpClient client = vertx.createHttpClient();
try {
WebSocket socket = client.webSocket(new WebSocketConnectOptions()
.setHost("127.0.0.1").setPort(listenerPort).setURI("/socket"))
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals("first", exchange(socket, "first"));
assertEquals("second", exchange(socket, "second"));
socket.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
} finally {
client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
}
}
@@ -0,0 +1,52 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.config.EmulatorConfig;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClientOptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class ElbV2DataPlaneConfigTest {
@ParameterizedTest
@ValueSource(ints = {-1, Integer.MIN_VALUE})
void negativeBackendKeepAliveTimeoutNamesTheInvalidSetting(int seconds) {
ElbV2DataPlane plane = plane(seconds);
plane.vertx = mock(Vertx.class);
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, plane::init);
assertEquals("floci.services.elbv2.backend-keep-alive-timeout-seconds must be non-negative",
error.getMessage());
verifyNoInteractions(plane.vertx);
}
@ParameterizedTest
@ValueSource(ints = {0, 1, 60})
void backendClientUsesConfiguredKeepAliveTimeout(int seconds) {
ElbV2DataPlane plane = plane(seconds);
plane.vertx = mock(Vertx.class);
plane.init();
ArgumentCaptor<HttpClientOptions> options = ArgumentCaptor.forClass(HttpClientOptions.class);
verify(plane.vertx).createHttpClient(options.capture());
assertEquals(seconds, options.getValue().getKeepAliveTimeout());
}
private static ElbV2DataPlane plane(int seconds) {
ElbV2DataPlane plane = new ElbV2DataPlane();
plane.config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(plane.config.services().elbv2().backendKeepAliveTimeoutSeconds()).thenReturn(seconds);
return plane;
}
}
+2
View File
@@ -400,6 +400,8 @@ floci:
elbv2:
enabled: true
mock: true
backend-keep-alive: true
backend-keep-alive-timeout-seconds: 60
codebuild:
enabled: true
# docker-network: floci-network