diff --git a/docs/services/elb.md b/docs/services/elb.md index 762426dd0e..9f953bc733 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -109,6 +109,10 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on ingress and backend egress rules. These listeners cannot yet reproduce NAT allowlisting failures. - TCP listeners relay bytes bidirectionally without parsing HTTP or terminating TLS. TLS passthrough requires a TCP listener, with certificates configured at the target, not at the listener. Targets are selected per connection using round-robin among healthy targets, falling back to registered targets when none are healthy. The default TCP idle timeout is 350 seconds, configurable via the `tcp.idle_timeout.seconds` listener attribute (60 to 6000 seconds). - TCP listeners require a dedicated local port. Floci still shares its address across load balancers, so a second listener on an in-use TCP port registers successfully and logs a warning, but serves no traffic until the listener holding the port is deleted or moved, and ports reserved by Floci remain unavailable. Address isolation and TLS-terminating NLB listeners are not provided by the TCP proxy. +- An asynchronous socket-bind failure retains the admitted listeners and retries while they + remain configured. Retry delays grow from 100 milliseconds to five seconds; a successful + bind resets the delay. Deleting the last listener or stopping Floci cancels its retry. + An external process holding the port must still release it before Floci can serve traffic. - HTTPS listeners terminate TLS using the configured ACM or IAM server certificates, with SNI certificate selection. When several load balancers share one local HTTPS port, clients must send SNI to identify the certificate they need; a connection without SNI cannot identify a particular load balancer before the TLS handshake. - ACM certificates must be issued before attaching them. Reimporting an attached ACM certificate refreshes subsequent full TLS handshakes; existing connections keep their negotiated certificate. Reload does not invalidate TLS session caches: a resumed session can retain its previously authenticated certificate after replacement or removal until the session expires or is invalidated. ACM deletion and revocation are refused while a listener still references the certificate. - Certificate replacement keeps the previous key material available to new handshakes while the replacement loads. A failed reload leaves the previous certificate active. diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java index a3a428ab72..013c1f11e0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java @@ -110,6 +110,8 @@ public class ElbV2DataPlane { static final int TCP_IDLE_TIMEOUT_SECONDS = 350; static final int MIN_TCP_IDLE_TIMEOUT_SECONDS = 60; static final int MAX_TCP_IDLE_TIMEOUT_SECONDS = 6000; + private static final long INITIAL_BIND_RETRY_MILLIS = 100; + private static final long MAX_BIND_RETRY_MILLIS = 5000; @Inject Vertx vertx; @@ -147,6 +149,8 @@ public class ElbV2DataPlane { private int depth; private int closing; private long generation; + private long bindRetryTimer = -1; + private long bindRetryDelay = INITIAL_BIND_RETRY_MILLIS; private ReloadingKeyManager tlsKeyManager; private volatile RoutingView routing = new RoutingView(Map.of(), Map.of()); } @@ -200,6 +204,7 @@ public class ElbV2DataPlane { private void retirePortState(int port, PortState state) { if (state.depth == 0 && state.closing == 0 && !servers.containsKey(port) && !tcpServers.containsKey(port) && !listenersByHostAndPort.containsKey(port)) { + cancelBindRetry(state); portStates.remove(port, state); } } @@ -248,6 +253,7 @@ public class ElbV2DataPlane { stopping = true; for (Map.Entry entry : portStates.entrySet()) { synchronized (entry.getValue()) { + cancelBindRetry(entry.getValue()); HttpServer server = servers.remove(entry.getKey()); if (server != null) { server.close(); @@ -552,7 +558,8 @@ public class ElbV2DataPlane { private void ensurePortServer(int port) { PortState state = portStates.get(port); - if (!stopping && state != null && state.closing == 0 && !servers.containsKey(port) && !tcpServers.containsKey(port) + if (!stopping && state != null && state.closing == 0 && state.bindRetryTimer == -1 + && !servers.containsKey(port) && !tcpServers.containsKey(port) && listenersByHostAndPort.containsKey(port)) { startPortServer(port, state); } @@ -592,11 +599,10 @@ public class ElbV2DataPlane { try { server.requestHandler(req -> handleRequest(req, port)); server.listen() - .onSuccess(s -> LOG.infov("ELBv2 {0} listener port started on {1}", - secure ? "HTTPS" : "HTTP", String.valueOf(port))) + .onSuccess(s -> portStarted(port, state, generation, secure ? "HTTPS" : "HTTP")) .onFailure(err -> onCurrentPort(port, state, () -> { if (state.generation == generation && servers.remove(port, server)) { - clearPortBindings(port); + scheduleBindRetry(port, state); closeOwnedServer(port, state, server); } else { server.close(); @@ -624,10 +630,10 @@ public class ElbV2DataPlane { tcpServers.put(port, server); try { server.connectHandler(socket -> handleTcpConnection(socket, state)); - server.listen().onSuccess(ignored -> LOG.infov("ELBv2 TCP listener port started on {0}", String.valueOf(port))) + server.listen().onSuccess(ignored -> portStarted(port, state, generation, "TCP")) .onFailure(err -> onCurrentPort(port, state, () -> { if (state.generation == generation && tcpServers.remove(port, server)) { - clearPortBindings(port); + scheduleBindRetry(port, state); closeOwnedServer(port, state, server::close); } else { server.close(); @@ -648,6 +654,37 @@ public class ElbV2DataPlane { } } + private void portStarted(int port, PortState state, long generation, String protocol) { + onCurrentPort(port, state, () -> { + if (state.generation == generation) { + state.bindRetryDelay = INITIAL_BIND_RETRY_MILLIS; + LOG.infov("ELBv2 {0} listener port started on {1}", protocol, String.valueOf(port)); + } + }); + } + + private void scheduleBindRetry(int port, PortState state) { + if (state.bindRetryTimer != -1) { + return; + } + long delay = state.bindRetryDelay; + state.bindRetryDelay = Math.min(delay * 2, MAX_BIND_RETRY_MILLIS); + state.bindRetryTimer = vertx.setTimer(delay, timer -> onCurrentPort(port, state, () -> { + if (state.bindRetryTimer == timer) { + state.bindRetryTimer = -1; + ensurePortServer(port); + } + })); + } + + private void cancelBindRetry(PortState state) { + if (state.bindRetryTimer != -1) { + long timer = state.bindRetryTimer; + state.bindRetryTimer = -1; + vertx.cancelTimer(timer); + } + } + private void handleTcpConnection(NetSocket socket, PortState state) { socket.pause(); socket.exceptionHandler(err -> socket.close()); @@ -701,6 +738,10 @@ public class ElbV2DataPlane { if (listenersByHost != null) { listenersByHostAndPort.remove(port, listenersByHost); } + PortState state = portStates.get(port); + if (state != null) { + cancelBindRetry(state); + } restartPortServer(port); } @@ -881,7 +922,10 @@ public class ElbV2DataPlane { state.closing--; throw failure; } - closed.onComplete(ignored -> onCurrentPort(port, state, () -> { + closed.onComplete(result -> onCurrentPort(port, state, () -> { + if (result.failed()) { + LOG.warnv(result.cause(), "ELBv2 server close failed on port {0}", String.valueOf(port)); + } state.closing--; if (state.generation == generation) { ensurePortServer(port); diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.java index 32a5318a9d..55cd71e0b1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.java @@ -38,6 +38,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime; @@ -52,6 +53,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -444,7 +446,7 @@ class ElbV2ListenerOwnershipTest { } @Test - void failedClosePermitsABoundedBindAttemptAndIdenticalPublicationCanRetry() { + void failedCloseRetainsListenersUntilBackgroundBindRetry() { Fixture fixture = new Fixture(new Registry()); Promise close = Promise.promise(); Listener first = listener("first", 8443, false); @@ -462,7 +464,7 @@ class ElbV2ListenerOwnershipTest { close.fail(new IllegalStateException("controlled close failure")); assertEquals(2, fixture.creations(8443)); assertEquals(1, fixture.closes(8443), "failed replacement must be closed"); - publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second"))); + fixture.runNextTimer(); assertEquals(3, fixture.creations(8443)); fixture.serves(8443, "second"); fixture.serves(9443, "unrelated"); @@ -472,6 +474,95 @@ class ElbV2ListenerOwnershipTest { } } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bindRetryWaitsForBothTimerAndFailedServerClose(boolean timerFirst) { + Registry registry = new Registry(); + Fixture fixture = new Fixture(registry); + Promise close = Promise.promise(); + Listener listener = listener("delayed-close", 8443, false); + try { + fixture.nextClose = close; + fixture.failNextListenPort = 8443; + publishRuntime(fixture.plane, listener, REGION, null, List.of(rule("recovered"))); + assertEquals(1, fixture.creations(8443)); + assertEquals(1, fixture.closes(8443)); + assertTrue(registry.containsKey(listener.getListenerArn())); + if (timerFirst) { + fixture.runNextTimer(); + assertEquals(1, fixture.creations(8443), "timer must not bind while close is pending"); + close.complete(); + } else { + close.complete(); + assertEquals(1, fixture.creations(8443), "close must not bypass the retry timer"); + fixture.runNextTimer(); + } + assertEquals(2, fixture.creations(8443)); + assertTrue(fixture.timers.isEmpty()); + fixture.serves(8443, "recovered"); + } finally { + close.tryComplete(); + fixture.plane.shutdown(); + } + } + + @Test + void repeatedBindFailuresBackOffWithoutDuplicatingPublication() { + Fixture fixture = new Fixture(new Registry()); + Listener listener = listener("retry", 8443, false); + try { + fixture.failNextListenPort = 8443; + publishRuntime(fixture.plane, listener, REGION, null, List.of(rule("retry"))); + for (long delay : List.of(100L, 200L, 400L, 800L, 1600L, 3200L, 5000L, 5000L)) { + int creations = fixture.creations(8443); + publishRuntime(fixture.plane, listener, REGION, listener.getPort(), List.of(rule("retry"))); + assertEquals(creations, fixture.creations(8443), "publication must not bypass an outstanding retry"); + assertEquals(1, fixture.timers.size()); + assertEquals(delay, fixture.nextTimerDelay); + fixture.failNextListenPort = 8443; + fixture.runNextTimer(); + } + fixture.runNextTimer(); + fixture.serves(8443, "retry"); + assertTrue(fixture.timers.isEmpty()); + fixture.failNextListenPort = 8443; + publishRuntime(fixture.plane, listener("retry", 8443, true), REGION, 8443, List.of(rule("retry"))); + assertEquals(100, fixture.nextTimerDelay, "a successful bind resets the next recovery delay"); + fixture.runNextTimer(); + fixture.serves(8443, "retry"); + } finally { + fixture.plane.shutdown(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void retirementCancelsBindRetryAndItsQueuedCallbackCannotReviveTheListener(boolean shutdown) { + Fixture fixture = new Fixture(new Registry()); + Listener listener = listener("retiring", 8443, false); + try { + fixture.failNextListenPort = 8443; + publishRuntime(fixture.plane, listener, REGION, null, List.of(rule("retiring"))); + Map.Entry> pending = fixture.timers.entrySet().iterator().next(); + if (shutdown) { + fixture.plane.shutdown(); + } else { + removeRuntime(fixture.plane, listener.getListenerArn(), listener.getPort()); + } + assertTrue(fixture.timers.isEmpty()); + pending.getValue().handle(pending.getKey()); + assertEquals(1, fixture.creations(8443)); + if (!shutdown) { + publishRuntime(fixture.plane, listener("replacement", 8443, false), REGION, null, List.of(rule("replacement"))); + pending.getValue().handle(pending.getKey()); + assertEquals(2, fixture.creations(8443)); + fixture.serves(8443, "replacement"); + } + } finally { + fixture.plane.shutdown(); + } + } + private static final class Registry extends ConcurrentHashMap { private final CountDownLatch entered = new CountDownLatch(1); private final CountDownLatch release = new CountDownLatch(1); @@ -531,6 +622,10 @@ class ElbV2ListenerOwnershipTest { private final Map created = new ConcurrentHashMap<>(); private final Map closed = new ConcurrentHashMap<>(); private final Map servers = new ConcurrentHashMap<>(); + private final Map> timers = new ConcurrentHashMap<>(); + private final AtomicLong timerSequence = new AtomicLong(); + private long nextTimerDelay; + private Promise nextClose; private volatile int failNextListenPort = -1; private Fixture(Registry registry) { @@ -554,6 +649,14 @@ class ElbV2ListenerOwnershipTest { CertificateMaterial material = new CertificateMaterial(CERTIFICATE, pair.certificatePem(), pair.privateKeyPem(), null); when(plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(material); plane.vertx = mock(Vertx.class); + when(plane.vertx.setTimer(anyLong(), any())).thenAnswer(call -> { + long timer = timerSequence.incrementAndGet(); + nextTimerDelay = call.getArgument(0); + timers.put(timer, call.getArgument(1)); + return timer; + }); + when(plane.vertx.cancelTimer(anyLong())).thenAnswer(call -> + timers.remove(call.getArgument(0)) != null); when(plane.vertx.createHttpServer(any(HttpServerOptions.class))).thenAnswer(call -> { int port = ((HttpServerOptions) call.getArgument(0)).getPort(); created.computeIfAbsent(port, ignored -> new AtomicInteger()).incrementAndGet(); @@ -572,7 +675,9 @@ class ElbV2ListenerOwnershipTest { }); when(server.close()).thenAnswer(ignored -> { closed.computeIfAbsent(port, key -> new AtomicInteger()).incrementAndGet(); - return Future.succeededFuture(); + Promise pending = nextClose; + nextClose = null; + return pending == null ? Future.succeededFuture() : pending.future(); }); when(server.updateSSLOptions(any(SSLOptions.class), eq(true))).thenReturn(Future.succeededFuture(true)); return server; @@ -584,6 +689,12 @@ class ElbV2ListenerOwnershipTest { return count == null ? 0 : count.get(); } + private void runNextTimer() { + assertEquals(1, timers.size()); + long timer = timers.keySet().iterator().next(); + timers.remove(timer).handle(timer); + } + private int closes(int port) { AtomicInteger count = closed.get(port); return count == null ? 0 : count.get(); diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java index 67515615f2..ad85faf736 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java @@ -408,7 +408,7 @@ class ElbV2ReservedPortTest { @ParameterizedTest @ValueSource(strings = {"factory", "handler", "listen", "failed-future"}) - void identicalStartRecoversFromServerAcquisitionFailure(String stage) { + void listenerRecoversFromServerAcquisitionFailure(String stage) { ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0); EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); @@ -454,6 +454,13 @@ class ElbV2ReservedPortTest { verify(failed).close(); } publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered"))); + if ("failed-future".equals(stage)) { + verify(replacement, never()).listen(); + @SuppressWarnings("unchecked") + ArgumentCaptor> retry = ArgumentCaptor.forClass(Handler.class); + verify(dataPlane.vertx).setTimer(eq(100L), retry.capture()); + retry.getValue().handle(0L); + } verify(replacement).listen(); assertFixedResponse(replacement, "retry.example.test", "recovered"); removeRuntime(dataPlane, listener.getListenerArn(), listener.getPort()); diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TcpDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TcpDataPlaneIntegrationTest.java index 9a5e3eeb74..e061ada765 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TcpDataPlaneIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TcpDataPlaneIntegrationTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; +import io.github.hectorvent.floci.testutil.LogCapture; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -55,6 +56,7 @@ import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.time.Duration; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -362,6 +364,50 @@ class ElbV2TcpDataPlaneIntegrationTest { } } + @ParameterizedTest + @EnumSource(value = ProtocolEnum.class, names = {"TCP", "HTTP"}) + void listenerStartsAfterExternalPortOwnerReleasesIt(ProtocolEnum protocol) throws Exception { + LoadBalancer other = client.createLoadBalancer(request -> request.name("tcp-regression-occupied") + .type(protocol == ProtocolEnum.TCP ? LoadBalancerTypeEnum.NETWORK : LoadBalancerTypeEnum.APPLICATION) + .subnets(Ec2Service.defaultSubnetId("us-east-1", "a"), + Ec2Service.defaultSubnetId("us-east-1", "b"))) + .loadBalancers().getFirst(); + try (ServerSocket occupied = new ServerSocket(0)) { + int port = occupied.getLocalPort(); + Action action = protocol == ProtocolEnum.TCP + ? Action.builder().type(ActionTypeEnum.FORWARD).targetGroupArn(targetGroupArn).build() + : Action.builder().type(ActionTypeEnum.FIXED_RESPONSE).fixedResponseConfig( + FixedResponseActionConfig.builder().statusCode("200").contentType("text/plain") + .messageBody("recovered").build()).build(); + Listener created = LogCapture.awaitRecord(ElbV2DataPlane.class, Duration.ofSeconds(5), + record -> record.getMessage().contains("listener port failed to start") + && record.getParameters() != null + && Arrays.asList(record.getParameters()).contains(Integer.toString(port)), + () -> client.createListener(request -> request.loadBalancerArn(other.loadBalancerArn()) + .protocol(protocol).port(port).defaultActions(action)).listeners().getFirst()); + assertEquals(created.listenerArn(), client.describeListeners(request -> request + .loadBalancerArn(other.loadBalancerArn())).listeners().getFirst().listenerArn()); + occupied.close(); + + await().atMost(Duration.ofSeconds(5)).ignoreExceptions().untilAsserted(() -> { + try (Socket socket = connect(port)) { + if (protocol == ProtocolEnum.TCP) { + assertEcho(socket, new byte[]{0, 9, 13, 10}); + } else { + socket.setSoTimeout(2000); + socket.getOutputStream().write(("GET / HTTP/1.1\r\nHost: " + other.dnsName() + + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); + String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII); + assertTrue(response.startsWith("HTTP/1.1 200"), response); + assertTrue(response.endsWith("recovered"), response); + } + } + }); + } finally { + client.deleteLoadBalancer(request -> request.loadBalancerArn(other.loadBalancerArn())); + } + } + @Test void tcpConnectionsUseRoundRobinAndKeepTheirSelectedTarget() throws Exception { NetServer second = vertx.createNetServer().connectHandler(socket -> socket.handler(buffer -> { diff --git a/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.java b/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.java index 87289dd16e..c89d3e90f9 100644 --- a/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.java +++ b/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.java @@ -1,7 +1,13 @@ package io.github.hectorvent.floci.testutil; +import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; @@ -14,13 +20,36 @@ public final class LogCapture { } public static List capture(Class source, Runnable action) { + List records = new ArrayList<>(); + withHandler(source, records::add, () -> { + action.run(); + return null; + }); + return records; + } + + /** Runs the action with capture installed, then waits for a matching asynchronous record. */ + public static T awaitRecord(Class source, Duration timeout, Predicate matches, + Supplier action) { + CompletableFuture matched = new CompletableFuture<>(); + return withHandler(source, record -> { + if (matches.test(record)) { + matched.complete(record); + } + }, () -> { + T result = action.get(); + matched.orTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS).join(); + return result; + }); + } + + private static T withHandler(Class source, Consumer observer, Supplier action) { Logger logger = Logger.getLogger(source.getName()); Level originalLevel = logger.getLevel(); - List records = new ArrayList<>(); Handler handler = new Handler() { @Override public void publish(LogRecord record) { - records.add(record); + observer.accept(record); } @Override @@ -35,11 +64,10 @@ public final class LogCapture { logger.addHandler(handler); try { logger.setLevel(Level.ALL); - action.run(); + return action.get(); } finally { logger.removeHandler(handler); logger.setLevel(originalLevel); } - return records; } } diff --git a/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.java b/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.java index 6c91f09702..e93ba3fe4c 100644 --- a/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.java +++ b/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.java @@ -1,13 +1,23 @@ package io.github.hectorvent.floci.testutil; +import io.github.hectorvent.floci.testing.ThreadStates; import org.junit.jupiter.api.Test; +import java.time.Duration; import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -49,4 +59,61 @@ class LogCaptureTest { logger.setLevel(originalLevel); } } + @Test + void awaitsMatchingRecordAfterActionReturns() throws Exception { + Logger logger = Logger.getLogger(LogCaptureTest.class.getName()); + Level originalLevel = logger.getLevel(); + int originalHandlerCount = logger.getHandlers().length; + CountDownLatch actionReturned = new CountDownLatch(1); + FutureTask task = new FutureTask<>(() -> LogCapture.awaitRecord(LogCaptureTest.class, + Duration.ofSeconds(5), record -> "matched".equals(record.getMessage()), () -> { + actionReturned.countDown(); + return "action result"; + })); + Thread worker = new Thread(task); + worker.start(); + try { + assertTrue(actionReturned.await(5, TimeUnit.SECONDS)); + ThreadStates.awaitState(worker, Set.of(Thread.State.WAITING), Duration.ofSeconds(5), "log waiter"); + logger.info("unrelated"); + assertFalse(task.isDone(), "an unrelated record must not release the waiter"); + logger.info("matched"); + assertEquals("action result", task.get(5, TimeUnit.SECONDS)); + assertEquals(originalLevel, logger.getLevel()); + assertEquals(originalHandlerCount, logger.getHandlers().length); + } finally { + logger.info("matched"); + worker.join(6000); + assertFalse(worker.isAlive(), "log waiter exited"); + } + } + + @Test + void awaitRestoresLoggerWhenNoRecordMatches() { + Logger logger = Logger.getLogger(LogCaptureTest.class.getName()); + Level originalLevel = logger.getLevel(); + int originalHandlerCount = logger.getHandlers().length; + CompletionException failure = assertThrows(CompletionException.class, () -> + LogCapture.awaitRecord(LogCaptureTest.class, Duration.ZERO, + record -> "missing".equals(record.getMessage()), () -> { + logger.info("unrelated"); + return null; + })); + assertInstanceOf(TimeoutException.class, failure.getCause()); + assertEquals(originalLevel, logger.getLevel()); + assertEquals(originalHandlerCount, logger.getHandlers().length); + } + + @Test + void awaitRestoresLoggerWhenActionThrows() { + Logger logger = Logger.getLogger(LogCaptureTest.class.getName()); + Level originalLevel = logger.getLevel(); + int originalHandlerCount = logger.getHandlers().length; + assertThrows(IllegalStateException.class, () -> LogCapture.awaitRecord(LogCaptureTest.class, + Duration.ofSeconds(5), record -> true, () -> { + throw new IllegalStateException("failed action"); + })); + assertEquals(originalLevel, logger.getLevel()); + assertEquals(originalHandlerCount, logger.getHandlers().length); + } }