From 983fdecc79f4c341c33c1bda11f2bef3b7bcc8af Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:11:17 +0000 Subject: [PATCH] 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 --- docs/configuration/environment-variables.md | 2 + docs/services/elb.md | 29 ++++++ .../io/floci/aws/config/EmulatorConfig.java | 8 ++ .../aws/services/elbv2/ElbV2DataPlane.java | 9 ++ src/main/resources/application.yml | 2 + .../ElbV2BackendConnectionTestSupport.java | 95 +++++++++++++++++++ .../ElbV2BackendKeepAliveIntegrationTest.java | 38 ++++++++ ...lbV2BackendNoKeepAliveIntegrationTest.java | 76 +++++++++++++++ .../elbv2/ElbV2DataPlaneConfigTest.java | 52 ++++++++++ src/test/resources/application.yml | 2 + 10 files changed, 313 insertions(+) create mode 100644 src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java create mode 100644 src/test/java/io/floci/aws/services/elbv2/ElbV2BackendKeepAliveIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/elbv2/ElbV2BackendNoKeepAliveIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/elbv2/ElbV2DataPlaneConfigTest.java diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 3d7a5d7fcb..873d42077f 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -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 | diff --git a/docs/services/elb.md b/docs/services/elb.md index 5398be6c0a..265e3e906f 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -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 diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index b3fe4c1f79..a3982dfc80 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -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 { diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java index be0ba3b21e..c650fd2782 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java @@ -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 -> { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 009ec60f7f..0c2db84297 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -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 diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java new file mode 100644 index 0000000000..ce60de553b --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendConnectionTestSupport.java @@ -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 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 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); + } + }); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendKeepAliveIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendKeepAliveIntegrationTest.java new file mode 100644 index 0000000000..86cbe02116 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendKeepAliveIntegrationTest.java @@ -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()); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendNoKeepAliveIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendNoKeepAliveIntegrationTest.java new file mode 100644 index 0000000000..ab63a7c6d2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2BackendNoKeepAliveIntegrationTest.java @@ -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 getConfigOverrides() { + return Map.of("floci.services.elbv2.mock", "false", + "floci.services.elbv2.backend-keep-alive", "false"); + } + } + + @Test + void disablingKeepAliveUsesFreshConnectionsForSequentialRequests() throws Exception { + Map 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); + } + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2DataPlaneConfigTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2DataPlaneConfigTest.java new file mode 100644 index 0000000000..4f93867c9c --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2DataPlaneConfigTest.java @@ -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 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; + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 6056d1f491..cad28ec314 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -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