The machine is driven directly: the events are passed to it by hand, and the results are + * observed through the state of the machine, the futures of the events and the recorded calls of + * the connection view. The heartbeat itself is covered by the tests of the algorithm, here it is + * only used as an observable side effect: the machine must schedule exactly one ping on the startup + * and must cancel it on the shutdown. + * + *
The test is synchronous: the timer is a {@link FakeTimer}, so nothing happens until the test + * fires the timeout by hand. + */ +@Timeout(value = 30) +@Execution(ExecutionMode.CONCURRENT) +@TestInstance(Lifecycle.PER_METHOD) +public class HeartbeatStateMachineTest { + + private static final String TAG = "node-a"; + private static final int IDX = 1; + private static final Duration INITIAL_DELAY = Duration.ofMillis(250); + private static final Duration TIMEOUT = Duration.ofSeconds(5); + + private FakeTimer timer; + private RecordingPoolEntryView view; + + @BeforeEach + void setUp() { + this.timer = new FakeTimer(); + this.view = viewWith(StubClient.create()); + } + + /** + * Checks that the startup moves the machine to the started state. + * + *
The startup is successful only if the future of the event is completed: the library waits
+ * for it and restarts the policy if it fails.
+ */
+ @Test
+ void testStartTransmitMachineToStartedState() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final CompletableFuture The heartbeat is the only thing the machine does, so the startup must not schedule the pings
+ * twice and must not schedule them at all if the startup has failed.
+ */
+ @Test
+ void testStartSchedulesExactlyOnePing() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ final CompletableFuture The initial delay is the delay before the very first ping, so it must be applied to the
+ * first scheduled timeout.
+ */
+ @Test
+ void testStartSchedulesFirstPingAfterInitialDelay() {
+ final HeartbeatStateMachine machine =
+ machine(HeartbeatOpts.getDefault().withInitialDelay(INITIAL_DELAY));
+
+ final CompletableFuture The window accumulates the results of the pings, so the startup must start the counting from
+ * scratch. The connection has just been established by the library, so it counts as the first
+ * successful ping: the window holds the mark of the connection.
+ */
+ @Test
+ void testStartFillsTheWindowWithTheConnection() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ final CompletableFuture The shutdown may come before the startup: the library stops the policy if its startup has
+ * failed. The machine must not start the heartbeat then and must complete the close future.
+ */
+ @Test
+ void testStopBeforeStartStopsTheMachine() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final CompletableFuture The pending ping must be cancelled, otherwise the machine would keep the connection busy
+ * after the shutdown.
+ */
+ @Test
+ void testStopCancelsThePendingPing() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final CompletableFuture The shutdown must be idempotent: the repeated shutdown must not fail and must not touch the
+ * connection again.
+ */
+ @Test
+ void testRepeatedStopIsIdempotent() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ final CompletableFuture The machine is stopped forever: the library starts a new one instead of the stopped one, so
+ * the startup of the stopped machine must fail instead of running a second heartbeat.
+ */
+ @Test
+ void testStartAfterStopFails() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ final CompletableFuture The machine has no heartbeat yet, so the ping and the state events have nothing to do and
+ * must be dropped silently.
+ */
+ @Test
+ void testHeartbeatEventsAreIgnoredInNewState() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ machine.handle(SendPingEvent.INSTANCE);
+ machine.handle(new PongEvent(StubClient.emptyBodyResponse(), null));
+ machine.handle(ActivateEvent.INSTANCE);
+ machine.handle(InvalidateEvent.INSTANCE);
+ machine.handle(KillEvent.INSTANCE);
+
+ Assertions.assertInstanceOf(NewState.class, machine.state());
+ Assertions.assertTrue(view.calls().isEmpty(), "The connection must not be touched");
+ Assertions.assertEquals(0, timer.scheduledCount(), "The machine must not start the heartbeat");
+ }
+
+ /**
+ * Checks that the events of a running heartbeat are ignored after the shutdown.
+ *
+ * The heartbeat is stopped, so the ping and the state events have nothing to do and must be
+ * dropped silently.
+ */
+ @Test
+ void testHeartbeatEventsAreIgnoredInStoppedState() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ CompletableFuture The event is a part of the internal protocol of the machine, so a null one must not break
+ * the machine.
+ */
+ @Test
+ void testNullEventIsIgnored() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ Assertions.assertDoesNotThrow(() -> machine.handle(null));
+ Assertions.assertDoesNotThrow(() -> machine.state().handle(null));
+
+ Assertions.assertInstanceOf(NewState.class, machine.state());
+ Assertions.assertTrue(view.calls().isEmpty(), "The connection must not be touched");
+ }
+
+ /**
+ * Checks the names of the states.
+ *
+ * The name of the state is used in the logs of the heartbeat, so it must be stable.
+ */
+ @Test
+ void testStateNames() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+
+ Assertions.assertEquals("HEARTBEAT_NEW", new NewState(machine).toString());
+ Assertions.assertEquals("HEARTBEAT_STARTED", new StartedState(machine).toString());
+ Assertions.assertEquals("HEARTBEAT_STOPPED", new StoppedState(machine).toString());
+ }
+
+ /**
+ * Checks that the concurrent startups start the heartbeat once.
+ *
+ * The library starts the policy once per connection, but the concurrent startups must be safe
+ * anyway: the machine is shared by all of them, so only the first startup may schedule the ping
+ * and all the start futures must be completed successfully.
+ */
+ @Test
+ void testConcurrentStartsStartTheHeartbeatOnce() throws Exception {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final int starters = 16;
+ final CountDownLatch ready = new CountDownLatch(starters);
+ final CountDownLatch go = new CountDownLatch(1);
+ final List The shutdown is a control event, so it is processed before the ordinary events even if they
+ * have been queued earlier. The queued pong must not be handled by the stopped machine, so the
+ * connection must not be killed.
+ */
+ @Test
+ void testStopPreemptsTheQueuedEvents() throws Exception {
+ final CountDownLatch pingStarted = new CountDownLatch(1);
+ final CountDownLatch releasePing = new CountDownLatch(1);
+ final HeartbeatOpts opts =
+ HeartbeatOpts.getDefault()
+ .withPingFunction(
+ (client, requestOpts) -> {
+ pingStarted.countDown();
+ try {
+ releasePing.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ return CompletableFuture.completedFuture(StubClient.emptyBodyResponse());
+ });
+ final HeartbeatStateMachine machine = machine(opts);
+ final CompletableFuture The connection has just been established by the library, so it is alive: the activation is
+ * reported right after the startup, before the first ping. The repeated successful pings do not
+ * report it again. The policy does not report the opening of the connection: the physical
+ * connection is tracked by the pool entry.
+ */
+ @Test
+ void testActivateEventIsEmittedOnce() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault().withWindowSize(2));
+ final CompletableFuture The library reports the opening of the connection after the startup, so the listener must
+ * know about the activation before the startup is completed.
+ */
+ @Test
+ void testActivateIsEmittedBeforeTheStartupIsReported() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final CompletableFuture The physical connection is tracked by the pool entry, so the policy reports only the
+ * heartbeat events. The whole lifecycle is checked here: the activation, the invalidation, the
+ * activation of the recovered connection and the kill with the requested restart.
+ */
+ @Test
+ void testPolicyDoesNotReportTheConnectionEvents() {
+ final RuntimeException noAnswer = new RuntimeException("the node does not answer");
+ this.view = viewWith(StubClient.failing(noAnswer).nextPingFails(noAnswer).nextPingSucceeds());
+ final HeartbeatStateMachine machine =
+ machine(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(2));
+ final CompletableFuture The connection is activated on the startup and invalidated later: both events are reported
+ * once.
+ */
+ @Test
+ void testInvalidateEventIsEmitted() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ machine(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(2)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+ final CompletableFuture The connection is activated on the startup, invalidated later and killed when the death
+ * threshold is reached. The restart is requested only after the kill event has been delivered to
+ * the listener.
+ */
+ @Test
+ void testKillEventIsEmittedAndTheRestartIsRequested() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ machine(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(1));
+ final CompletableFuture The ping function is a part of the contract with the user, and it must never return null. If
+ * it does, the machine must not fail with an unexpected error: the broken ping is a ping error,
+ * and the connection is killed through the regular kill event, exactly once.
+ */
+ @Test
+ void testNullPingKillsTheConnection() {
+ final HeartbeatStateMachine machine =
+ machine(HeartbeatOpts.getDefault().withPingFunction((client, requestOpts) -> null));
+ final CompletableFuture The measurement of the ping is started before the ping function is called. If the function
+ * returns null, nobody completes the ping, so the machine must stop the measurement itself,
+ * otherwise the metric would show a ping that lasts forever. The broken ping is counted as a
+ * failed one.
+ */
+ @Test
+ void testNullPingStopsTheTimeMeasurement() {
+ final SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ final HeartbeatStateMachine machine =
+ new HeartbeatStateMachine(
+ this.view,
+ HeartbeatOpts.getDefault().withPingFunction((client, requestOpts) -> null),
+ Utils.configure(this.timer, registry));
+ final CompletableFuture The first ping is scheduled during the startup, and the timer may fail then. The machine has
+ * already moved to the started state by that moment, so the error handler must roll it back: the
+ * machine must be stopped, its context must be released, the connection must be invalidated and
+ * the start future must fail with the cause of the error. The activation must not be reported,
+ * because the startup has not been completed.
+ */
+ @Test
+ void testFailedStartStopsTheMachine() {
+ final HeartbeatStateMachine machine =
+ machine(HeartbeatOpts.getDefault(), new BrokenTimer(this.timer, 0));
+ final CompletableFuture The startup is successful here, so the error handler cannot fail the start future. Instead,
+ * it must treat the connection as dead: the kill is reported once and the restart is requested
+ * once. The timer is broken when the machine schedules the second ping.
+ */
+ @Test
+ void testUnexpectedErrorAfterStartKillsTheConnection() {
+ final HeartbeatStateMachine machine =
+ machine(HeartbeatOpts.getDefault(), new BrokenTimer(this.timer, 1));
+ final CompletableFuture The heartbeat is already running, so the repeated startup must only report the result of the
+ * first one through its own future: it must not touch the connection and must not schedule one
+ * more ping.
+ */
+ @Test
+ void testRepeatedStartCompletesTheFutureWithoutSideEffects() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final CompletableFuture The callback of the start future is called by the machine itself while it handles the start
+ * event. The shutdown is queued then and must be processed right after the startup: the startup
+ * stays successful, and the machine is stopped without a pending ping.
+ */
+ @Test
+ void testStopFromTheStartCallbackIsProcessedAfterTheStartup() {
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault());
+ final CompletableFuture The measurement is started before the ping function is called, so the machine must stop it
+ * itself if the ping has not been sent. The failed ping is counted as an error, but it does not
+ * kill the connection.
+ */
+ @Test
+ void testThrownPingStopsTheTimeMeasurement() {
+ final SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ final HeartbeatOpts opts =
+ HeartbeatOpts.getDefault()
+ .withPingFunction(
+ (client, requestOpts) -> {
+ throw new RuntimeException("cannot send the ping");
+ });
+ final HeartbeatStateMachine machine = machine(opts, registry);
+ final CompletableFuture The ping is sent, but the answer is an error: the measurement is finished with the answer,
+ * and the ping is counted as an error.
+ */
+ @Test
+ void testFailedPingStopsTheTimeMeasurement() {
+ final SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ this.view =
+ viewWith(
+ StubClient.create().nextPingFails(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault(), registry);
+ final CompletableFuture The measurement is the metric of the ping duration, so it must be active until the answer is
+ * received and must be stopped right after it.
+ */
+ @Test
+ void testTimeMeasurementLastsWhilePingIsInFlight() {
+ final SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ final CompletableFuture The window is the heart of the algorithm: it keeps the results of the last pings, so the
+ * heartbeat invalidates the connection when the failed pings reach the invalidation threshold and
+ * kills it when the death threshold is exceeded. The tests check the boundaries of the thresholds,
+ * the sliding of the window and the reaction to the recovery of the connection.
+ *
+ * The test is synchronous: the timer is a {@link FakeTimer}, so nothing happens until the test
+ * fires the timeout by hand. One fired timeout is one ping, because the stub answers at once.
+ */
+@Timeout(value = 30)
+@Execution(ExecutionMode.CONCURRENT)
+@TestInstance(Lifecycle.PER_METHOD)
+public class HeartbeatWindowTest {
+
+ private static final String TAG = "node-a";
+ private static final int IDX = 1;
+
+ private FakeTimer timer;
+ private RecordingPoolEntryView view;
+
+ @BeforeEach
+ void setUp() {
+ this.timer = new FakeTimer();
+ this.view = viewWith(StubClient.create());
+ }
+
+ /**
+ * Checks that the established connection counts as the first successful ping.
+ *
+ * The heartbeat is started right after the connection is established, so the connection itself
+ * is the proof that the node is alive: the window starts with the success mark of the connection
+ * and no extra ping is needed to confirm it.
+ */
+ @Test
+ void testConnectionIsFirstPing() {
+ final HeartbeatStateMachine machine = start(HeartbeatOpts.getDefault().withWindowSize(4));
+
+ Assertions.assertEquals(
+ 1, machine.ctx().window.size(), "The window must hold the mark of the connection");
+ Assertions.assertNotNull(machine.ctx().window.peekFirst());
+ Assertions.assertEquals(
+ 0,
+ machine.ctx().window.peekFirst().intValue(),
+ "The established connection must be a success");
+ Assertions.assertEquals(0, machine.ctx().currentFailedPings);
+ Assertions.assertEquals(0, machine.ctx().currentDeathPings);
+ }
+
+ /**
+ * Checks that the heartbeat makes no decision until the window is full.
+ *
+ * The window is filled with the results of the pings, so the heartbeat may invalidate the
+ * connection only when it knows the whole window: the failed pings of the incomplete window are
+ * counted, but they are not a reason to invalidate the connection yet.
+ */
+ @Test
+ void testNoDecisionUntilWindowIsFull() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(4)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(2);
+
+ Assertions.assertEquals(
+ Collections.singletonList("onHeartbeatEvent:ACTIVATE"),
+ this.view.listener().events(),
+ "The incomplete window must not invalidate the connection");
+ Assertions.assertEquals(2, machine.ctx().currentFailedPings, "The failures must be counted");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The full window must invalidate the connection");
+ }
+
+ /**
+ * Checks the boundary of the invalidation threshold.
+ *
+ * The connection is invalidated when the count of the failed pings in the window reaches the
+ * threshold, so the threshold is reached exactly on the given ping.
+ */
+ @ParameterizedTest(name = "[{index}] the threshold {0} invalidates on the ping {1}")
+ @CsvSource({"1, 3", "2, 3", "3, 3", "4, 4"})
+ void testInvalidationThresholdBoundary(int threshold, int expectedPing) {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(4)
+ .withInvalidationThreshold(threshold)
+ .withDeathThreshold(100));
+
+ firePings(expectedPing - 1);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The connection must not be invalidated before the threshold is reached");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The connection must be invalidated when the threshold is reached");
+ }
+
+ /**
+ * Checks that the connection is not invalidated when the threshold is out of the window.
+ *
+ * The window keeps the results of the last pings only, so the threshold that is greater than
+ * the size of the window can never be reached.
+ */
+ @Test
+ void testUnreachableInvalidationThreshold() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(4)
+ .withInvalidationThreshold(5)
+ .withDeathThreshold(100));
+
+ firePings(10);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The threshold is out of the window, so the connection must not be invalidated");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must not be killed");
+ Assertions.assertEquals(4, machine.ctx().currentFailedPings, "The window holds the failures");
+ Assertions.assertEquals(4, machine.ctx().window.size(), "The window must keep its size");
+ }
+
+ /**
+ * Checks the boundary of the death threshold.
+ *
+ * The connection is killed when the count of the invalidations exceeds the death threshold, so
+ * the kill happens on the ping that exceeds it.
+ */
+ @ParameterizedTest(name = "[{index}] the threshold {0} kills on the ping {1}")
+ @CsvSource({"1, 2", "2, 3", "3, 4"})
+ void testKillThresholdBoundary(int threshold, int expectedPing) {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(threshold));
+
+ firePings(expectedPing - 1);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must not be killed before the threshold is exceeded");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must be killed when the threshold is exceeded");
+ }
+
+ /**
+ * Checks that the counter of the deaths is reset when the connection comes back to life.
+ *
+ * The counter grows on every invalidation and is reset when the connection is alive again, so
+ * the connection that recovers before the death threshold is reached is not killed.
+ */
+ @Test
+ void testDeathCounterIsResetWhenConnectionComesBackToLife() {
+ final RuntimeException noAnswer = new RuntimeException("the node does not answer");
+ this.view =
+ viewWith(
+ StubClient.failing(noAnswer)
+ .nextPingFails(noAnswer)
+ .nextPingFails(noAnswer)
+ .nextPingSucceeds());
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(2)
+ .withInvalidationThreshold(2)
+ .withDeathThreshold(1));
+
+ // the first two pings fail: the connection is invalidated
+ firePings(2);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The failed pings must invalidate the connection");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection is alive");
+
+ // the third ping succeeds: the connection is alive again and the counter of the deaths is reset
+ firePings(1);
+
+ Assertions.assertEquals(
+ 2,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.ACTIVATE),
+ "The recovered connection must be activated again");
+
+ // the failures of the next pings invalidate the connection again, but the counter of the
+ // deaths has been reset, so the kill needs one more invalidation
+ firePings(2);
+
+ Assertions.assertEquals(
+ 2,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The connection must be invalidated again");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The reset counter of the deaths must not kill the recovered connection");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The second invalidation in a row must kill the connection");
+ }
+
+ /**
+ * Checks that the window slides with the pings.
+ *
+ * The oldest result leaves the window as the new one arrives, so a success pushes the old
+ * failures out of the window and the connection becomes alive again.
+ */
+ @Test
+ void testWindowSlides() {
+ final RuntimeException noAnswer = new RuntimeException("the node does not answer");
+ this.view =
+ viewWith(
+ StubClient.failing(noAnswer)
+ .nextPingFails(noAnswer)
+ .nextPingFails(noAnswer)
+ .nextPingSucceeds());
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(2)
+ .withInvalidationThreshold(2)
+ .withDeathThreshold(100));
+
+ firePings(2);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The failed pings must invalidate the connection");
+ Assertions.assertEquals(2, machine.ctx().window.size(), "The window must be full");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 2,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.ACTIVATE),
+ "The success must push the old failure out of the window and activate the connection");
+ Assertions.assertEquals(1, machine.ctx().currentFailedPings, "The old failure must leave");
+ Assertions.assertEquals(2, machine.ctx().window.size(), "The window must keep its size");
+ }
+
+ /**
+ * Checks that the window keeps the configured size.
+ *
+ * The window is a sliding one, so it must not grow beyond the configured size.
+ */
+ @Test
+ void testWindowKeepsItsSize() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(3)
+ .withInvalidationThreshold(2)
+ .withDeathThreshold(100));
+
+ firePings(10);
+
+ Assertions.assertEquals(3, machine.ctx().window.size(), "The window must keep its size");
+ Assertions.assertEquals(3, machine.ctx().currentFailedPings);
+ }
+
+ /**
+ * Checks that the terminal error kills the connection without waiting for the window.
+ *
+ * The connection is dead, so there is nothing to wait for: the heartbeat kills the connection
+ * at once.
+ */
+ @Test
+ void testTerminalErrorBypassesWindow() {
+ this.view = viewWith(StubClient.failing(new ConnectionException("the connection is dead")));
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(4)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The dead connection must not wait for the window");
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The dead connection must be killed");
+ Assertions.assertSame(HeartbeatConstants.KILL_STATE, this.view.state());
+ Assertions.assertEquals(1, this.view.reconnectCallsCount(), "The restart must be requested");
+ }
+
+ /**
+ * Checks that the error that is not terminal is counted as a failed ping.
+ *
+ * The node may be busy or the packet may be lost, so such an error is not a proof that the
+ * connection is dead: it is counted in the window as a failed ping.
+ */
+ @Test
+ void testNonTerminalErrorIsCountedAsFailure() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(4)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must not be killed");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The incomplete window must not invalidate the connection");
+ Assertions.assertEquals(1, machine.ctx().currentFailedPings, "The failure must be counted");
+ Assertions.assertEquals(2, machine.ctx().window.size());
+ }
+
+ /**
+ * Checks that the killed connection is not pinged anymore.
+ *
+ * The library restarts the connection after the kill, so the heartbeat must stop at once.
+ */
+ @Test
+ void testKillStopsHeartbeat() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(1));
+
+ firePings(2);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must be killed");
+ Assertions.assertEquals(
+ 0, this.timer.pendingCount(), "The heartbeat must be stopped after the kill");
+ Assertions.assertInstanceOf(StoppedState.class, machine.state());
+ }
+
+ /**
+ * Checks the numbers of the default options against the legacy heartbeat.
+ *
+ * The legacy heartbeat invalidates the connection on the third failed ping and kills it on the
+ * seventh one with the default options: the new heartbeat must behave the same way.
+ */
+ @Test
+ void testDefaultOptionsMatchLegacyNumbers() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ start(HeartbeatOpts.getDefault());
+
+ firePings(2);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The legacy heartbeat invalidates the connection on the third failed ping");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The legacy heartbeat invalidates the connection on the third failed ping");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must be alive on the third failed ping");
+
+ firePings(4);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The legacy heartbeat kills the connection on the seventh failed ping");
+ Assertions.assertEquals(
+ Arrays.asList(
+ "onHeartbeatEvent:ACTIVATE", "onHeartbeatEvent:INVALIDATE", "onHeartbeatEvent:KILL"),
+ this.view.listener().events());
+ }
+
+ /**
+ * Checks that the hanging ping does not pile up the pings.
+ *
+ * The ping that hangs forever is a proof that the node does not answer, but the policy must
+ * not send the next ping while the previous one is still in flight: the requests would pile up
+ * and flood the connection. The timeout of the request is the concern of the client, so the
+ * policy waits for the answer and decides nothing on its own.
+ */
+ @Test
+ void testHangingPingDoesNotPileUpPings() {
+ final StubClient stub = StubClient.create().nextPingHangs();
+ this.view = viewWith(stub);
+ final HeartbeatStateMachine machine = start(HeartbeatOpts.getDefault());
+
+ firePings(1);
+
+ Assertions.assertEquals(1, stub.pingCount(), "Only the hanging ping must be sent");
+ Assertions.assertEquals(
+ 0,
+ this.timer.pendingCount(),
+ "The next ping must not be scheduled while the previous one is in flight");
+ Assertions.assertEquals(1, this.timer.scheduledCount(), "The next ping must not be scheduled");
+ Assertions.assertEquals(1, machine.ctx().window.size(), "The window must not grow");
+ Assertions.assertEquals(
+ 0, machine.ctx().currentFailedPings, "The hanging ping is not a failure yet");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The connection must not be invalidated");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must not be killed");
+ Assertions.assertEquals(
+ 0, this.view.reconnectCallsCount(), "The connection must not be restarted");
+ Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, this.view.state());
+ }
+
+ /**
+ * Checks that the answer that is not a success is counted as a failed ping.
+ *
+ * The node may answer with an error or with an unexpected body. Such an answer is a proof that
+ * the node is not healthy, but it is not a proof that the connection is dead, so it is counted in
+ * the window as an ordinary failed ping.
+ */
+ @ParameterizedTest(name = "[{index}] {1}")
+ @MethodSource("dataForTestFailedPingAnswers")
+ void testFailedAnswerIsCountedAsFailedPing(IProtoResponse answer, String description) {
+ this.view = viewWith(StubClient.create().nextPingReturns(answer));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(1);
+
+ Assertions.assertEquals(1, machine.ctx().currentFailedPings, description);
+ Assertions.assertEquals(
+ 1, this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE), description);
+ Assertions.assertEquals(
+ 0, this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL), description);
+ }
+
+ /** The answers of the node that are not a success of the ping. */
+ static Stream The answer of the ping may arrive after the policy has been stopped: the stopped machine
+ * must not react to it, otherwise it would kill the connection that the library has already
+ * closed.
+ */
+ @Test
+ void testPongAfterShutdownIsIgnored() {
+ final CompletableFuture The ping function is a part of the user configuration, so it may fail before the request is
+ * even sent. Such an error is not a proof that the connection is dead, so it is counted in the
+ * window as an ordinary failed ping.
+ */
+ @Test
+ void testErrorOfPingFunctionIsCountedAsFailedPing() {
+ final RuntimeException noAnswer = new RuntimeException("the node does not answer");
+ this.view = viewWith(StubClient.create());
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withPingFunction(
+ (client, requestOpts) -> {
+ throw noAnswer;
+ })
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1, machine.ctx().currentFailedPings, "The error must be counted as a failure");
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The connection must be invalidated");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The connection must not be killed");
+ }
+
+ /**
+ * Checks that the terminal error of the ping function kills the connection at once.
+ *
+ * The dead connection must not wait for the window: the kill is the only way to make the
+ * library open a new one.
+ */
+ @Test
+ void testTerminalErrorOfPingFunctionKillsConnection() {
+ final ConnectionException dead = new ConnectionException("the connection is dead");
+ this.view = viewWith(StubClient.create());
+ start(
+ HeartbeatOpts.getDefault()
+ .withPingFunction(
+ (client, requestOpts) -> {
+ throw dead;
+ })
+ .withWindowSize(4)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The dead connection must not wait for the window");
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL),
+ "The dead connection must be killed");
+ Assertions.assertSame(HeartbeatConstants.KILL_STATE, this.view.state());
+ Assertions.assertEquals(1, this.view.reconnectCallsCount(), "The restart must be requested");
+ }
+
+ /**
+ * Checks that the window reserves a slot for the established connection.
+ *
+ * The mark of the connection occupies one of the slots of the window, so the heartbeat knows
+ * the whole window one ping earlier than its size.
+ */
+ @ParameterizedTest(name = "[{index}] the window of {0} decides on the ping {1}")
+ @CsvSource({"2, 1", "3, 2", "4, 3", "5, 4"})
+ void testWindowReservesSlotForConnection(int windowSize, int expectedPing) {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(windowSize)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(expectedPing - 1);
+
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The incomplete window must not invalidate the connection");
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The window must decide as soon as it is full");
+ }
+
+ /**
+ * Checks that the window of the size one holds the result of the last ping only.
+ *
+ * The mark of the connection leaves the window at the first ping, so the window of the size
+ * one holds the result of the last ping only.
+ */
+ @Test
+ void testWindowOfSizeOneHoldsLastPingOnly() {
+ this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer")));
+ final HeartbeatStateMachine machine =
+ start(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(100));
+
+ firePings(1);
+
+ Assertions.assertEquals(
+ 1, machine.ctx().window.size(), "The window must hold the last ping only");
+ Assertions.assertEquals(
+ 1, machine.ctx().currentFailedPings, "The mark of the connection must leave the window");
+ Assertions.assertEquals(
+ 1,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The full window must invalidate the connection at once");
+ }
+
+ /**
+ * Checks that the heartbeat sends exactly one ping per interval.
+ *
+ * Every fired timeout must send exactly one ping and take exactly one client, so the node is
+ * not flooded and the client is not touched twice.
+ */
+ @Test
+ void testHeartbeatSendsOnePingPerInterval() {
+ final StubClient stub = StubClient.create();
+ this.view = viewWith(stub);
+ start(HeartbeatOpts.getDefault());
+
+ firePings(5);
+
+ Assertions.assertEquals(5, stub.pingCount(), "Every fired timeout must send exactly one ping");
+ Assertions.assertEquals(
+ 5, this.view.clientCallsCount(), "The client must be taken once per ping");
+ Assertions.assertEquals(1, this.timer.pendingCount(), "Exactly one ping must be pending");
+ Assertions.assertEquals(
+ 0,
+ this.view.listener().heartbeatEventCount(HeartbeatEvent.INVALIDATE),
+ "The connection is alive");
+ Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, this.view.state());
+ }
+
+ /** Starts the heartbeat with the given options and waits for the startup. */
+ private HeartbeatStateMachine start(HeartbeatOpts opts) {
+ final HeartbeatStateMachine machine = machine(opts);
+ final CompletableFuture Формат пакета: [заголовок][тело]; {@code headerSize} = длина заголовка.
+ * Packet format: [header][body]; {@code headerSize} = header length.
*/
static IProtoResponse response(MapValue header, Value body) {
try (final MessageBufferPacker headerPacker = MessagePack.newDefaultBufferPacker();
@@ -109,12 +108,12 @@ static IProtoResponse response(MapValue header, Value body) {
}
}
- /** Ответ без тела — как от {@code IPROTO_PING}. */
+ /** Empty-body response, such as from {@code IPROTO_PING}. */
static IProtoResponse emptyBody() {
return response(OK_HEADER, ValueFactory.emptyMap());
}
- /** То же, но с произвольным числом элементов в DATA. */
+ /** Same, but with an arbitrary number of elements in DATA. */
static IProtoResponse dataArray(Value... values) {
final ValueFactory.MapBuilder bodyBuilder = ValueFactory.newMapBuilder();
bodyBuilder.put(
@@ -122,7 +121,7 @@ static IProtoResponse dataArray(Value... values) {
return response(OK_HEADER, bodyBuilder.build());
}
- /** Ответ-ошибка сервера. */
+ /** Server error response. */
static IProtoResponse error(int code, String message) {
final MapValue body =
ValueFactory.newMap(
@@ -133,7 +132,7 @@ static IProtoResponse error(int code, String message) {
return response(errorHeader(code), body);
}
- /** Ответ без IPROTO_DATA — например, ответ на IPROTO_ID. */
+ /** A response without IPROTO_DATA — for example, a response to IPROTO_ID. */
static IProtoResponse withoutData() {
return IProtoResponses.response(
OK_HEADER,
@@ -142,7 +141,7 @@ static IProtoResponse withoutData() {
ValueFactory.newInteger(IProtoConstant.IPROTO_FEATURES), ValueFactory.emptyArray()));
}
- /** IPROTO_DATA есть, но это не массив. */
+ /** IPROTO_DATA is present, but it is not an array. */
static IProtoResponse dataNotArray() {
return IProtoResponses.response(
OK_HEADER,
diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/FakeTimer.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FakeTimer.java
new file mode 100644
index 00000000..3441a6cf
--- /dev/null
+++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FakeTimer.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY
+ * All Rights Reserved.
+ */
+
+package io.tarantool.pool.support;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.netty.util.Timeout;
+import io.netty.util.Timer;
+import io.netty.util.TimerTask;
+
+/**
+ * A {@link Timer} that fires nothing by itself: the test decides when a scheduled timeout runs.
+ *
+ * The heartbeat policy schedules the next ping through the timer it has been configured with, so
+ * a manual timer turns the whole heartbeat into a deterministic sequence of steps: the test fires a
+ * timeout, the policy sends a ping, the test completes the ping future, and the policy reacts to
+ * the answer. Neither sleeps nor polling are needed.
+ *
+ * The timeouts are fired in the order of their scheduling. A timeout scheduled by a fired task
+ * is not fired by the same {@link #fireAll()} call, so the test may walk through the heartbeat step
+ * by step.
+ */
+public final class FakeTimer implements Timer {
+
+ private final ConcurrentLinkedQueue The timeouts scheduled by the fired tasks stay pending: the test may fire them one by one to
+ * control the heartbeat step by step.
+ *
+ * @return the count of the fired timeouts
+ */
+ public int fireAll() {
+ int count = 0;
+ for (final FakeTimeout timeout : pendingTimeouts()) {
+ if (timeout.fire()) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ /** A timeout scheduled in a {@link FakeTimer}. */
+ public static final class FakeTimeout implements Timeout {
+
+ private final FakeTimer timer;
+ private final TimerTask task;
+ private final long delayMillis;
+ private final AtomicBoolean expired = new AtomicBoolean();
+ private final AtomicBoolean cancelled = new AtomicBoolean();
+
+ private FakeTimeout(FakeTimer timer, TimerTask task, long delayMillis) {
+ this.timer = timer;
+ this.task = task;
+ this.delayMillis = delayMillis;
+ }
+
+ /**
+ * Returns the delay of the timeout in milliseconds.
+ *
+ * @return the delay in milliseconds
+ */
+ public long delayMillis() {
+ return this.delayMillis;
+ }
+
+ /**
+ * Runs the task of the timeout.
+ *
+ * @return {@code true} if the task has been run, {@code false} if the timeout has been fired or
+ * cancelled before
+ */
+ public boolean fire() {
+ if (!this.expired.compareAndSet(false, true)) {
+ return false;
+ }
+ this.timer.pending.remove(this);
+ this.timer.fired.incrementAndGet();
+ try {
+ this.task.run(this);
+ } catch (Exception e) {
+ throw new IllegalStateException("The timer task has failed", e);
+ }
+ return true;
+ }
+
+ @Override
+ public Timer timer() {
+ return this.timer;
+ }
+
+ @Override
+ public TimerTask task() {
+ return this.task;
+ }
+
+ @Override
+ public boolean isExpired() {
+ return this.expired.get();
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return this.cancelled.get();
+ }
+
+ @Override
+ public boolean cancel() {
+ if (!this.cancelled.compareAndSet(false, true)) {
+ return false;
+ }
+ this.timer.pending.remove(this);
+ this.timer.cancelled.incrementAndGet();
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "FakeTimeout{delayMillis="
+ + this.delayMillis
+ + ", expired="
+ + this.expired.get()
+ + ", cancelled="
+ + this.cancelled.get()
+ + '}';
+ }
+ }
+}
diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/FlakyTimer.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FlakyTimer.java
new file mode 100644
index 00000000..2418b01f
--- /dev/null
+++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FlakyTimer.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY
+ * All Rights Reserved.
+ */
+
+package io.tarantool.pool.support;
+
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.netty.util.Timeout;
+import io.netty.util.Timer;
+import io.netty.util.TimerTask;
+
+/** A timer that fails the given count of the first timeouts and delegates the rest. */
+public class FlakyTimer implements Timer {
+
+ private final Timer delegate;
+ private final AtomicInteger failuresLeft;
+
+ public FlakyTimer(Timer delegate, int failures) {
+ this.delegate = delegate;
+ this.failuresLeft = new AtomicInteger(failures);
+ }
+
+ @Override
+ public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) {
+ if (this.failuresLeft.getAndDecrement() > 0) {
+ throw new RuntimeException("the timer is broken");
+ }
+ return this.delegate.newTimeout(task, delay, unit);
+ }
+
+ @Override
+ public Set The view is intentionally hostile: it throws an exception when the policy passes {@code null}
+ * to {@link #changeState(PoolEntryState)} or to {@link #emit(Consumer)}, because the real view
+ * forbids such calls. Every violation is counted as well, so the test may report it even if the
+ * policy has swallowed the exception.
+ *
+ * The state changes, the emitted events and the reconnects are recorded in the order of their
+ * occurrence, so the test may assert not only the counts but also the sequence of the actions of
+ * the policy.
+ *
+ * A fresh connection is closed, so the view starts in the {@link #CLOSED_STATE} and stays there
+ * until the state is set with {@link #changeState(PoolEntryState)}. The test sets the state
+ * returned by {@code AvailabilityPolicy#initState(view)} the same way the library does upon the
+ * creation of a pool entry.
+ */
+public final class RecordingPoolEntryView implements PoolEntryView {
+
+ /**
+ * The state of a connection that has not been initialized by the policy yet: the connection is
+ * closed, so it is not visible to the load balancer.
+ */
+ public static final PoolEntryState CLOSED_STATE = new PoolEntryState("CLOSED", true) {};
+
+ private final Metadata metadata;
+ private final IProtoClient client;
+ private final RecordingPoolEventListener listener = new RecordingPoolEventListener();
+ private final List Before a state is set the connection is closed, so the view reports {@link #CLOSED_STATE}.
+ * Afterwards it reports the last state set with {@link #changeState(PoolEntryState)}.
+ *
+ * @return the current state of the connection
+ */
+ @Override
+ public PoolEntryState state() {
+ return this.state;
+ }
+
+ @Override
+ public IProtoClient client() {
+ this.clientCalls.incrementAndGet();
+ this.calls.add("client");
+ return this.client;
+ }
+
+ @Override
+ public void reconnect() {
+ this.reconnectCalls.incrementAndGet();
+ this.calls.add("reconnect");
+ }
+
+ @Override
+ public void emit(Consumer The heartbeat policy checks the availability of a node with the client of the connection view,
+ * so the test must be able to decide what the node answers: a successful ping, a failed ping, a
+ * ping that hangs forever, a ping with a specific response body, or a ping whose answer is
+ * delivered by the test at a chosen moment.
+ *
+ * The answers are taken from the queue in the order of their scripting. When the queue is empty,
+ * the default answer is used: a successful ping for {@link #create()}, a failed ping for {@link
+ * #failing(Throwable)}.
+ */
+public final class StubClient {
+
+ private final IProtoClient client;
+ private final Queue The future is returned as is, so the test keeps the control over the moment of the answer:
+ * the heartbeat reacts to the ping only when the future is completed. A future that is never
+ * completed makes the ping hang forever.
+ *
+ * @param future the future to return from the next ping
+ * @return this stub instance
+ */
+ public StubClient nextPingReturnsFuture(CompletableFuture The tests cover the lifecycle of a policy: the configuration, the initialization, the startup,
+ * the shutdown and the restart. The heartbeat itself is covered by the tests of the state machine,
+ * here it is only used as an observable side effect: the policy must schedule exactly one ping per
+ * connection and must cancel it on the shutdown.
+ *
+ * The whole test is synchronous: the timer is a {@link FakeTimer}, so the ping is sent only when
+ * the test fires it, and the stubbed client answers the ping immediately.
+ */
+@Timeout(value = 30)
+@Execution(ExecutionMode.CONCURRENT)
+@TestInstance(Lifecycle.PER_METHOD)
+public class DefaultAvailabilityPolicyTest {
+
+ private static final String TAG = "node-a";
+ private static final int IDX = 1;
+ private static final Duration TIMEOUT = Duration.ofSeconds(5);
+
+ private FakeTimer timer;
+ private MeterRegistry registry;
+
+ @BeforeEach
+ void setUp() {
+ this.timer = new FakeTimer();
+ this.registry = new SimpleMeterRegistry();
+ }
+
+ /**
+ * Checks that a fresh connection is available by default.
+ *
+ * The initial state is returned by {@code initState()} and is applied to the connection by the
+ * library, so it must be the active one.
+ */
+ @Test
+ void testInitStateReturnsActiveState() {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ final PoolEntryState state = policy.initState(view);
+
+ Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, state);
+ Assertions.assertFalse(state.isLocked(), "The connection must be available by default");
+ }
+
+ /**
+ * Checks that the startup of an unconfigured policy fails.
+ *
+ * The policy has no timer and no metrics until it is configured, so it must not start a
+ * heartbeat: the failure must be reported via the returned stage.
+ */
+ @Test
+ void testStartBeforeConfigureFails() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ final Throwable cause = assertFails(policy.start(view));
+ Assertions.assertInstanceOf(NullPointerException.class, cause);
+ }
+
+ /**
+ * Checks that the startup of a policy configured without a timer fails.
+ *
+ * The timer is guaranteed to be non-null by the library, so the policy must not work without
+ * it, but it must fail gracefully via the returned stage.
+ */
+ @Test
+ void testStartWithNullTimerFails() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ Assertions.assertThrows(NullPointerException.class, () -> policy.configure(null, null));
+ }
+
+ /**
+ * Checks that the startup with a null view fails.
+ *
+ * The view is never null by the contract of the library, so the policy must not work with it,
+ * but it must fail gracefully via the returned stage.
+ */
+ @Test
+ void testStartWithNullViewFails() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+
+ policy.configure(timer, registry);
+ final Throwable cause = assertFails(policy.start(null));
+ Assertions.assertInstanceOf(NullPointerException.class, cause);
+ }
+
+ /**
+ * Checks that the repeated configuration keeps the timer of the first one.
+ *
+ * The policy is configured once per pool, so the repeated configuration is not expected, but
+ * it must not break the already configured policy: the timer of the first configuration stays in
+ * use.
+ */
+ @Test
+ void testRepeatedConfigureKeepsFirstTimer() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view =
+ RecordingPoolEntryView.create(TAG, IDX, policy, StubClient.create().client());
+
+ final FakeTimer second = new FakeTimer();
+
+ policy.configure(timer, registry);
+ policy.configure(second, registry);
+
+ assertSucceeds(policy.start(view));
+
+ Assertions.assertEquals(
+ 1, timer.pendingCount(), "The policy must use the timer of the first configuration");
+ Assertions.assertEquals(
+ 0, second.pendingCount(), "The policy must ignore the second configuration");
+ }
+
+ /**
+ * Checks that the repeated configuration keeps the metrics of the first one.
+ *
+ * The counters of the second registry are registered, but they are never incremented, because
+ * the policy works with the metrics of the first configuration.
+ */
+ @Test
+ void testRepeatedConfigureKeepsFirstRegistry() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+ final MeterRegistry second = new SimpleMeterRegistry();
+
+ policy.configure(timer, registry);
+ policy.configure(timer, second);
+
+ assertSucceeds(policy.start(view));
+ timer.fireNext();
+
+ Assertions.assertEquals(
+ 1,
+ registry.counter(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).count(),
+ "The first registry is in use");
+ Assertions.assertEquals(
+ 0,
+ second.counter(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).count(),
+ "The second registry is not in use");
+ }
+
+ /** Checks that the metrics of the policy are registered in the given registry. */
+ @Test
+ void testMetricsAreRegistered() {
+ final DefaultAvailabilityPolicy policy = policy();
+
+ policy.configure(timer, registry);
+
+ Assertions.assertNotNull(registry.find(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).counter());
+ Assertions.assertNotNull(registry.find(HeartbeatConstants.POOL_HEARTBEAT_ERRORS).counter());
+ Assertions.assertNotNull(registry.find(HeartbeatConstants.POOL_HEARTBEAT_TIME).longTaskTimer());
+ }
+
+ /**
+ * Checks that the policy works without the metrics.
+ *
+ * The registry is passed only if the client has specified one, so the policy must not fail
+ * without it and must not count the heartbeats.
+ */
+ @Test
+ void testStartWithoutMetrics() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(timer, null);
+
+ assertSucceeds(policy.start(view));
+ timer.fireNext();
+
+ Assertions.assertEquals(1, timer.firedCount());
+ }
+
+ /**
+ * Checks that the repeated startup of the same connection succeeds.
+ *
+ * The policy is started once per connection, so the repeated startup is not expected, but it
+ * must not fail and must not start a second heartbeat.
+ */
+ @Test
+ void testRepeatedStartSucceeds() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(timer, registry);
+
+ final List The stop must be idempotent, so the repeated shutdown of the same connection must not fail.
+ */
+ @Test
+ void testRepeatedStopSucceeds() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(timer, registry);
+ assertSucceeds(policy.start(view));
+
+ for (int i = 0; i < 10; i++) {
+ assertSucceeds(policy.stop(view));
+ }
+ Assertions.assertEquals(
+ 0, timer.pendingCount(), "The pending ping must be cancelled by the shutdown");
+ }
+
+ /**
+ * Checks that {@code stop()} can be called on a newly created policy object without exceptions.
+ *
+ * The library stops the policy if its startup has failed, so closing a policy that has not
+ * been started must not fail.
+ */
+ @Test
+ void testStopWithoutStartSucceeds() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(timer, registry);
+
+ assertSucceeds(policy.stop(view));
+
+ Assertions.assertTrue(view.calls().isEmpty(), "The policy must not touch the connection");
+ }
+
+ /**
+ * Checks that the policy may be started again after the shutdown.
+ *
+ * The library recycles a connection with a {@code stop -> start} sequence, so the policy must
+ * survive it.
+ */
+ @Test
+ void testStartAfterStopSucceeds() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(timer, registry);
+
+ assertSucceeds(policy.start(view));
+ assertSucceeds(policy.stop(view));
+ assertSucceeds(policy.start(view));
+
+ Assertions.assertEquals(
+ 2, timer.scheduledCount(), "The restarted heartbeat must schedule a new ping");
+ }
+
+ /**
+ * Checks that the shutdown with a cause invalidates the connection.
+ *
+ * The cause may be null, so it must not affect the outcome of the shutdown.
+ */
+ @Test
+ void testStopInvalidatesTheConnection() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(timer, registry);
+ assertSucceeds(policy.start(view));
+
+ assertSucceeds(policy.stop(view, new IllegalStateException("the connection is gone")));
+
+ Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state());
+ }
+
+ /**
+ * Checks that the lifecycles of the different connections are independent.
+ *
+ * The shutdown of one connection must not affect the other ones.
+ */
+ @Test
+ void testViewsAreIndependent() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView first = view(policy, StubClient.create());
+ final RecordingPoolEntryView second = view(policy, StubClient.create());
+
+ policy.configure(timer, registry);
+
+ assertSucceeds(policy.start(first));
+ assertSucceeds(policy.start(second));
+ Assertions.assertEquals(2, timer.pendingCount(), "Every connection must have its own ping");
+
+ assertSucceeds(policy.stop(first));
+
+ Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, first.state());
+ Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, second.state());
+ Assertions.assertEquals(
+ Collections.singletonList(HeartbeatConstants.ACTIVE_STATE_NAME),
+ second.stateChangeNames(),
+ "The shutdown of the first connection must not change the state of the second one");
+ Assertions.assertEquals(0, second.reconnectCallsCount());
+ Assertions.assertEquals(
+ 1, timer.pendingCount(), "Only the ping of the stopped connection must be cancelled");
+
+ // the heartbeat of the second connection keeps working
+ timer.fireNext();
+ Assertions.assertEquals(1, registry.counter(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).count());
+ Assertions.assertEquals(
+ 1, timer.pendingCount(), "The second connection must schedule the next ping");
+ }
+
+ /**
+ * Checks that the restart backoff is zero and does not touch the connection.
+ *
+ * The policy has no backoff, so the connection must be restarted immediately.
+ */
+ @Test
+ void testRestartBackoffIsZero() {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ final Duration backoff = policy.restartBackoff(view);
+
+ Assertions.assertEquals(Duration.ZERO, backoff);
+ Assertions.assertTrue(view.calls().isEmpty(), "The policy must not touch the connection");
+ }
+
+ /**
+ * Checks that the shutdown does not wait for a ping that has not been answered.
+ *
+ * The shutdown must complete in a bounded time even if the node is hung: the ping is in flight
+ * and is never answered, so the shutdown must not wait for the answer or for the request timeout.
+ * The stage is completed by the moment the shutdown returns, and the connection is invalidated.
+ *
+ * The late answer must not touch the stopped connection: it is neither a success nor a failure
+ * for the heartbeat, even a terminal error must not kill the connection that is already closed.
+ */
+ @Test
+ void testStopDoesNotWaitForHangingPing() {
+ assertStopCompletesWhilePingHangs(answer -> answer.complete(StubClient.emptyBodyResponse()));
+ }
+
+ /**
+ * Checks that the connection can be restarted after a failed startup.
+ *
+ * If the startup has failed, the machine of the connection stays in the policy in the stopped
+ * state, so the repeated startup fails until the library stops the policy. The library stops the
+ * policy after every failed startup, so after the shutdown the next startup must succeed with a
+ * brand-new machine.
+ */
+ @Test
+ void testStartAfterFailedStartAndStopSucceeds() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ policy.configure(new FlakyTimer(timer, 1), registry);
+
+ // the timer fails while the first ping is being scheduled
+ final Throwable startCause = assertFails(policy.start(view));
+ Assertions.assertInstanceOf(HeartbeatException.class, startCause);
+ Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state());
+ Assertions.assertTrue(
+ view.listener().events().isEmpty(),
+ "The failed startup must not be reported as activation");
+ Assertions.assertEquals(0, timer.pendingCount(), "The failed startup must not leave a ping");
+
+ // the dead machine is still registered: the startup without the shutdown is rejected
+ Assertions.assertInstanceOf(HeartbeatClosedException.class, assertFails(policy.start(view)));
+
+ // the library stops the policy after the failed startup: the entry must be released
+ assertSucceeds(policy.stop(view));
+
+ assertSucceeds(policy.start(view));
+
+ Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, view.state());
+ Assertions.assertEquals(
+ Collections.singletonList("onHeartbeatEvent:ACTIVATE"), view.listener().events());
+ Assertions.assertEquals(1, timer.scheduledCount(), "The new machine must schedule the ping");
+ Assertions.assertEquals(1, timer.pendingCount());
+ }
+
+ /** Checks that the policy cannot be created without the heartbeat options. */
+ @Test
+ void testConstructorRejectsNullOptions() {
+ final IllegalArgumentException ex =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new DefaultAvailabilityPolicy(null));
+ Assertions.assertEquals("Heartbeat options must not be null!", ex.getMessage());
+ }
+
+ /**
+ * Checks that the options of the policy are passed to the machines of the connections.
+ *
+ * The initial delay is the only option that is observable right after the startup: it is the
+ * delay of the first scheduled ping.
+ */
+ @Test
+ void testInitialDelayOfOptionsIsApplied() throws Exception {
+ final Duration initialDelay = Duration.ofMillis(777);
+ final DefaultAvailabilityPolicy policy =
+ new DefaultAvailabilityPolicy(HeartbeatOpts.getDefault().withInitialDelay(initialDelay));
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+ policy.configure(timer, registry);
+
+ assertSucceeds(policy.start(view));
+
+ Assertions.assertEquals(initialDelay.toMillis(), timer.lastScheduled().delayMillis());
+ }
+
+ /**
+ * Checks that the thresholds of the options are applied: the connection is invalidated and killed
+ * exactly as the options of the policy say.
+ */
+ @Test
+ void testThresholdsOfOptionsAreApplied() throws Exception {
+ final DefaultAvailabilityPolicy policy =
+ new DefaultAvailabilityPolicy(
+ HeartbeatOpts.getDefault()
+ .withWindowSize(1)
+ .withInvalidationThreshold(1)
+ .withDeathThreshold(1));
+ final RecordingPoolEntryView view =
+ view(policy, StubClient.failing(new RuntimeException("the node does not answer")));
+ policy.configure(timer, registry);
+ assertSucceeds(policy.start(view));
+
+ timer.fireNext();
+ Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state());
+ Assertions.assertEquals(0, view.reconnectCallsCount(), "The death threshold is not reached");
+
+ timer.fireNext();
+ Assertions.assertSame(HeartbeatConstants.KILL_STATE, view.state());
+ Assertions.assertEquals(1, view.reconnectCallsCount());
+ }
+
+ /**
+ * Checks that a failed startup of an unconfigured policy does not break the policy.
+ *
+ * The machine cannot be created before the policy is configured, so nothing must be registered
+ * for the connection. After the configuration the same connection must start normally, without
+ * the shutdown in between.
+ */
+ @Test
+ void testStartAfterFailedStartBeforeConfigureSucceeds() throws Exception {
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+
+ final Throwable cause = assertFails(policy.start(view));
+ Assertions.assertInstanceOf(NullPointerException.class, cause);
+ Assertions.assertTrue(
+ view.calls().isEmpty(), "The failed startup must not touch the connection");
+ Assertions.assertEquals(0, timer.scheduledCount(), "The failed startup must not ping");
+
+ policy.configure(timer, registry);
+
+ assertSucceeds(policy.start(view));
+
+ Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, view.state());
+ Assertions.assertEquals(
+ Collections.singletonList("onHeartbeatEvent:ACTIVATE"), view.listener().events());
+ Assertions.assertEquals(1, timer.scheduledCount());
+ Assertions.assertEquals(1, timer.pendingCount());
+ }
+
+ /**
+ * Checks that a terminal failure of the hanging ping, that comes after the shutdown, is ignored.
+ *
+ * @see #testStopDoesNotWaitForHangingPing()
+ */
+ @Test
+ void testTerminalFailureOfHangingPingAfterStopIsIgnored() {
+ assertStopCompletesWhilePingHangs(
+ answer -> answer.completeExceptionally(new ConnectionException("the connection is dead")));
+ }
+
+ /**
+ * Checks that the concurrent configuration is applied once.
+ *
+ * All the threads try to configure the policy with their own timer, but only one timer must
+ * win: the connection that starts afterwards schedules its ping with it and with no other.
+ */
+ @Test
+ void testConcurrentConfigureAppliesOneTimer() throws Exception {
+ final int threads = 16;
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+ final List The machine is created by {@code computeIfAbsent}, so all the callers must share it.
+ */
+ @Test
+ void testConcurrentStartsOfTheSameConnectionShareOneMachine() throws Exception {
+ final int threads = 16;
+ final DefaultAvailabilityPolicy policy = policy();
+ final RecordingPoolEntryView view = view(policy, StubClient.create());
+ policy.configure(timer, registry);
+ final List Every task reports that it has started and then waits for the common gate, so the gate is
+ * opened only when all the threads are really running.
+ */
+ private static void runConcurrently(int threads, IntConsumer action) throws Exception {
+ final ExecutorService executor = Executors.newFixedThreadPool(threads);
+ final CompletableFuture