test(web): graceful 종료 시험이 처리 중인 요청을 붙잡고 끝까지 받는지 본다 #103
+10
-20
@@ -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,10 +8,11 @@ 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;
|
||||
|
||||
/**
|
||||
* Load, abuse and graceful shutdown on the the second servlet container.
|
||||
* Load, abuse and graceful shutdown on the second servlet container.
|
||||
*
|
||||
* <p>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
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+9
-19
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+66
-20
@@ -4,19 +4,21 @@ 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;
|
||||
|
||||
/**
|
||||
* Drives a graceful shutdown and refuses to wait for ever.
|
||||
*
|
||||
* <p>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.
|
||||
* <p>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.
|
||||
*
|
||||
* <p>The probe therefore measures rather than assumes, and reports "did not finish within the grace
|
||||
* period" as a result the caller can assert on.
|
||||
* <p>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 +27,53 @@ 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.
|
||||
*
|
||||
* <p>{@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;
|
||||
}
|
||||
}
|
||||
|
||||
/** What the draining step can ask about the shutdown it runs inside. */
|
||||
@FunctionalInterface
|
||||
public interface Draining {
|
||||
|
||||
/**
|
||||
* 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 reportedWithin(Duration window);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, Consumer<Draining> whileDraining) {
|
||||
CountDownLatch finished = new CountDownLatch(1);
|
||||
AtomicReference<Object> result = new AtomicReference<>();
|
||||
AtomicReference<GracefulShutdownResult> 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 +84,29 @@ public final class GracefulShutdownProbe {
|
||||
finished.countDown();
|
||||
});
|
||||
|
||||
boolean completed;
|
||||
boolean completed = false;
|
||||
long endedAt;
|
||||
try {
|
||||
whileDraining.accept(window -> awaitQuietly(finished, window));
|
||||
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);
|
||||
return new Outcome(completed ? result.get() : null, Duration.ofNanos(endedAt - 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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>Single use: one context serves one shutdown, so one request is held and released once.
|
||||
*/
|
||||
// @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")
|
||||
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<String> 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();
|
||||
}
|
||||
}
|
||||
+102
@@ -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,24 @@ 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.
|
||||
*
|
||||
* <p>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);
|
||||
|
||||
// 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);
|
||||
|
||||
// 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();
|
||||
|
||||
@@ -109,6 +132,85 @@ 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.
|
||||
*
|
||||
* <p>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. 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 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.
|
||||
*
|
||||
* <p>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<WebLoadFixture.Reply> 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();
|
||||
AtomicBoolean reportedWhileHeld = new AtomicBoolean();
|
||||
|
||||
// when
|
||||
GracefulShutdownProbe.Outcome outcome =
|
||||
GracefulShutdownProbe.shutDown(
|
||||
webServer(),
|
||||
SHUTDOWN_GRACE,
|
||||
draining -> {
|
||||
refusedWhileDraining.set(fixture.refusesNewConnectionsWithin(REFUSAL_WITHIN));
|
||||
reportedWhileHeld.set(draining.reportedWithin(HELD_WINDOW));
|
||||
inFlight.release();
|
||||
});
|
||||
|
||||
// then
|
||||
assertThat(
|
||||
new InFlightShutdown(
|
||||
outcomeOf(held),
|
||||
!reportedWhileHeld.get(),
|
||||
outcome.finishedGracefully(),
|
||||
refusedWhileDraining.get()))
|
||||
.as(
|
||||
"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, 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<WebLoadFixture.Reply> 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 waitedForHeldRequest,
|
||||
boolean finishedGracefully,
|
||||
boolean refusedWhileDraining) {}
|
||||
|
||||
private static void closeQuietly(Socket socket) {
|
||||
try {
|
||||
socket.close();
|
||||
|
||||
+119
@@ -2,7 +2,10 @@ 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;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -10,6 +13,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 +21,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 +157,71 @@ 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<Reply> send(String path) {
|
||||
CompletableFuture<Reply> 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}.
|
||||
*
|
||||
* <p>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. Retried until {@code within} so a server that closes its
|
||||
* listening socket a little after the shutdown call returns is not reported as accepting.
|
||||
*
|
||||
* <p>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
|
||||
*/
|
||||
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 (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);
|
||||
return false;
|
||||
}
|
||||
|
||||
private int get(String path) throws IOException {
|
||||
HttpURLConnection connection =
|
||||
(HttpURLConnection) URI.create(baseUrl + path).toURL().openConnection();
|
||||
@@ -171,6 +241,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<Future<?>> futures) {
|
||||
for (Future<?> future : futures) {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user