From d0f802597fe7d8d348e8210decb69078e88b27d7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 09:45:05 +0900 Subject: [PATCH 1/3] =?UTF-8?q?test(web):=20graceful=20=EC=A2=85=EB=A3=8C?= =?UTF-8?q?=20=EC=8B=9C=ED=97=98=EC=9D=B4=20=EC=B2=98=EB=A6=AC=20=EC=A4=91?= =?UTF-8?q?=EC=9D=B8=20=EC=9A=94=EC=B2=AD=EC=9D=84=20=EB=B6=99=EC=9E=A1?= =?UTF-8?q?=EA=B3=A0=20=EB=81=9D=EA=B9=8C=EC=A7=80=20=EB=B0=9B=EB=8A=94?= =?UTF-8?q?=EC=A7=80=20=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `gracefulShutdownFinishesInFlightWork`(Tomcat·Jetty)는 처리 중인 요청 없이 종료를 시작하고, probe는 결과와 상관없이 `stop()`을 부르며, `finishedGracefully`는 아무도 읽지 않는다. 그래서 `server.shutdown`을 `immediate`로 바꿔도, probe가 기다리지 않고 바로 `stop()`을 불러도 두 서버 모두 통과한다. Boot는 graceful이 꺼지면 callback을 바로 `IMMEDIATE`로 부르므로, 결과가 있는지만 보던 `finishedGracefully`도 참이었다. 고친 시험은 testFixtures의 `InFlightFixtureController`로 GET 하나를 latch로 붙잡는다. 그 요청이 controller에 들어온 뒤 종료를 시작하고, `stop()` 전에 새 연결이 거절되는지 본 다음 요청을 풀어 준다. `GracefulShutdownProbe`는 이 종료 중 단계를 받고 서버가 알린 `GracefulShutdownResult`를 돌려준다. `finishedGracefully`는 `IDLE`일 때만 참이다. 세 약속(요청이 200과 본문 전체로 끝남, `IDLE`, 종료 중 거절)을 한 번에 비교해, 실패하면 깨진 약속을 모두 보여 준다. 종료 시험은 `@DirtiesContext`로 자기 context를 버린다. 그래서 「클래스의 마지막에 돈다」는 JUnit 순서에 더는 기대지 않는다. 공통 본문은 `WebLoadAndShutdownContract`로 옮겨 두 IT가 같은 것을 부른다. 붙잡는 요청은 raw socket으로 한 번만 보내고, `Content-Length`만큼 받았는지 본다. `HttpURLConnection`은 응답이 끊긴 GET을 새 연결로 다시 보낸다. 첫 변이 실행에서 끊긴 요청이 `ConnectException`으로 보였는데, 이 재전송 때문이었다. 서버가 아직 연결을 받는 동안 끊겼다면 재전송이 성공해 끊김을 가렸을 것이다. 버린 안: `took` 상한만 줄이기는 처리 중인 일이 없으면 무엇을 줄여도 graceful을 증명하지 못한다. sleep으로 요청을 붙잡기는 부하에 따라 흔들린다. 위험·한계: - 두 lane(`performanceTest`, `webJettyPerformanceTest`)은 `performanceCheck`(nightly)에만 있다. pr 단계는 이 시험을 컴파일과 정적 검사로만 본다. - 종료 중 거절은 새 TCP 연결로 본다(5초까지 20ms마다 다시 시도). 두 서버 모두 종료 스레드에서 accept를 닫기 때문이다. - `config/server.yml:9`의 기본값은 이 시험이 읽지 않는다. fixture 앱은 bootstrap 설정을 싣지 않는다. 그 기본값을 고정하는 시험은 여전히 없다. 검증: desktop에서 두 lane을 `--rerun --no-build-cache`(FROM-CACHE 0)로 돌렸다. | 트리 | 변이 | rc | 종료 시험 | |---|---|---|---| | 8a2656ae(main) | 없음 | 0 | 통과 | | 8a2656ae(main) | `server.shutdown=immediate` | 0 | 통과(RED) | | 8a2656ae(main) | probe가 기다리지 않고 `stop()` | 0 | 통과(RED) | | 이 커밋 | 없음, 3번 | 0 | 통과(Tomcat·Jetty) | | 이 커밋 | `server.shutdown=immediate` | 1 | 둘 다 실패: IMMEDIATE, 거절 없음 | | 이 커밋 | probe가 기다리지 않고 `stop()` | 1 | 둘 다 실패: 요청 끊김, REQUESTS_ACTIVE | 첫 GREEN 실행에는 `:adapter:inbound:web:spotlessCheck`도 넣었고 통과했다. `python3 -m unittest discover -s scripts/tests`는 노트북에서 339개 OK. Refs: REV-BE-0026 --- .../performance/JettyLoadAndShutdownIT.java | 28 ++--- .../performance/TomcatLoadAndShutdownIT.java | 28 ++--- .../performance/GracefulShutdownProbe.java | 51 +++++--- .../InFlightFixtureController.java | 73 ++++++++++++ .../WebLoadAndShutdownContract.java | 86 ++++++++++++++ .../testkit/performance/WebLoadFixture.java | 112 ++++++++++++++++++ 6 files changed, 324 insertions(+), 54 deletions(-) create mode 100644 src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java diff --git a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java index 5e310429..29adcd9a 100644 --- a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java +++ b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.inbound.web.testkit.performance; -import static org.assertj.core.api.Assertions.assertThat; - import dev.caskeleton.webtestkit.ContractFixtureApplication; -import java.time.Duration; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -11,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.web.server.servlet.context.ServletWebServerApplicationContext; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; /** @@ -22,7 +20,7 @@ import org.springframework.test.context.ActiveProfiles; * like the network. */ @SpringBootTest( - classes = ContractFixtureApplication.class, + classes = {ContractFixtureApplication.class, InFlightFixtureController.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "server.shutdown=graceful") @ActiveProfiles("web-contract") @@ -32,6 +30,8 @@ class JettyLoadAndShutdownIT extends WebLoadAndShutdownContract { @Autowired private ServletWebServerApplicationContext context; + @Autowired private InFlightFixtureController inFlight; + @Override protected WebLoadFixture fixture() { return new WebLoadFixture(port); @@ -44,20 +44,10 @@ class JettyLoadAndShutdownIT extends WebLoadAndShutdownContract { @Test @Tag("web-shutdown") - @DisplayName("graceful shutdown drains within the deployment's grace period") - void gracefulShutdownFinishesInFlightWork() { - // Last, and destructive: the context serves nothing afterwards. - WebLoadFixture fixture = fixture(); - assertThat(fixture.stillServing(loadPath())).isTrue(); - - GracefulShutdownProbe.Outcome outcome = - GracefulShutdownProbe.shutDown(webServer(), Duration.ofSeconds(10)); - - // Bounded on purpose. A shutdown that waits indefinitely for a connection to go idle is how a - // rolling deploy stalls with half the fleet drained — and it produces no error to alert on. - assertThat(outcome.took()).isLessThan(Duration.ofSeconds(15)); - assertThat(fixture.stillServing(loadPath())) - .as("the server accepted a new request after it was told to stop") - .isFalse(); + @DisplayName("graceful 종료는 처리 중인 요청을 끝까지 답한 뒤 유예 시간 안에 IDLE로 끝난다") + // Destructive: the server is stopped, so the context is thrown away for whatever runs next. + @DirtiesContext + void gracefulShutdownFinishesInFlightWork() throws InterruptedException { + assertShutdownFinishesInFlightWork(inFlight); } } diff --git a/src/adapter/inbound/web/src/performanceTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/TomcatLoadAndShutdownIT.java b/src/adapter/inbound/web/src/performanceTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/TomcatLoadAndShutdownIT.java index e1fef5b5..1d13d42a 100644 --- a/src/adapter/inbound/web/src/performanceTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/TomcatLoadAndShutdownIT.java +++ b/src/adapter/inbound/web/src/performanceTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/TomcatLoadAndShutdownIT.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.inbound.web.testkit.performance; -import static org.assertj.core.api.Assertions.assertThat; - import dev.caskeleton.webtestkit.ContractFixtureApplication; -import java.time.Duration; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -11,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.web.server.servlet.context.ServletWebServerApplicationContext; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; /** @@ -22,7 +20,7 @@ import org.springframework.test.context.ActiveProfiles; * like the network. */ @SpringBootTest( - classes = ContractFixtureApplication.class, + classes = {ContractFixtureApplication.class, InFlightFixtureController.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "server.shutdown=graceful") @ActiveProfiles("web-contract") @@ -32,6 +30,8 @@ class TomcatLoadAndShutdownIT extends WebLoadAndShutdownContract { @Autowired private ServletWebServerApplicationContext context; + @Autowired private InFlightFixtureController inFlight; + @Override protected WebLoadFixture fixture() { return new WebLoadFixture(port); @@ -44,20 +44,10 @@ class TomcatLoadAndShutdownIT extends WebLoadAndShutdownContract { @Test @Tag("web-shutdown") - @DisplayName("graceful shutdown drains within the deployment's grace period") - void gracefulShutdownFinishesInFlightWork() { - // Last, and destructive: the context serves nothing afterwards. - WebLoadFixture fixture = fixture(); - assertThat(fixture.stillServing(loadPath())).isTrue(); - - GracefulShutdownProbe.Outcome outcome = - GracefulShutdownProbe.shutDown(webServer(), Duration.ofSeconds(10)); - - // Bounded on purpose. A shutdown that waits indefinitely for a connection to go idle is how a - // rolling deploy stalls with half the fleet drained — and it produces no error to alert on. - assertThat(outcome.took()).isLessThan(Duration.ofSeconds(15)); - assertThat(fixture.stillServing(loadPath())) - .as("the server accepted a new request after it was told to stop") - .isFalse(); + @DisplayName("graceful 종료는 처리 중인 요청을 끝까지 답한 뒤 유예 시간 안에 IDLE로 끝난다") + // Destructive: the server is stopped, so the context is thrown away for whatever runs next. + @DirtiesContext + void gracefulShutdownFinishesInFlightWork() throws InterruptedException { + assertShutdownFinishesInFlightWork(inFlight); } } diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java index b5d327d9..c2d86ccf 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import org.springframework.boot.web.server.GracefulShutdownResult; import org.springframework.boot.web.server.WebServer; /** @@ -15,8 +16,8 @@ import org.springframework.boot.web.server.WebServer; * with no output; in a deployment it manifests as a rolling restart that stalls with half the fleet * drained and no error anywhere. * - *

The probe therefore measures rather than assumes, and reports "did not finish within the grace - * period" as a result the caller can assert on. + *

The probe therefore measures rather than assumes, and reports what the server said — or that + * it said nothing within the grace period — as a result the caller can assert on. */ public final class GracefulShutdownProbe { @@ -25,20 +26,36 @@ public final class GracefulShutdownProbe { /** * What a shutdown attempt did. * - * @param finishedGracefully whether the server reported completion within the grace period - * @param took how long it took, capped at the grace period + * @param result what the server reported when it finished, or {@code null} if it reported nothing + * within the grace period + * @param took how long it took, capped at the grace period plus the draining step */ - public record Outcome(boolean finishedGracefully, Duration took) {} + public record Outcome(GracefulShutdownResult result, Duration took) { + + /** + * Whether the server waited for its requests and then reported itself idle within the grace + * period. + * + *

{@link GracefulShutdownResult#IMMEDIATE} is not graceful: it is what a server without + * graceful shutdown reports at once, while its requests are still running. Counting it as a + * finish is how a check passes with {@code server.shutdown=immediate}. + */ + public boolean finishedGracefully() { + return result == GracefulShutdownResult.IDLE; + } + } /** - * Asks a server to stop and waits at most {@code grace}. + * Asks a server to stop, runs {@code whileDraining}, then waits at most {@code grace}. * * @param server the server to stop * @param grace the longest a rolling deploy is willing to wait for one instance + * @param whileDraining what the caller observes and finishes after shutdown began and before the + * server is stopped — a request still in flight is released here */ - public static Outcome shutDown(WebServer server, Duration grace) { + public static Outcome shutDown(WebServer server, Duration grace, Runnable whileDraining) { CountDownLatch finished = new CountDownLatch(1); - AtomicReference result = new AtomicReference<>(); + AtomicReference result = new AtomicReference<>(); long startedAt = System.nanoTime(); // The callback runs on the server's own shutdown thread. Calling stop() before it fires is @@ -49,18 +66,20 @@ public final class GracefulShutdownProbe { finished.countDown(); }); - boolean completed; + boolean completed = false; + long endedAt; try { + whileDraining.run(); completed = finished.await(grace.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); - completed = false; + } finally { + endedAt = System.nanoTime(); + // Stopped either way. A server that did not drain within the grace period is stopped anyway + // — that is what a deployment does, and leaving it running would strand the test JVM. A + // failing draining step still reaches here, so it cannot leave the server half shut. + server.stop(); } - Duration took = Duration.ofNanos(System.nanoTime() - startedAt); - - // Stopped either way. A server that did not drain within the grace period is stopped anyway — - // that is what a deployment does, and leaving it running would strand the test JVM. - server.stop(); - return new Outcome(completed && result.get() != null, took); + return new Outcome(completed ? result.get() : null, Duration.ofNanos(endedAt - startedAt)); } } diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java new file mode 100644 index 00000000..744fd043 --- /dev/null +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java @@ -0,0 +1,73 @@ +package dev.caskeleton.adapter.inbound.web.testkit.performance; + +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.springframework.boot.test.context.TestComponent; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * One request the shutdown case can hold in flight for as long as it needs. + * + *

Held by a latch, not by a sleep. A graceful shutdown is only observable while a request is + * still being served, and a sleep-length guess at "long enough" is either too short on a loaded + * runner (the request finishes before shutdown begins and nothing is in flight) or makes every run + * slower. The test decides when the work finishes: it lets the request reach this controller, + * starts the shutdown, and only then releases it. + * + *

Single use: one context serves one shutdown, so one request is held and released once. + */ +// @TestComponent for the same reason as the other fixture controllers: a plain @RestController in +// this package is scanned into the real application, publishing fixture routes in a deployment. +@RestController +@TestComponent +@RequestMapping("/api/v1/in-flight-fixtures") +public class InFlightFixtureController { + + /** The path that is held until {@link #release()}. */ + public static final String HELD_PATH = "/api/v1/in-flight-fixtures/held"; + + /** The body the held request answers with once released. */ + public static final String HELD_BODY = "the held request finished"; + + // Longer than any wait in the shutdown case, so the test's own bounds fail first and say why. + // It exists only so a test that never releases cannot pin a server thread for ever. + private static final Duration RELEASE_LIMIT = Duration.ofSeconds(60); + + private final CountDownLatch arrived = new CountDownLatch(1); + private final CountDownLatch released = new CountDownLatch(1); + + /** + * Answers only after {@link #release()}. + * + * @throws InterruptedException if the server interrupts the request thread while it is held + */ + @GetMapping(path = "/held", produces = MediaType.TEXT_PLAIN_VALUE) + public ResponseEntity held() throws InterruptedException { + arrived.countDown(); + if (!released.await(RELEASE_LIMIT.toMillis(), TimeUnit.MILLISECONDS)) { + return ResponseEntity.internalServerError().body("the held request was never released"); + } + return ResponseEntity.ok(HELD_BODY); + } + + /** + * Waits until the held request is inside this controller, so it is in flight on the server. + * + * @param within how long to wait + * @return whether it arrived in time + * @throws InterruptedException if the waiting thread is interrupted + */ + public boolean awaitArrival(Duration within) throws InterruptedException { + return arrived.await(within.toMillis(), TimeUnit.MILLISECONDS); + } + + /** Lets the held request finish. */ + public void release() { + released.countDown(); + } +} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java index 3e63e769..a6ee2cb9 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java @@ -6,6 +6,11 @@ import java.io.IOException; import java.net.Socket; import java.time.Duration; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -34,6 +39,18 @@ public abstract class WebLoadAndShutdownContract { /** The bound p99 must stay inside during the standard profile. */ protected static final Duration MAX_P99 = Duration.ofSeconds(2); + /** + * How long a rolling deploy waits for one instance to drain. + * + *

Bounded on purpose. A shutdown that waits indefinitely for a connection to go idle is how a + * rolling deploy stalls with half the fleet drained — and it produces no error to alert on. + */ + protected static final Duration SHUTDOWN_GRACE = Duration.ofSeconds(10); + + // How long the draining step waits to see a new connection refused. The servers stop accepting + // on their own shutdown thread, so this is a bounded condition wait, not a measurement. + private static final Duration REFUSAL_WITHIN = Duration.ofSeconds(5); + /** The lane's fixture. */ protected abstract WebLoadFixture fixture(); @@ -109,6 +126,75 @@ public abstract class WebLoadAndShutdownContract { assertThat(result.completed() + result.rejected()).isEqualTo(200); } + /** + * Shuts the lane's server down while one request is held inside a controller: stop accepting, + * finish what is in flight. + * + *

The request is held by {@code inFlight} until the shutdown has begun, so there is something + * in flight to finish — without it the case passes whether or not the server drains. Three + * promises are compared in one assertion, so a failure names every one it broke: the held request + * ends with 200 and its whole body, the server waits for it and reports itself idle within {@link + * #SHUTDOWN_GRACE} ({@link GracefulShutdownProbe.Outcome#finishedGracefully()}), and a new + * connection is refused while the server drains rather than only after it is stopped. + * + *

Destructive: the server is stopped. The calling test is annotated {@code @DirtiesContext}, + * so no other test is handed the stopped server, whatever order JUnit runs them in. + * + * @param inFlight the lane's held-request fixture + * @throws InterruptedException if the test thread is interrupted while waiting + */ + protected final void assertShutdownFinishesInFlightWork(InFlightFixtureController inFlight) + throws InterruptedException { + // given + WebLoadFixture fixture = fixture(); + CompletableFuture held = + fixture.send(InFlightFixtureController.HELD_PATH); + assertThat(inFlight.awaitArrival(SHUTDOWN_GRACE)) + .as("the held request never reached the controller, so nothing was in flight to finish") + .isTrue(); + AtomicBoolean refusedWhileDraining = new AtomicBoolean(); + + // when + GracefulShutdownProbe.Outcome outcome = + GracefulShutdownProbe.shutDown( + webServer(), + SHUTDOWN_GRACE, + () -> { + refusedWhileDraining.set(fixture.refusesNewConnectionsWithin(REFUSAL_WITHIN)); + inFlight.release(); + }); + + // then + assertThat( + new InFlightShutdown( + outcomeOf(held), outcome.finishedGracefully(), refusedWhileDraining.get())) + .as( + "graceful shutdown must let the request in flight finish, wait for it and report IDLE" + + " within %s, and refuse new connections before it stops (the server reported %s" + + " after %s)", + SHUTDOWN_GRACE, outcome.result(), outcome.took()) + .usingRecursiveComparison() + .isEqualTo(new InFlightShutdown("200 " + InFlightFixtureController.HELD_BODY, true, true)); + } + + // How the held request ended, as text the comparison prints: a cut-off connection and a request + // that never finished are both failures of the drain and must read differently from a 5xx. + private static String outcomeOf(CompletableFuture held) + throws InterruptedException { + try { + WebLoadFixture.Reply reply = held.get(SHUTDOWN_GRACE.toMillis(), TimeUnit.MILLISECONDS); + return reply.status() + " " + reply.body(); + } catch (ExecutionException cutOff) { + return "cut off: " + cutOff.getCause(); + } catch (TimeoutException unfinished) { + return "not finished within " + SHUTDOWN_GRACE; + } + } + + /** What one shutdown with a request in flight did, in the shape the case compares. */ + private record InFlightShutdown( + String heldRequest, boolean finishedGracefully, boolean refusedWhileDraining) {} + private static void closeQuietly(Socket socket) { try { socket.close(); diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java index af490591..1ee0f5d4 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java @@ -2,7 +2,9 @@ package dev.caskeleton.adapter.inbound.web.testkit.performance; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -10,6 +12,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -17,6 +20,7 @@ import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.LockSupport; /** * Generates load against a running container and observes what it costs. @@ -152,6 +156,65 @@ public final class WebLoadFixture implements AutoCloseable { } } + /** + * A response read to its end. + * + * @param status the status code + * @param body the whole body as text + */ + public record Reply(int status, String body) {} + + /** + * Sends one GET on its own thread and returns without waiting for the answer. + * + *

For a request that must still be in flight when something else happens to the server. The + * future completes with the reply read to its end, or exceptionally with the I/O failure — a + * response cut off mid-way is a failure, not a short body. + * + *

Sent once, on one new connection, and never resent. {@code HttpURLConnection} quietly sends + * a GET again on a fresh connection when the first response is cut off, so a request the server + * dropped could come back as the retry's success. + * + * @param path the path to request + */ + public CompletableFuture send(String path) { + CompletableFuture reply = new CompletableFuture<>(); + Thread.ofVirtual() + .name("web-load-fixture-send") + .start( + () -> { + try { + reply.complete(exchangeOnce(path)); + } catch (IOException | RuntimeException failed) { + reply.completeExceptionally(failed); + } + }); + return reply; + } + + /** + * Whether the container refuses a new connection at some point within {@code within}. + * + *

A new TCP connection rather than a request: the HTTP client keeps idle connections for + * reuse, and a request sent over one that was opened before the shutdown says nothing about + * whether the server still accepts. Polled because the servers stop accepting on their own + * shutdown thread, after the call that starts the shutdown has returned. + * + * @param within how long to keep trying + */ + public boolean refusesNewConnectionsWithin(Duration within) { + long deadline = System.nanoTime() + within.toNanos(); + do { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(host, port), 1_000); + } catch (IOException refused) { + return true; + } + LockSupport.parkNanos(Duration.ofMillis(20).toNanos()); + } while (System.nanoTime() < deadline); + return false; + } + private int get(String path) throws IOException { HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + path).toURL().openConnection(); @@ -171,6 +234,55 @@ public final class WebLoadFixture implements AutoCloseable { } } + private Reply exchangeOnce(String path) throws IOException { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(host, port), 5_000); + socket.setSoTimeout(20_000); + OutputStream out = socket.getOutputStream(); + out.write( + ("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII)); + out.flush(); + return parse(socket.getInputStream().readAllBytes()); + } + } + + // Whole means Content-Length bytes after the headers. With `Connection: close` a body also ends + // at end of stream, so a connection closed early would otherwise read as a short, whole body. + private static Reply parse(byte[] response) throws IOException { + // ISO-8859-1 maps each byte to one char, so string offsets are byte offsets. + String text = new String(response, StandardCharsets.ISO_8859_1); + int headEnd = text.indexOf("\r\n\r\n"); + if (headEnd < 0) { + throw new IOException( + "the response ended inside its headers after " + response.length + " bytes"); + } + String[] lines = text.substring(0, headEnd).split("\r\n", -1); + String[] statusLine = lines[0].split(" ", 3); + if (statusLine.length < 2) { + throw new IOException("not an HTTP status line: " + lines[0]); + } + long declared = -1; + for (String line : lines) { + int colon = line.indexOf(':'); + if (colon > 0 && line.substring(0, colon).trim().equalsIgnoreCase("Content-Length")) { + declared = Long.parseLong(line.substring(colon + 1).trim()); + } + } + int bodyStart = headEnd + 4; + int received = response.length - bodyStart; + if (declared < 0) { + throw new IOException("no Content-Length, so a cut-off body cannot be told from a whole one"); + } + if (received != declared) { + throw new IOException( + "the body was cut off after " + received + " of " + declared + " bytes"); + } + return new Reply( + Integer.parseInt(statusLine[1]), + new String(response, bodyStart, received, StandardCharsets.UTF_8)); + } + private static void drain(List> futures) { for (Future future : futures) { try { -- 2.54.0 From 90ce8262824f401c2d159d708d04e59412323785 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 11:18:16 +0900 Subject: [PATCH 2/3] =?UTF-8?q?test(web):=20=EC=A2=85=EB=A3=8C=20=EC=8B=9C?= =?UTF-8?q?=ED=97=98=EC=9D=B4=20connect=20=EC=8B=9C=EA=B0=84=20=EC=B4=88?= =?UTF-8?q?=EA=B3=BC=EB=A5=BC=20=EA=B1=B0=EC=A0=88=EB=A1=9C=20=EC=84=B8?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EA=B3=A0=20=EC=9D=B4=EB=A5=B8=20=EC=99=84?= =?UTF-8?q?=EB=A3=8C=EB=A5=BC=20=EC=9E=A1=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 리뷰에서 나온 두 거짓 통과와 틀린 주석 하나를 고친다. - `refusesNewConnectionsWithin`이 connect 시간 초과도 거절로 셌다. graceful 종료가 accept만 멈추고 listen 소켓을 열어 두면(예: Tomcat `bindOnInit=true`), 시험 연결이 backlog를 채운다. 그 뒤 connect가 1초 만에 시간 초과로 끝나 「종료 중 거절」이 참이 됐다. 이제 `ConnectException`만 거절로 세고, 시간 초과는 계속 다시 시도한다. - 서버가 붙잡힌 요청을 기다리지 않고 바로 `IDLE`을 알려도 시험이 구분하지 못했다. 그 뒤 `stop()`이 응답 쓰기와 경쟁해, 쓰기가 이기면 통과했다. probe가 종료 중 단계에 `Draining.reported()`를 넘긴다. 시험은 요청을 풀기 직전에 그 값이 거짓인지 본다 (`waitedForHeldRequest`). - 폴링 이유 주석을 고친다. Boot 4.0.9의 Tomcat과 Jetty는 `shutDownGracefully`가 돌아오기 전에 listen 소켓을 닫는다(javap로 확인함). - `InFlightFixtureController`의 `@TestComponent` 근거를 고친다. 조립 루트는 자기 패키지만 scan한다. 위험: 시험만 바꾼다. 두 lane은 nightly(`performanceCheck`)에서만 돈다. 검증: desktop에서 두 lane을 `--rerun --no-build-cache`(FROM-CACHE 0)로 돌렸다. 변이는 버릴 worktree에만 넣었다. | 트리 | 변이 | rc | 종료 시험 | |---|---|---|---| | 앞 커밋 d0f80259 | Tomcat `bindOnInit=true` | 0 | 통과(거짓 통과) | | 앞 커밋 d0f80259 | 서버가 바로 IDLE 보고 | 1 | Tomcat 실패(경쟁), Jetty 통과 | | 이 커밋 | 없음, 3번 | 0 | 통과(Tomcat·Jetty) | | 이 커밋 | Tomcat `bindOnInit=true` | 1 | Tomcat 실패: 거절 없음 | | 이 커밋 | 서버가 바로 IDLE 보고 | 1 | 둘 다 실패: 기다리지 않음 | | 이 커밋 | `server.shutdown=immediate` | 1 | 둘 다 실패 | | 이 커밋 | probe가 기다리지 않고 `stop()` | 1 | 둘 다 실패: 요청 끊김 | 첫 GREEN 실행에 `:adapter:inbound:web:spotlessCheck`, `testQualityCheck`, `auxiliaryStyleCheck`도 넣었고 통과했다. Refs: REV-BE-0026 --- .../performance/GracefulShutdownProbe.java | 17 ++++++++-- .../InFlightFixtureController.java | 4 +-- .../WebLoadAndShutdownContract.java | 33 ++++++++++++------- .../testkit/performance/WebLoadFixture.java | 13 ++++++-- 4 files changed, 49 insertions(+), 18 deletions(-) diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java index c2d86ccf..464ae934 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import org.springframework.boot.web.server.GracefulShutdownResult; import org.springframework.boot.web.server.WebServer; @@ -45,6 +46,17 @@ public final class GracefulShutdownProbe { } } + /** What the draining step can ask about the shutdown it runs inside. */ + @FunctionalInterface + public interface Draining { + + /** + * Whether the server has already reported its shutdown finished. Asked while a request is still + * held, {@code true} means the server did not wait for it. + */ + boolean reported(); + } + /** * Asks a server to stop, runs {@code whileDraining}, then waits at most {@code grace}. * @@ -53,7 +65,8 @@ public final class GracefulShutdownProbe { * @param whileDraining what the caller observes and finishes after shutdown began and before the * server is stopped — a request still in flight is released here */ - public static Outcome shutDown(WebServer server, Duration grace, Runnable whileDraining) { + public static Outcome shutDown( + WebServer server, Duration grace, Consumer whileDraining) { CountDownLatch finished = new CountDownLatch(1); AtomicReference result = new AtomicReference<>(); long startedAt = System.nanoTime(); @@ -69,7 +82,7 @@ public final class GracefulShutdownProbe { boolean completed = false; long endedAt; try { - whileDraining.run(); + whileDraining.accept(() -> finished.getCount() == 0); completed = finished.await(grace.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java index 744fd043..2e0dcdfc 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java @@ -21,8 +21,8 @@ import org.springframework.web.bind.annotation.RestController; * *

Single use: one context serves one shutdown, so one request is held and released once. */ -// @TestComponent for the same reason as the other fixture controllers: a plain @RestController in -// this package is scanned into the real application, publishing fixture routes in a deployment. +// @TestComponent like the other fixture controllers: a component scan that reaches this package +// skips it, so it is registered only where a test names it in @SpringBootTest(classes = ...). @RestController @TestComponent @RequestMapping("/api/v1/in-flight-fixtures") diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java index a6ee2cb9..884301df 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java @@ -47,8 +47,9 @@ public abstract class WebLoadAndShutdownContract { */ protected static final Duration SHUTDOWN_GRACE = Duration.ofSeconds(10); - // How long the draining step waits to see a new connection refused. The servers stop accepting - // on their own shutdown thread, so this is a bounded condition wait, not a measurement. + // How long the draining step keeps trying to see a new connection refused. Tomcat and Jetty close + // their listening socket before shutDownGracefully returns, so the first attempt is normally + // refused; the bound only keeps a server that never closes it from hanging the case. private static final Duration REFUSAL_WITHIN = Duration.ofSeconds(5); /** The lane's fixture. */ @@ -131,11 +132,12 @@ public abstract class WebLoadAndShutdownContract { * finish what is in flight. * *

The request is held by {@code inFlight} until the shutdown has begun, so there is something - * in flight to finish — without it the case passes whether or not the server drains. Three + * in flight to finish — without it the case passes whether or not the server drains. Four * promises are compared in one assertion, so a failure names every one it broke: the held request - * ends with 200 and its whole body, the server waits for it and reports itself idle within {@link - * #SHUTDOWN_GRACE} ({@link GracefulShutdownProbe.Outcome#finishedGracefully()}), and a new - * connection is refused while the server drains rather than only after it is stopped. + * ends with 200 and its whole body, the server has not reported its shutdown finished while that + * request is still held, it then reports itself idle within {@link #SHUTDOWN_GRACE} ({@link + * GracefulShutdownProbe.Outcome#finishedGracefully()}), and a new connection is refused while the + * server drains rather than only after it is stopped. * *

Destructive: the server is stopped. The calling test is annotated {@code @DirtiesContext}, * so no other test is handed the stopped server, whatever order JUnit runs them in. @@ -153,28 +155,34 @@ public abstract class WebLoadAndShutdownContract { .as("the held request never reached the controller, so nothing was in flight to finish") .isTrue(); AtomicBoolean refusedWhileDraining = new AtomicBoolean(); + AtomicBoolean reportedWhileHeld = new AtomicBoolean(); // when GracefulShutdownProbe.Outcome outcome = GracefulShutdownProbe.shutDown( webServer(), SHUTDOWN_GRACE, - () -> { + draining -> { refusedWhileDraining.set(fixture.refusesNewConnectionsWithin(REFUSAL_WITHIN)); + reportedWhileHeld.set(draining.reported()); inFlight.release(); }); // then assertThat( new InFlightShutdown( - outcomeOf(held), outcome.finishedGracefully(), refusedWhileDraining.get())) + outcomeOf(held), + !reportedWhileHeld.get(), + outcome.finishedGracefully(), + refusedWhileDraining.get())) .as( - "graceful shutdown must let the request in flight finish, wait for it and report IDLE" + "graceful shutdown must wait for the request in flight, let it finish, report IDLE" + " within %s, and refuse new connections before it stops (the server reported %s" + " after %s)", SHUTDOWN_GRACE, outcome.result(), outcome.took()) .usingRecursiveComparison() - .isEqualTo(new InFlightShutdown("200 " + InFlightFixtureController.HELD_BODY, true, true)); + .isEqualTo( + new InFlightShutdown("200 " + InFlightFixtureController.HELD_BODY, true, true, true)); } // How the held request ended, as text the comparison prints: a cut-off connection and a request @@ -193,7 +201,10 @@ public abstract class WebLoadAndShutdownContract { /** What one shutdown with a request in flight did, in the shape the case compares. */ private record InFlightShutdown( - String heldRequest, boolean finishedGracefully, boolean refusedWhileDraining) {} + String heldRequest, + boolean waitedForHeldRequest, + boolean finishedGracefully, + boolean refusedWhileDraining) {} private static void closeQuietly(Socket socket) { try { diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java index 1ee0f5d4..a4e00f07 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadFixture.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.testkit.performance; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Socket; @@ -197,8 +198,12 @@ public final class WebLoadFixture implements AutoCloseable { * *

A new TCP connection rather than a request: the HTTP client keeps idle connections for * reuse, and a request sent over one that was opened before the shutdown says nothing about - * whether the server still accepts. Polled because the servers stop accepting on their own - * shutdown thread, after the call that starts the shutdown has returned. + * whether the server still accepts. Retried until {@code within} so a server that closes its + * listening socket a little after the shutdown call returns is not reported as accepting. + * + *

Only a refused connection counts. A connect that times out means the socket is still + * listening but nobody accepts, as when a paused server's backlog fills up. That server still + * takes connections and drops them later; it does not refuse them. * * @param within how long to keep trying */ @@ -207,8 +212,10 @@ public final class WebLoadFixture implements AutoCloseable { do { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), 1_000); - } catch (IOException refused) { + } catch (ConnectException refused) { return true; + } catch (IOException notRefused) { + // Timed out or failed otherwise: the server did not refuse, so keep trying. } LockSupport.parkNanos(Duration.ofMillis(20).toNanos()); } while (System.nanoTime() < deadline); -- 2.54.0 From 2e470d6872f5b5bba11928553c4646d17da8d307 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 13:06:31 +0900 Subject: [PATCH 3/3] =?UTF-8?q?test(web):=20=EC=A2=85=EB=A3=8C=20=EC=8B=9C?= =?UTF-8?q?=ED=97=98=EC=9D=B4=20=EC=9A=94=EC=B2=AD=EC=9D=84=20=EB=B6=99?= =?UTF-8?q?=EC=9E=A1=EC=9D=80=20=EB=8F=99=EC=95=88=20=EB=8A=A6=EC=9D=80=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C=20=EB=B3=B4=EA=B3=A0=EB=8F=84=20=EC=9E=A1?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 확인 리뷰가 남긴 빈 곳 하나와 주석 넷을 고친다. - `Draining.reported()`는 요청을 풀기 직전에 「이미 보고했나」를 한 번 읽었다. 서버가 붙잡힌 요청을 기다리지 않고 다른 스레드에서 조금 늦게 `IDLE`을 보고하면, 그 한 번 읽기가 보고보다 앞서 통과했다. 이제 `reportedWithin(Duration)`이 latch를 그만큼 기다리고, 시험은 요청을 붙잡은 채 500ms(`HELD_WINDOW`)를 준다. 제대로 된 서버는 요청이 도는 동안 보고하지 않으므로, 느린 기계에서도 이 칸이 실패하지 않는다. 500ms는 고장 난 서버를 얼마나 늦게까지 잡는지만 정한다. - `InFlightFixtureController`: `@TestComponent`는 Boot의 `TypeExcludeFilter`를 쓰는 scan(`@SpringBootApplication`)만 건너뛴다. 보통 `@ComponentScan`은 건너뛰지 않으므로 시험이 이름으로 싣는다. - `GracefulShutdownProbe` 클래스 Javadoc의 Reactor Netty 이야기를 지운다. 이 leaf에는 WebFlux가 없다. 대신 Tomcat·Jetty가 처리 중 요청이 끝나야 보고하고 자체 시간 제한이 없다는 것을 적는다(Boot 4.0.9 `tomcat.GracefulShutdown`·`jetty.GracefulShutdown`을 javap로 확인: 50ms·100ms 간격으로 abort 전까지 돈다). - `WebLoadAndShutdownContract.SHUTDOWN_GRACE` Javadoc의 「연결이 idle이 되기를 기다림」을 「요청이 끝나기를 기다림」으로 고친다(같은 Netty 이야기에서 온 문장). - `JettyLoadAndShutdownIT` Javadoc의 「the the」. 위험: 시험만 바꾼다. 두 lane은 nightly(`performanceCheck`)에서만 돈다. Windows처럼 backlog가 차면 RST를 보내는 OS에서는 `bindOnInit` 변이가 다시 거짓 통과할 수 있다(이 repo는 Linux에서만 돈다). Jetty에는 「listen은 열고 accept만 멈춤」 변이를 만들지 않았다. 검증: desktop에서 두 lane을 `--rerun --no-build-cache`(FROM-CACHE 0)로 돌렸다. 변이는 버릴 worktree에만 넣었다. | 트리 | 변이 | rc | 종료 시험 | |---|---|---|---| | 앞 커밋 90ce8262 | 다른 스레드에서 5ms 뒤 IDLE, 3번 | 0 | 3번 다 통과(놓침) | | 2fa50f62 | 없음, 3번 | 0 | 통과(Tomcat·Jetty) | | 2fa50f62 | 다른 스레드에서 5ms 뒤 IDLE, 3번 | 1 | 3번 다 둘 다 실패: 기다리지 않음 | | 2fa50f62 | 서버가 바로 IDLE 보고 | 1 | 둘 다 실패: 기다리지 않음 | | 2fa50f62 | Tomcat `bindOnInit=true` | 1 | Tomcat 실패: 거절 없음 | | 2fa50f62 | `server.shutdown=immediate` | 1 | 둘 다 실패: IMMEDIATE | | 2fa50f62 | probe가 기다리지 않고 `stop()` | 1 | 둘 다 실패: 요청 끊김 | | 이 커밋 d5889a51 | 없음 | 0 | 통과(Tomcat·Jetty) | 2fa50f62는 이 커밋에서 `SHUTDOWN_GRACE` Javadoc 한 줄만 다르다. 이 커밋 트리와 2fa50f62의 첫 실행에 `:adapter:inbound:web:spotlessCheck`, `testQualityCheck`, `auxiliaryStyleCheck`도 넣었고 통과했다. Refs: REV-BE-0026 --- .../performance/JettyLoadAndShutdownIT.java | 2 +- .../performance/GracefulShutdownProbe.java | 32 +++++++++++++------ .../InFlightFixtureController.java | 5 +-- .../WebLoadAndShutdownContract.java | 9 ++++-- 4 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java index 29adcd9a..f3bc7541 100644 --- a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java +++ b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/JettyLoadAndShutdownIT.java @@ -12,7 +12,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; /** - * Load, abuse and graceful shutdown on the the second servlet container. + * Load, abuse and graceful shutdown on the second servlet container. * *

Shutdown is asserted per container rather than once, because it is implemented per container. * "Stop accepting, finish what is in flight" is a promise each server keeps in its own way, and the diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java index 464ae934..47a40390 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/GracefulShutdownProbe.java @@ -11,11 +11,11 @@ import org.springframework.boot.web.server.WebServer; /** * Drives a graceful shutdown and refuses to wait for ever. * - *

Bounded because unbounded is the actual failure mode. {@code shutDownGracefully} waits for - * in-flight work, and on Reactor Netty a connection that is open but idle counts — so calling it - * with a lingering keep-alive connection never returns. In a test that manifests as a hung build - * with no output; in a deployment it manifests as a rolling restart that stalls with half the fleet - * drained and no error anywhere. + *

Bounded because unbounded is the actual failure mode. Tomcat and Jetty report a graceful + * shutdown only once their active requests finish, and set no limit of their own: the limit is + * Spring's per-phase lifecycle timeout, which calling the server directly bypasses. So one request + * that never finishes means the server never reports, and in a test that manifests as a hung build + * with no output. * *

The probe therefore measures rather than assumes, and reports what the server said — or that * it said nothing within the grace period — as a result the caller can assert on. @@ -51,10 +51,15 @@ public final class GracefulShutdownProbe { public interface Draining { /** - * Whether the server has already reported its shutdown finished. Asked while a request is still - * held, {@code true} means the server did not wait for it. + * Waits up to {@code window} for the server to report its shutdown finished, and says whether + * it did. Asked while a request is still held, {@code true} means the server did not wait for + * it: a graceful server cannot finish while one of its requests is still running, so a correct + * server never makes this {@code true} however slow the machine. + * + * @param window how long to give a server that reports without waiting, possibly from another + * thread and a little late */ - boolean reported(); + boolean reportedWithin(Duration window); } /** @@ -82,7 +87,7 @@ public final class GracefulShutdownProbe { boolean completed = false; long endedAt; try { - whileDraining.accept(() -> finished.getCount() == 0); + whileDraining.accept(window -> awaitQuietly(finished, window)); completed = finished.await(grace.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); @@ -95,4 +100,13 @@ public final class GracefulShutdownProbe { } return new Outcome(completed ? result.get() : null, Duration.ofNanos(endedAt - startedAt)); } + + private static boolean awaitQuietly(CountDownLatch latch, Duration window) { + try { + return latch.await(window.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return latch.getCount() == 0; + } + } } diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java index 2e0dcdfc..97636071 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/InFlightFixtureController.java @@ -21,8 +21,9 @@ import org.springframework.web.bind.annotation.RestController; * *

Single use: one context serves one shutdown, so one request is held and released once. */ -// @TestComponent like the other fixture controllers: a component scan that reaches this package -// skips it, so it is registered only where a test names it in @SpringBootTest(classes = ...). +// @TestComponent like the other fixture controllers: in a test context, a scan that applies Boot's +// TypeExcludeFilter (as @SpringBootApplication does) skips it. A plain @ComponentScan does not, so +// a test registers it by name in @SpringBootTest(classes = ...). @RestController @TestComponent @RequestMapping("/api/v1/in-flight-fixtures") diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java index 884301df..6b288e12 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/performance/WebLoadAndShutdownContract.java @@ -42,7 +42,7 @@ public abstract class WebLoadAndShutdownContract { /** * How long a rolling deploy waits for one instance to drain. * - *

Bounded on purpose. A shutdown that waits indefinitely for a connection to go idle is how a + *

Bounded on purpose. A shutdown that waits indefinitely for its requests to finish is how a * rolling deploy stalls with half the fleet drained — and it produces no error to alert on. */ protected static final Duration SHUTDOWN_GRACE = Duration.ofSeconds(10); @@ -52,6 +52,11 @@ public abstract class WebLoadAndShutdownContract { // refused; the bound only keeps a server that never closes it from hanging the case. private static final Duration REFUSAL_WITHIN = Duration.ofSeconds(5); + // How long the request stays held after the refusal check, for a server that reports its + // shutdown finished without waiting for it. A correct server never reports while a request runs, + // so a slow machine cannot fail it here; the window only bounds how late a broken one is caught. + private static final Duration HELD_WINDOW = Duration.ofMillis(500); + /** The lane's fixture. */ protected abstract WebLoadFixture fixture(); @@ -164,7 +169,7 @@ public abstract class WebLoadAndShutdownContract { SHUTDOWN_GRACE, draining -> { refusedWhileDraining.set(fixture.refusesNewConnectionsWithin(REFUSAL_WITHIN)); - reportedWhileHeld.set(draining.reported()); + reportedWhileHeld.set(draining.reportedWithin(HELD_WINDOW)); inFlight.release(); }); -- 2.54.0