From 0e96b40cf0f4bc745f858cc4507d8af519e6ff69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=91=D0=B5?= =?UTF-8?q?=D0=BB=D0=BE=D0=BD=D0=BE=D0=B3=D0=BE=D0=B2?= Date: Tue, 17 Nov 2026 13:00:40 +0300 Subject: [PATCH 1/3] feat(heartbeat): add the HeartbeatStateMachine An implementation of the `HeartbeatMachine` has been added; it serves as a redesigned version of the heartbeat mechanism used in `PoolEntry`. This implementation utilizes an event-driven state machine based on: - `io.tarantool.core.state.AbstractDrainLoopMachine.java` - `io.tarantool.core.state.Event` - `io.tarantool.core.state.State` --- .../java/io/tarantool/core/utils/CFUtils.java | 44 ++++ .../{PolicyEvent.java => HeartbeatEvent.java} | 41 ++-- .../heartbeat/HeartbeatState.java | 94 +++++++ .../heartbeat/HeartbeatStateMachine.java | 180 ++++++++++++++ .../availability/heartbeat/InitialState.java | 52 ++++ .../availability/heartbeat/RunningState.java | 197 +++++++++++++++ .../availability/heartbeat/StoppedState.java | 29 +++ .../pool/availability/heartbeat/Utils.java | 113 +++++++++ .../schemas/availability-policy.puml | 231 ++++++++++++++++++ 9 files changed, 964 insertions(+), 17 deletions(-) create mode 100644 tarantool-core/src/main/java/io/tarantool/core/utils/CFUtils.java rename tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/{PolicyEvent.java => HeartbeatEvent.java} (71%) create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachine.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/InitialState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/RunningState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StoppedState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/Utils.java create mode 100644 tarantool-pooling/src/main/resources/schemas/availability-policy.puml diff --git a/tarantool-core/src/main/java/io/tarantool/core/utils/CFUtils.java b/tarantool-core/src/main/java/io/tarantool/core/utils/CFUtils.java new file mode 100644 index 00000000..b55667fe --- /dev/null +++ b/tarantool-core/src/main/java/io/tarantool/core/utils/CFUtils.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.core.utils; + +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; + +/** A class containing utility methods to work with {@link CompletionStage}. */ +public final class CFUtils { + + private CFUtils() {} + + public static void linkFuture(CompletionStage root, CompletionStage linkable) { + if (linkable == null) { + return; + } + + root.whenComplete( + (r, e) -> { + if (e == null) { + linkable.toCompletableFuture().complete(r); + } else { + final Throwable unwrap = unwrap(e); + linkable.toCompletableFuture().completeExceptionally(unwrap); + } + }); + } + + public static Throwable unwrap(Throwable throwable) { + if (throwable == null) { + return null; + } + Throwable current = throwable; + while ((current instanceof CompletionException || current instanceof ExecutionException) + && current.getCause() != null) { + current = current.getCause(); + } + return current; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyEvent.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatEvent.java similarity index 71% rename from tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyEvent.java rename to tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatEvent.java index 507a46f9..fc5c40ed 100644 --- a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyEvent.java +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatEvent.java @@ -10,11 +10,11 @@ import io.tarantool.core.protocol.IProtoResponse; import io.tarantool.core.state.Event; -abstract class PolicyEvent implements Event { +abstract class HeartbeatEvent implements Event { private final String name; - PolicyEvent(String name) { + HeartbeatEvent(String name) { this.name = name; } @@ -23,7 +23,7 @@ public String toString() { return this.name; } - static final class StartEvent extends PolicyEvent { + static final class StartEvent extends HeartbeatEvent { private final CompletableFuture startFuture; @@ -38,7 +38,7 @@ CompletableFuture startFuture() { } /** An event sent when a response to a ping request is received. */ - static final class PongEvent extends PolicyEvent { + static final class PongEvent extends HeartbeatEvent { private final IProtoResponse response; @@ -62,15 +62,16 @@ Throwable exception() { /** * An event sent when the ping timer expires, indicating that a ping request should be dispatched. */ - static final class SendPingEvent extends PolicyEvent { - static final PolicyEvent INSTANCE = new SendPingEvent(); + static final class SendPingEvent extends HeartbeatEvent { + + static final HeartbeatEvent INSTANCE = new SendPingEvent(); private SendPingEvent() { super("HEARTBEAT_SEND_PING_EVT"); } } - static final class StopEvent extends PolicyEvent implements Control { + static final class StopEvent extends Control { private final CompletableFuture closeFuture; @@ -96,8 +97,9 @@ Throwable cause() { * HeartbeatConstants#ACTIVE_STATE}. That is, to make the connection available to the load * balancer. */ - static final class ActivateEvent extends PolicyEvent implements Control { - static final PolicyEvent INSTANCE = new ActivateEvent(); + static final class ActivateEvent extends Control { + + static final HeartbeatEvent INSTANCE = new ActivateEvent(); private ActivateEvent() { super("HEARTBEAT_ACTIVATE_EVT"); @@ -109,8 +111,9 @@ private ActivateEvent() { * HeartbeatConstants#INVALIDATE_STATE}. That is, this connection is no longer available to the * load balancer. */ - static final class InvalidateEvent extends PolicyEvent implements Control { - static final PolicyEvent INSTANCE = new InvalidateEvent(); + static final class InvalidateEvent extends Control { + + static final HeartbeatEvent INSTANCE = new InvalidateEvent(); private InvalidateEvent() { super("HEARTBEAT_INVALIDATE_EVT"); @@ -121,9 +124,9 @@ private InvalidateEvent() { * An event sent when the connection state changes to {@link HeartbeatConstants#KILL_STATE}, * signaling that the connection must be reconnected. */ - static final class KillEvent extends PolicyEvent implements Control { + static final class KillEvent extends Control { - static final PolicyEvent INSTANCE = new KillEvent(); + static final HeartbeatEvent INSTANCE = new KillEvent(); private KillEvent() { super("HEARTBEAT_KILL_EVT"); @@ -131,13 +134,17 @@ private KillEvent() { } /** - * A marker interface. All event classes implementing this interface act as control signals and - * have the highest priority over regular events. + * A marker class. All event classes extending this class act as control signals and have the + * highest priority over regular events. */ - private interface Control extends Event { + private abstract static class Control extends HeartbeatEvent { + + Control(String name) { + super(name); + } @Override - default boolean isControl() { + public final boolean isControl() { return true; } } diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatState.java new file mode 100644 index 00000000..f13439c8 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatState.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.core.state.State; +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StopEvent; + +/** + * The base class of the internal states of the default availability policy. A state works with the + * machine and with its context without any restrictions. + */ +abstract class HeartbeatState implements State { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + protected final HeartbeatStateMachine machine; + private final String name; + + HeartbeatState(HeartbeatStateMachine machine, String name) { + this.machine = machine; + this.name = name; + } + + @Override + public void handle(HeartbeatEvent event) { + if (event == null) { + this.logger.debug("[{}][{}]: got a null event. Skipping...", machine.identity(), this); + return; + } + this.logger.debug("[{}][{}]: received '{}' event", machine.identity(), this, event); + + if (event instanceof StartEvent) onStart((StartEvent) event); + else if (event instanceof StopEvent) onStop((StopEvent) event); + else if (event instanceof SendPingEvent) onSendPing((SendPingEvent) event); + else if (event instanceof PongEvent) onPong((PongEvent) event); + else if (event instanceof ActivateEvent) onActivate((ActivateEvent) event); + else if (event instanceof InvalidateEvent) onInvalidate((InvalidateEvent) event); + else if (event instanceof KillEvent) onKill((KillEvent) event); + else + this.logger.debug( + "[{}][{}]: received an unexpected '{}' event", machine.identity(), this, event); + } + + protected void onStart(StartEvent e) {} + + protected void onStop(StopEvent e) {} + + protected void onSendPing(SendPingEvent e) {} + + protected void onPong(PongEvent e) {} + + protected void onActivate(ActivateEvent e) {} + + protected void onInvalidate(InvalidateEvent e) {} + + protected void onKill(KillEvent e) {} + + protected final void logStartHandleEvent(HeartbeatEvent event) { + this.logger.debug("[{}][{}]: start handle '{}' event", this.machine.identity(), this, event); + } + + protected final void transitionTo(HeartbeatState nextState) { + this.machine.state(nextState); + this.logger.debug( + "[{}][{}]: transitioned to '{}' state", this.machine.identity(), this, nextState); + } + + protected final void completeStop(StopEvent event) { + CFUtils.linkFuture(machine.rootCloseFuture(), event.closeFuture()); + if (event.cause() != null) { + this.logger.debug( + "[{}][{}]: stop policy with cause", machine.identity(), this, event.cause()); + } + this.machine.rootCloseFuture().complete(null); + } + + @Override + public String toString() { + return this.name; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachine.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachine.java new file mode 100644 index 00000000..5ae06ddf --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachine.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import io.netty.util.Timeout; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.core.protocol.IProtoRequestOpts; +import io.tarantool.core.state.AbstractDrainLoopMachine; +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.exceptions.HeartbeatException; + +/** + * The internal state machine of the default availability policy. It is not a part of the public + * API: the client must not have access to the machine, its states and its context. + */ +final class HeartbeatStateMachine extends AbstractDrainLoopMachine { + + private static final Logger LOGGER = LoggerFactory.getLogger(HeartbeatStateMachine.class); + + private final PoolEntryView view; + private final Utils utils; + private final HeartbeatOpts heartbeatOpts; + private final IProtoRequestOpts heartbeatPingOpts; + private final String identity; + + private final CompletableFuture rootCloseFuture = new CompletableFuture<>(); + private final CompletableFuture rootStartFuture = new CompletableFuture<>(); + private final HeartbeatCtx ctx; + private volatile HeartbeatState state = new InitialState(this); + + HeartbeatStateMachine(PoolEntryView view, HeartbeatOpts opts, Utils utils) { + this.view = Objects.requireNonNull(view, "view must not be null"); + this.heartbeatOpts = Objects.requireNonNull(opts, "HeartbeatOpts must not be null!"); + this.utils = Objects.requireNonNull(utils, "Policy is not configured!"); + Objects.requireNonNull(utils.timer(), "Timer must not be null!"); + + final Metadata metadata = view.metadata(); + this.identity = metadata.settings().getTag() + '/' + metadata.index(); + this.heartbeatPingOpts = IProtoRequestOpts.empty().withRequestTimeout(opts.getPingInterval()); + this.ctx = new HeartbeatCtx(new ArrayDeque<>(opts.getWindowSize())); + } + + @Override + protected void processEvent(HeartbeatEvent event) { + this.state.handle(event); + } + + @Override + protected void onHandleError(Throwable error) { + LOGGER.warn( + "[{}]: caught an unexpected error while handling an event. Stopping the machine and" + + " reconnecting...", + this, + error); + final boolean isStarted = + this.rootStartFuture.isDone() && !this.rootStartFuture.isCompletedExceptionally(); + if (isStarted) { + this.view.changeState(HeartbeatConstants.KILL_STATE); + handle(KillEvent.INSTANCE); + } else { + // The start has failed: do not leave a half-started machine (with a running ping timer) + // behind. Move to the closed state and release the context. + this.state = new StoppedState(this); + this.view.changeState(HeartbeatConstants.INVALIDATE_STATE); + this.ctx.clear(); + this.rootStartFuture.completeExceptionally( + new HeartbeatException("Got unexpected errors", error)); + } + } + + void state(HeartbeatState newState) { + this.state = newState; + } + + HeartbeatState state() { + return this.state; + } + + HeartbeatCtx ctx() { + return this.ctx; + } + + PoolEntryView view() { + return this.view; + } + + HeartbeatOpts opts() { + return this.heartbeatOpts; + } + + Utils utils() { + return this.utils; + } + + CompletableFuture rootCloseFuture() { + return this.rootCloseFuture; + } + + CompletableFuture rootStartFuture() { + return this.rootStartFuture; + } + + IProtoRequestOpts heartbeatPingRequestOpts() { + return this.heartbeatPingOpts; + } + + String identity() { + return this.identity; + } + + /** + * The mutable part of the machine state. It is shared between the states and must be accessible + * for them without any restrictions. + */ + final class HeartbeatCtx { + + final Deque window; + Timeout heartbeatTask; + int currentDeathPings; + int currentFailedPings; + + /** Monotonic ({@link System#nanoTime()}) timestamp of the last sent ping. */ + long lastPingNanos; + + io.tarantool.pool.HeartbeatEvent lastEvent; + + HeartbeatCtx(Deque window) { + this.window = window; + } + + void clear() { + cancelNextPingTimer(); + this.window.clear(); + this.heartbeatTask = null; + this.currentDeathPings = 0; + this.currentFailedPings = 0; + this.lastPingNanos = 0; + this.lastEvent = null; + } + + void cancelNextPingTimer() { + if (this.heartbeatTask != null) { + this.heartbeatTask.cancel(); + } + } + + void scheduleNextPing(long delta) { + cancelNextPingTimer(); + this.heartbeatTask = + utils + .timer() + .newTimeout(_u -> handle(SendPingEvent.INSTANCE), delta, TimeUnit.MILLISECONDS); + } + + void firstSuccess() { + this.window.clear(); + this.window.addFirst(0); + } + } + + @Override + public String toString() { + return '[' + this.identity + "][HeartbeatStateMachine]"; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/InitialState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/InitialState.java new file mode 100644 index 00000000..289c3e54 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/InitialState.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StopEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine.HeartbeatCtx; + +final class InitialState extends HeartbeatState { + + InitialState(HeartbeatStateMachine machine) { + super(machine, "HEARTBEAT_NEW"); + } + + @Override + protected void onStart(StartEvent event) { + logStartHandleEvent(event); + final HeartbeatOpts opts = machine.opts(); + this.logger.info( + "[{}][{}]: start heartbeat with [failures = {}, interval = {}, death pings = {}]", + this.machine.identity(), + this, + opts.getInvalidationThreshold(), + opts.getPingInterval(), + opts.getDeathThreshold()); + + final HeartbeatCtx ctx = this.machine.ctx(); + ctx.firstSuccess(); + + final HeartbeatState nextState = new RunningState(this.machine); + transitionTo(nextState); + CFUtils.linkFuture(this.machine.rootStartFuture(), event.startFuture()); + ctx.scheduleNextPing(opts.initialDelay().toMillis()); + nextState.handle(ActivateEvent.INSTANCE); + this.machine.rootStartFuture().complete(null); + } + + @Override + protected void onStop(StopEvent event) { + logStartHandleEvent(event); + this.machine.ctx().clear(); + transitionTo(new StoppedState(this.machine)); + this.machine.view().changeState(HeartbeatConstants.INVALIDATE_STATE); + completeStop(event); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/RunningState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/RunningState.java new file mode 100644 index 00000000..40976a00 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/RunningState.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import io.micrometer.core.instrument.LongTaskTimer; + +import io.tarantool.core.connection.exceptions.ConnectionException; +import io.tarantool.core.exceptions.ShutdownException; +import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.PoolEntryState; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StopEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine.HeartbeatCtx; + +final class RunningState extends HeartbeatState { + + RunningState(HeartbeatStateMachine machine) { + super(machine, "HEARTBEAT_STARTED"); + } + + @Override + protected void onStart(StartEvent event) { + logStartHandleEvent(event); + CFUtils.linkFuture(this.machine.rootStartFuture(), event.startFuture()); + } + + @Override + protected void onStop(StopEvent event) { + logStartHandleEvent(event); + transitionTo(new StoppedState(this.machine)); + this.machine.view().changeState(HeartbeatConstants.INVALIDATE_STATE); + this.machine.ctx().clear(); + completeStop(event); + this.logger.info("[{}][{}]: availability policy is stopped", machine.identity(), this); + } + + @Override + protected void onActivate(ActivateEvent event) { + emitStateChange( + event, + HeartbeatConstants.ACTIVE_STATE, + io.tarantool.pool.HeartbeatEvent.ACTIVATE, + "connection is OK"); + } + + @Override + protected void onInvalidate(InvalidateEvent event) { + emitStateChange( + event, + HeartbeatConstants.INVALIDATE_STATE, + io.tarantool.pool.HeartbeatEvent.INVALIDATE, + "connection is invalid"); + } + + @Override + protected void onKill(KillEvent event) { + transitionTo(new StoppedState(this.machine)); + this.machine.ctx().clear(); + emitStateChange( + event, HeartbeatConstants.KILL_STATE, io.tarantool.pool.HeartbeatEvent.KILL, null); + this.logger.warn("[{}][{}]: close connection", this.machine.identity(), this); + this.machine.view().reconnect(); + } + + @Override + protected void onSendPing(SendPingEvent event) { + logStartHandleEvent(event); + this.machine.ctx().lastPingNanos = System.nanoTime(); + final LongTaskTimer.Sample timer = this.machine.utils().beginHeartbeatTimeMetric(); + + CompletableFuture ping; + try { + ping = + Objects.requireNonNull( + this.machine + .opts() + .getPingFunction() + .apply(this.machine.view().client(), this.machine.heartbeatPingRequestOpts()), + "ping function returned null"); + } catch (Exception e) { + this.logger.debug( + "[{}][{}]: caught an error while sending the ping...", this.machine.identity(), this, e); + ping = new CompletableFuture<>(); + ping.completeExceptionally(e); + } + + ping.whenComplete( + (res, ex) -> { + this.machine.utils().finishHeartbeatTimeMetric(timer); + this.machine.handle(new PongEvent(res, ex)); + }); + } + + @Override + protected void onPong(PongEvent event) { + logStartHandleEvent(event); + final Throwable error = CFUtils.unwrap(event.exception()); + final int failure = + (error != null + || !PingResult.hasSuccessPingResult(event.response(), this.machine.identity())) + ? 1 + : 0; + + if (error != null) { + this.logger.debug( + "[{}][{}]: ping failed: {}", this.machine.identity(), this, event.exception().toString()); + } + this.machine.utils().incHeartbeatCounters(failure); + + if (isTerminalError(error)) { + this.logger.warn( + "[{}][{}]: connection is dead: {}", this.machine.identity(), this, error.toString()); + this.machine.handle(KillEvent.INSTANCE); + return; + } + + nextPing(); + final HeartbeatCtx ctx = machine.ctx(); + final HeartbeatOpts opts = machine.opts(); + + ctx.window.addFirst(failure); + ctx.currentFailedPings += failure; + if (ctx.window.size() > opts.getWindowSize()) { + ctx.currentFailedPings -= ctx.window.removeLast(); + } else if (ctx.window.size() < opts.getWindowSize()) { + return; + } + + if (ctx.currentFailedPings >= opts.getInvalidationThreshold()) { + compareWithLastAndSend(io.tarantool.pool.HeartbeatEvent.INVALIDATE, InvalidateEvent.INSTANCE); + if (++ctx.currentDeathPings > opts.getDeathThreshold()) { + compareWithLastAndSend(io.tarantool.pool.HeartbeatEvent.KILL, KillEvent.INSTANCE); + } + } else { + compareWithLastAndSend(io.tarantool.pool.HeartbeatEvent.ACTIVATE, ActivateEvent.INSTANCE); + ctx.currentDeathPings = 0; + } + } + + private void emitStateChange( + HeartbeatEvent event, + PoolEntryState viewState, + io.tarantool.pool.HeartbeatEvent hbEvent, + String infoMsg) { + logStartHandleEvent(event); + final PoolEntryView view = this.machine.view(); + final Metadata meta = view.metadata(); + view.changeState(viewState); + this.machine.ctx().lastEvent = hbEvent; + view.emit(l -> l.onHeartbeatEvent(meta.settings().getTag(), meta.index(), hbEvent)); + if (infoMsg != null) { + this.logger.info("[{}][{}]: {}", this.machine.identity(), this, infoMsg); + } + } + + private void nextPing() { + final long elapsed = + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - machine.ctx().lastPingNanos); + final long delta = machine.opts().getPingInterval() - elapsed; + if (delta <= 0) { + machine.handle(SendPingEvent.INSTANCE); + } else { + machine.ctx().scheduleNextPing(delta); + } + } + + private void compareWithLastAndSend( + io.tarantool.pool.HeartbeatEvent expectedLast, HeartbeatEvent eventToSend) { + if (machine.ctx().lastEvent != expectedLast) { + machine.handle(eventToSend); + } + } + + // TODO decide which exceptions are terminal + private static boolean isTerminalError(Throwable error) { + return error instanceof ConnectionException + || error instanceof ShutdownException + || error instanceof IllegalStateException + || error instanceof NullPointerException; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StoppedState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StoppedState.java new file mode 100644 index 00000000..4a37a5f5 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StoppedState.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StopEvent; +import io.tarantool.pool.availability.heartbeat.exceptions.HeartbeatClosedException; + +final class StoppedState extends HeartbeatState { + + StoppedState(HeartbeatStateMachine machine) { + super(machine, "HEARTBEAT_STOPPED"); + } + + @Override + protected void onStart(StartEvent event) { + logStartHandleEvent(event); + event.startFuture().completeExceptionally(new HeartbeatClosedException("Already closed!")); + } + + @Override + protected void onStop(StopEvent event) { + logStartHandleEvent(event); + completeStop(event); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/Utils.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/Utils.java new file mode 100644 index 00000000..f5dbe55a --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/Utils.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.LongTaskTimer; +import io.micrometer.core.instrument.MeterRegistry; +import io.netty.util.Timer; + +/** + * The internal context of the policy: the timer and the metrics shared between all the connections. + */ +final class Utils { + + private final Timer timer; + private final MeterRegistry metrics; + + /** Count of successful heartbeat ping requests. */ + private final Counter heartbeatSuccess; + + /** Count of failed heartbeat ping requests. */ + private final Counter heartbeatErrors; + + /** Time of ping request. */ + private final LongTaskTimer heartbeatTime; + + private Utils( + Timer timer, + MeterRegistry metrics, + Counter heartbeatSuccess, + Counter heartbeatErrors, + LongTaskTimer heartbeatTime) { + this.timer = timer; + this.metrics = metrics; + this.heartbeatSuccess = heartbeatSuccess; + this.heartbeatErrors = heartbeatErrors; + this.heartbeatTime = heartbeatTime; + } + + static Utils configure(Timer timer, MeterRegistry metrics) { + Counter heartbeatSuccess = null; + Counter heartbeatErrors = null; + LongTaskTimer heartbeatTime = null; + if (metrics != null) { + heartbeatSuccess = + Counter.builder(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS) + .description("Count of successful heartbeat ping requests") + .register(metrics); + + heartbeatErrors = + Counter.builder(HeartbeatConstants.POOL_HEARTBEAT_ERRORS) + .description("Count of failed heartbeat ping requests") + .register(metrics); + + heartbeatTime = + LongTaskTimer.builder(HeartbeatConstants.POOL_HEARTBEAT_TIME) + .description("Time of ping request") + .register(metrics); + } + + return new Utils(timer, metrics, heartbeatSuccess, heartbeatErrors, heartbeatTime); + } + + /** + * Creates timer span for time measurement. + * + * @return instance of {@code LongTaskTimer.Sample} + */ + LongTaskTimer.Sample beginHeartbeatTimeMetric() { + if (this.metrics == null) { + return null; + } + + return this.heartbeatTime.start(); + } + + /** + * If timer span is not null, stops time measurement. + * + * @param timer an instance of {@code LongTaskTimer.Sample} + */ + void finishHeartbeatTimeMetric(LongTaskTimer.Sample timer) { + if (timer == null) { + return; + } + + timer.stop(); + } + + /** + * Increments heartbeat related metrics. + * + * @param fail if ping is failed then this value is 1, otherwise this value is 0. + */ + void incHeartbeatCounters(int fail) { + if (this.metrics == null) { + return; + } + + if (fail != 0) { + heartbeatErrors.increment(); + } else { + heartbeatSuccess.increment(); + } + } + + Timer timer() { + return this.timer; + } +} diff --git a/tarantool-pooling/src/main/resources/schemas/availability-policy.puml b/tarantool-pooling/src/main/resources/schemas/availability-policy.puml new file mode 100644 index 00000000..720030ff --- /dev/null +++ b/tarantool-pooling/src/main/resources/schemas/availability-policy.puml @@ -0,0 +1,231 @@ +@startuml +skinparam linetype ortho +skinparam nodesep 100 +skinparam ranksep 100 + + + +interface io.tarantool.core.state.Event { + + boolean isControl() <> +} + +interface io.tarantool.core.state.State { + + void handle(E) +} + +interface io.tarantool.core.state.StateMachine { + + void handle(E) +} + +abstract class io.tarantool.core.state.AbstractDrainLoopMachine { + - controlEvents: Queue {readOnly} + - events: Queue {readOnly} + - wip: AtomicInteger {readOnly} + - safelyProcess(e: E): void + # {abstract} processEvent(E): void + # {abstract} onHandleError(Throwable): void + + handle(E): void +} + +io.tarantool.core.state.StateMachine ..> io.tarantool.core.state.Event: <> +io.tarantool.core.state.State ..> io.tarantool.core.state.Event: <> +io.tarantool.core.state.AbstractDrainLoopMachine ..|> io.tarantool.core.state.StateMachine + +enum io.tarantool.pool.HeartbeatEvent <> { + INVALIDATE + ACTIVATE + KILL +} + +abstract class io.tarantool.pool.availability.heartbeat.HeartbeatEvent <> { + - name: String + ~ HeartbeatEvent(String): <> +} + +abstract class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$Control <> { + + isControl(): boolean <> +} + +io.tarantool.pool.availability.heartbeat.HeartbeatEvent ..|> io.tarantool.core.state.Event +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$Control --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$StartEvent { + - startFuture: CompletableFuture {readOnly} + ~ StartEvent(CompletableFuture): <> + ~ startFuture(): CompletableFuture +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$PongEvent { + - response: IProtoResponse {readOnly} + - ex: Throwable {readOnly} + ~ PongEvent(IProtoResponse, Throwable): <> + ~ response(): IProtoResponse + ~ exception(): Throwable +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$SendPingEvent { + ~ {static} INSTANCE: HeartbeatEvent {readOnly} + - SendPingEvent(): <> +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$StopEvent { + - closeFuture: CompletableFuture {readOnly} + - cause: Throwable {readOnly} + ~ StopEvent(CompletableFuture, Throwable): <> + ~ closeFuture(): CompletableFuture + ~ cause(): Throwable +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$ActivateEvent { + ~ {static} INSTANCE: HeartbeatEvent {readOnly} + - ActivateEvent(): <> +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$InvalidateEvent { + ~ {static} INSTANCE: HeartbeatEvent {readOnly} + - InvalidateEvent(): <> +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatEvent$KillEvent { + ~ {static} INSTANCE: HeartbeatEvent {readOnly} + - KillEvent(): <> +} + +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$StartEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$SendPingEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$PongEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent + +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$KillEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent$Control +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$ActivateEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent$Control +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$InvalidateEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent$Control +io.tarantool.pool.availability.heartbeat.HeartbeatEvent$StopEvent --|> io.tarantool.pool.availability.heartbeat.HeartbeatEvent$Control + +abstract class io.tarantool.pool.availability.heartbeat.HeartbeatState { + # logger: Logger {readOnly} + # machine: HeartbeatStateMachine {readOnly} + - name: String {readOnly} + + handle(HeartbeatEvent): void + ~ HeartbeatState(machine: HeartbeatStateMachine, name: String): <> + # onStart(StartEvent): void + # onStop(StopEvent): void + # onSendPing(SendPingEvent): void + # onPong(PongEvent): void + # onActivate(ActivateEvent): void + # onInvalidate(InvalidateEvent): void + # onKill(KillEvent): void + # logStartHandleEvent(HeartbeatEvent): void + # transitionTo(HeartbeatState): void + # completeStop(StopEvent): void +} + +io.tarantool.pool.availability.heartbeat.HeartbeatState ..|> io.tarantool.core.state.State + +class io.tarantool.pool.availability.heartbeat.InitialState { + ~ InitialState(HeartbeatStateMachine): <> + # onStart(StartEvent): void + # onStop(StopEvent): void +} + +class io.tarantool.pool.availability.heartbeat.StoppedState { + ~ StoppedState(HeartbeatStateMachine): <> + # onStart(StartEvent): void + # onStop(StopEvent): void +} + +class io.tarantool.pool.availability.heartbeat.RunningState { + ~ RunningState(HeartbeatStateMachine): <> + # onStart(StartEvent): void + # onStop(StopEvent): void + # onActivate(ActivateEvent): void + # onInvalidate(InvalidateEvent): void + # onKill(KillEvent): void + # onSendPing(SendPingEvent): void + # onPong(PongEvent): void + - emitStateChange(HeartbeatEvent, PoolEntryState, io.tarantool.pool.HeartbeatEvent, String): void + - nextPing(): void + - sendIfNotLast(io.tarantool.pool.HeartbeatEvent, HeartbeatEvent): void + - {static} unwrap(Throwable): Throwable + - {static} isTerminalError(Throwable): boolean +} + +io.tarantool.pool.availability.heartbeat.InitialState --|> io.tarantool.pool.availability.heartbeat.HeartbeatState +io.tarantool.pool.availability.heartbeat.StoppedState --|> io.tarantool.pool.availability.heartbeat.HeartbeatState +io.tarantool.pool.availability.heartbeat.RunningState --|> io.tarantool.pool.availability.heartbeat.HeartbeatState + +class io.tarantool.pool.availability.heartbeat.Utils { + - timer: Timer + - metrics: MeterRegistry + - heartbeatSuccess: Counter + - heartbeatErrors: Counter + - heartbeatTime: LongTaskTimer + ~ {static} Utils configure(Timer,MeterRegistry) + - Utils(timer: Timer, metrics: MeterRegistry, heartbeatSuccess: Counter, + heartbeatErrors: Counter, heartbeatTime: LongTaskTimer): <> + ~ beginHeartbeatTimeMetric(): LongTaskTimer.Sample + ~ finishHeartbeatTimeMetric(time: LongTaskTimer.Sample): void + ~ incHeartbeatCounters(failures: int): void + ~ timer(): Timer +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine { + - utils: Utils + - heartbeatOpts: HeartbeatOpts + - heartbeatPingOpts: IProtoRequestOpts + - identity: String + - rootStartFuture: CompletableFuture {readOnly} + - rootCloseFuture: CompletableFuture {readOnly} + - ctx: HeartbeatCtx + - view: PoolEntryView + - state: HeartbeatState {volatile} + # processEvent(event: HeartbeatEvent): void + # onHandleError(ex: Throwable): void + ~ HeartbeatStateMachine(view: PoolEntryView, opts: HeartbeatOpts, utils: Utils): <> + ~ state(state: HeartbeatState): void + ~ state(): HeartbeatState + ~ ctx(): HeartbeatCtx + ~ view(): PoolEntryView + ~ opts(): HeartbeatOpts + ~ utils(): Utils + ~ rootCloseFuture(): CompletableFuture + ~ rootStartFuture(): CompletableFuture + ~ heartbeatPingRequestOpts(): IProtoRequestOpts + ~ identity(): String +} + +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine --> io.tarantool.pool.availability.heartbeat.Utils: <> +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine ..> io.tarantool.pool.availability.heartbeat.HeartbeatEvent: <> +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine <--> io.tarantool.pool.availability.heartbeat.HeartbeatState +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine --|> io.tarantool.core.state.AbstractDrainLoopMachine +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine *-- io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine$HeartbeatCtx +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine ..> io.tarantool.pool.availability.heartbeat.InitialState: <> +io.tarantool.pool.availability.heartbeat.HeartbeatState ..> io.tarantool.pool.availability.heartbeat.HeartbeatEvent: <> +io.tarantool.pool.availability.heartbeat.RunningState ..> io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine$HeartbeatCtx: <> +io.tarantool.pool.availability.heartbeat.RunningState ..> io.tarantool.pool.availability.heartbeat.PingResult: <> +io.tarantool.pool.availability.heartbeat.RunningState ..> io.tarantool.pool.HeartbeatEvent: <> +io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine$HeartbeatCtx --> io.tarantool.pool.HeartbeatEvent: lastEvent + +class io.tarantool.pool.availability.heartbeat.PingResult { + - {static} LOGGER: Logger {readOnly} + ~ {static} hasSuccessPingResult(IProtoResponse, String): boolean +} + +class io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine$HeartbeatCtx <> { + ~ window: Deque {readOnly} + ~ heartbeatTask: Timeout + ~ currentDeathPings: int + ~ currentFailedPings: int + ~ lastPingNanos: long + ~ lastEvent: io.tarantool.pool.HeartbeatEvent + ~ HeartbeatCtx(Deque): <> + ~ clear(): void + ~ cancelNextPingTimer(): void + ~ scheduleNextPing(long): void + ~ firstSuccess(): void +} +@enduml From bb820ebab22be13ff97e9f0f75319709a0f7fed0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=91=D0=B5?= =?UTF-8?q?=D0=BB=D0=BE=D0=BD=D0=BE=D0=B3=D0=BE=D0=B2?= Date: Tue, 17 Nov 2026 11:13:43 +0300 Subject: [PATCH 2/3] test(heartbeat): add state machine evaluation tests - Tests have been added to verify the functionality of the HeartbeatStateMachine state machine. --- .../heartbeat/HeartbeatStateMachineTest.java | 968 ++++++++++++++++++ 1 file changed, 968 insertions(+) create mode 100644 tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachineTest.java diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachineTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachineTest.java new file mode 100644 index 00000000..2b44c93c --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachineTest.java @@ -0,0 +1,968 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import io.netty.util.Timer; +import io.netty.util.TimerTask; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +import io.tarantool.core.connection.exceptions.ConnectionException; +import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.pool.HeartbeatEvent; +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StopEvent; +import io.tarantool.pool.availability.heartbeat.exceptions.HeartbeatClosedException; +import io.tarantool.pool.availability.heartbeat.exceptions.HeartbeatException; +import io.tarantool.pool.support.FakeTimer; +import io.tarantool.pool.support.RecordingPoolEntryView; +import io.tarantool.pool.support.StubClient; + +/** + * The unit tests of the {@link HeartbeatStateMachine}: the transitions between the states and the + * completion of the lifecycle futures. + * + *

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 startFuture = new CompletableFuture<>(); + + machine.handle(new StartEvent(startFuture)); + + Assertions.assertInstanceOf(RunningState.class, machine.state()); + Assertions.assertTrue(startFuture.isDone(), "The start future must be completed"); + Assertions.assertFalse( + startFuture.isCompletedExceptionally(), "The startup must be successful"); + } + + /** + * Checks that the startup schedules exactly one ping. + * + *

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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + Assertions.assertEquals(1, timer.scheduledCount(), "Exactly one ping must be scheduled"); + Assertions.assertEquals(1, timer.pendingCount(), "The scheduled ping must be pending"); + Assertions.assertDoesNotThrow(startFuture::join); + } + + /** + * Checks that the first ping is scheduled with the initial delay. + * + *

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 cf = new CompletableFuture<>(); + machine.handle(new StartEvent(cf)); + + Assertions.assertDoesNotThrow(cf::join); + Assertions.assertEquals(1, timer.scheduledCount()); + Assertions.assertEquals( + INITIAL_DELAY.toMillis(), + timer.lastScheduled().delayMillis(), + "The first ping must be delayed by the initial delay"); + } + + /** + * Checks that the startup clears the window of the pings and fills it with the connection. + * + *

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 testStartFillsWindowWithConnection() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + + final CompletableFuture cf = new CompletableFuture<>(); + machine.handle(new StartEvent(cf)); + + Assertions.assertDoesNotThrow(cf::join); + Assertions.assertEquals( + 1, machine.ctx().window.size(), "The window must hold the mark of the connection"); + final Integer first = machine.ctx().window.peekFirst(); + Assertions.assertNotNull(first); + Assertions.assertEquals(0, first.intValue(), "The established connection must be a success"); + Assertions.assertEquals(0, machine.ctx().currentFailedPings); + Assertions.assertEquals(0, machine.ctx().currentDeathPings); + } + + /** + * Checks that the shutdown of a machine that has not been started stops it. + * + *

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 testStopBeforeStartStopsMachine() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + final CompletableFuture closeFuture = new CompletableFuture<>(); + + machine.handle(new StopEvent(closeFuture, null)); + + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertSame( + HeartbeatConstants.INVALIDATE_STATE, view.state(), "The connection must be invalidated"); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertFalse( + closeFuture.isCompletedExceptionally(), "The shutdown must be successful"); + Assertions.assertEquals( + 0, timer.scheduledCount(), "The machine must not start the heartbeat on the shutdown"); + } + + /** + * Checks that the shutdown of a started machine stops the heartbeat. + * + *

The pending ping must be cancelled, otherwise the machine would keep the connection busy + * after the shutdown. + */ + @Test + void testStopCancelsPendingPing() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + final CompletableFuture cf = new CompletableFuture<>(); + machine.handle(new StartEvent(cf)); + Assertions.assertEquals(1, timer.pendingCount(), "The ping must be scheduled"); + Assertions.assertDoesNotThrow(cf::join); + + final CompletableFuture closeFuture = new CompletableFuture<>(); + machine.handle(new StopEvent(closeFuture, null)); + + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertFalse(closeFuture.isCompletedExceptionally()); + Assertions.assertEquals(0, timer.pendingCount(), "The pending ping must be cancelled"); + } + + /** + * Checks that the repeated shutdown of the same machine is harmless. + * + *

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 cf = new CompletableFuture<>(); + machine.handle(new StartEvent(cf)); + + Assertions.assertDoesNotThrow(cf::join); + final CompletableFuture firstClose = new CompletableFuture<>(); + machine.handle(new StopEvent(firstClose, null)); + + final CompletableFuture secondClose = new CompletableFuture<>(); + machine.handle(new StopEvent(secondClose, null)); + + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertTrue(firstClose.isDone()); + Assertions.assertTrue(secondClose.isDone(), "The repeated shutdown must complete the future"); + Assertions.assertFalse(secondClose.isCompletedExceptionally()); + Assertions.assertEquals( + 2, view.stateChanges().size(), "The connection must be touched only once"); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + } + + /** + * Checks that the startup of a stopped machine fails. + * + *

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 startCf = new CompletableFuture<>(); + machine.handle(new StartEvent(startCf)); + + final CompletableFuture closeFuture = new CompletableFuture<>(); + machine.handle(new StopEvent(closeFuture, null)); + + final CompletableFuture startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + Assertions.assertDoesNotThrow(startCf::join); + Assertions.assertDoesNotThrow(closeFuture::join); + + final Throwable cause = assertFails(startFuture); + Assertions.assertInstanceOf(HeartbeatClosedException.class, cause); + Assertions.assertEquals("Already closed!", cause.getMessage()); + } + + /** + * Checks that the events of a running heartbeat are ignored before the startup. + * + *

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(InitialState.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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + CompletableFuture closeFuture = new CompletableFuture<>(); + machine.handle(new StopEvent(closeFuture, null)); + + final int callsAfterStop = view.calls().size(); + + 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(StoppedState.class, machine.state()); + Assertions.assertEquals( + callsAfterStop, view.calls().size(), "The connection must not be touched"); + Assertions.assertEquals(0, timer.pendingCount(), "The machine must not schedule the pings"); + } + + /** + * Checks that a null event is ignored. + * + *

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(InitialState.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 InitialState(machine).toString()); + Assertions.assertEquals("HEARTBEAT_STARTED", new RunningState(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 testConcurrentStartsStartHeartbeatOnce() 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> startFutures = new ArrayList<>(); + final ExecutorService executor = Executors.newFixedThreadPool(starters); + try { + for (int i = 0; i < starters; i++) { + final CompletableFuture startFuture = new CompletableFuture<>(); + startFutures.add(startFuture); + executor.submit( + () -> { + ready.countDown(); + go.await(); + machine.handle(new StartEvent(startFuture)); + return null; + }); + } + Assertions.assertTrue(ready.await(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + go.countDown(); + for (final CompletableFuture startFuture : startFutures) { + startFuture.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + } finally { + executor.shutdownNow(); + } + + Assertions.assertInstanceOf(RunningState.class, machine.state()); + Assertions.assertEquals(1, timer.scheduledCount(), "Only one heartbeat must be started"); + Assertions.assertEquals(1, timer.pendingCount(), "Only one ping must be scheduled"); + } + + /** + * Checks that the shutdown preempts the events that are waiting in the queue. + * + *

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 testStopPreemptsQueuedEvents() 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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + // the ping blocks the machine, so the events below are queued + final Thread pingThread = new Thread(() -> machine.handle(SendPingEvent.INSTANCE)); + pingThread.start(); + Assertions.assertTrue(pingStarted.await(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + + final CompletableFuture closeFuture = new CompletableFuture<>(); + machine.handle(new PongEvent(null, new ConnectionException("the connection is dead"))); + machine.handle(new StopEvent(closeFuture, null)); + + releasePing.countDown(); + pingThread.join(TIMEOUT.toMillis()); + Assertions.assertFalse(pingThread.isAlive(), "The machine must process the queued events"); + + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertEquals( + 0, view.reconnectCallsCount(), "The queued pong must not kill the stopped connection"); + Assertions.assertEquals( + 0, view.listener().heartbeatEventCount(HeartbeatEvent.KILL), "The kill must not happen"); + } + + /** + * Checks that the activation is reported to the listener. + * + *

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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + Assertions.assertDoesNotThrow(startFuture::join); + + Assertions.assertEquals( + Collections.singletonList("onHeartbeatEvent:ACTIVATE"), view.listener().events()); + Assertions.assertEquals(0, timer.firedCount(), "The activation must not wait for a ping"); + + timer.fireNext(); + timer.fireNext(); + timer.fireNext(); + + final RecordingPoolEntryView.RecordingPoolEventListener listener = view.listener(); + Assertions.assertEquals( + Collections.singletonList("onHeartbeatEvent:ACTIVATE"), listener.events()); + Assertions.assertEquals(1, listener.heartbeatEventCount(HeartbeatEvent.ACTIVATE)); + Assertions.assertEquals( + 0, + listener.connectionOpenedCount(), + "The policy must not report the opening of the connection"); + Assertions.assertEquals( + Collections.singletonList(HeartbeatConstants.ACTIVE_STATE_NAME), view.stateChangeNames()); + Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, view.state()); + } + + /** + * Checks that the activation is reported before the startup is reported to the library. + * + *

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 testActivateIsEmittedBeforeStartupIsReported() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + final CompletableFuture startFuture = new CompletableFuture<>(); + final AtomicBoolean activatedBeforeStartup = new AtomicBoolean(false); + startFuture.whenComplete( + (unused, error) -> + activatedBeforeStartup.set( + view.listener().heartbeatEventCount(HeartbeatEvent.ACTIVATE) == 1)); + + machine.handle(new StartEvent(startFuture)); + + Assertions.assertDoesNotThrow(startFuture::join); + Assertions.assertTrue( + activatedBeforeStartup.get(), "The activation must be reported before the startup"); + } + + /** + * Checks that the policy reports no events of the physical connection. + * + *

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 testPolicyDoesNotReportConnectionEvents() { + 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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + Assertions.assertDoesNotThrow(startFuture::join); + + // the first ping fails, the second one succeeds and the next ones fail again + timer.fireNext(); + timer.fireNext(); + timer.fireNext(); + timer.fireNext(); + timer.fireNext(); + + final RecordingPoolEntryView.RecordingPoolEventListener listener = view.listener(); + Assertions.assertEquals( + 0, + listener.connectionOpenedCount(), + "The policy must not report the opening of the connection"); + Assertions.assertEquals( + 0, + listener.connectionClosedCount(), + "The policy must not report the closing of the connection"); + Assertions.assertEquals( + 0, + listener.connectionFailedCount(), + "The policy must not report the failure of the connection"); + Assertions.assertEquals( + 0, + listener.reconnectScheduledCount(), + "The policy must not report the scheduled reconnect"); + Assertions.assertEquals( + Arrays.asList( + "onHeartbeatEvent:ACTIVATE", + "onHeartbeatEvent:INVALIDATE", + "onHeartbeatEvent:ACTIVATE", + "onHeartbeatEvent:INVALIDATE", + "onHeartbeatEvent:KILL"), + listener.events(), + "The policy reports the heartbeat events only"); + Assertions.assertEquals( + 1, view.reconnectCallsCount(), "The policy asks the library to restart the connection"); + } + + /** + * Checks that the invalidation is reported to the listener. + * + *

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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + timer.fireNext(); + timer.fireNext(); + + final RecordingPoolEntryView.RecordingPoolEventListener listener = view.listener(); + Assertions.assertEquals( + Arrays.asList("onHeartbeatEvent:ACTIVATE", "onHeartbeatEvent:INVALIDATE"), + listener.events()); + Assertions.assertEquals(1, listener.heartbeatEventCount(HeartbeatEvent.INVALIDATE)); + Assertions.assertEquals( + 0, + listener.connectionOpenedCount(), + "The policy must not report the opening of the connection"); + Assertions.assertEquals( + Arrays.asList( + HeartbeatConstants.ACTIVE_STATE_NAME, HeartbeatConstants.INVALIDATE_STATE_NAME), + view.stateChangeNames()); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + } + + /** + * Checks that the kill is reported to the listener and that the restart is requested after it. + * + *

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 testKillEventIsEmittedAndRestartIsRequested() { + 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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + timer.fireNext(); + + final RecordingPoolEntryView.RecordingPoolEventListener listener = view.listener(); + Assertions.assertEquals( + Arrays.asList( + "onHeartbeatEvent:ACTIVATE", "onHeartbeatEvent:INVALIDATE", "onHeartbeatEvent:KILL"), + listener.events()); + Assertions.assertEquals(1, listener.heartbeatEventCount(HeartbeatEvent.KILL)); + Assertions.assertEquals( + Arrays.asList( + HeartbeatConstants.ACTIVE_STATE_NAME, + HeartbeatConstants.INVALIDATE_STATE_NAME, + HeartbeatConstants.KILL_STATE_NAME), + view.stateChangeNames()); + Assertions.assertSame(HeartbeatConstants.KILL_STATE, view.state()); + Assertions.assertEquals( + Arrays.asList( + "changeState:" + HeartbeatConstants.ACTIVE_STATE_NAME, + "emit", + "client", + "changeState:" + HeartbeatConstants.INVALIDATE_STATE_NAME, + "emit", + "client", + "changeState:" + HeartbeatConstants.KILL_STATE_NAME, + "emit", + "reconnect"), + view.calls(), + "The restart must be requested after the kill event has been delivered"); + Assertions.assertEquals(1, view.reconnectCallsCount(), "The restart must be requested once"); + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + } + + /** + * Checks that a null returned by the ping function is handled as a failed ping. + * + *

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 testNullPingKillsConnection() { + final HeartbeatStateMachine machine = + machine(HeartbeatOpts.getDefault().withPingFunction((client, requestOpts) -> null)); + final CompletableFuture startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertSame(HeartbeatConstants.KILL_STATE, view.state()); + Assertions.assertEquals(1, view.listener().heartbeatEventCount(HeartbeatEvent.KILL)); + Assertions.assertEquals(1, view.reconnectCallsCount(), "The restart must be requested once"); + Assertions.assertEquals(0, timer.pendingCount(), "The killed machine must not ping anymore"); + } + + /** + * Checks that a null returned by the ping function does not leak the time measurement. + * + *

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 testNullPingStopsTimeMeasurement() { + 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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + + Assertions.assertEquals( + 0, + registry.get(HeartbeatConstants.POOL_HEARTBEAT_TIME).longTaskTimer().activeTasks(), + "The measurement of the broken ping must be stopped"); + Assertions.assertEquals( + 1.0, + registry.get(HeartbeatConstants.POOL_HEARTBEAT_ERRORS).counter().count(), + "The broken ping must be counted as a failed one"); + Assertions.assertEquals( + 0.0, registry.get(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).counter().count()); + } + + /** + * Checks that a failed startup does not leave a half-started machine behind. + * + *

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 testFailedStartStopsMachine() { + final HeartbeatStateMachine machine = + machine(HeartbeatOpts.getDefault(), new BrokenTimer(this.timer, 0)); + final CompletableFuture startFuture = new CompletableFuture<>(); + + machine.handle(new StartEvent(startFuture)); + + final Throwable cause = assertFails(startFuture); + Assertions.assertInstanceOf(HeartbeatException.class, cause); + Assertions.assertEquals("the timer is broken", cause.getCause().getMessage()); + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertTrue(machine.ctx().window.isEmpty(), "The context must be released"); + Assertions.assertNull(machine.ctx().heartbeatTask, "No ping must be left in the context"); + Assertions.assertEquals(0, timer.pendingCount(), "The machine must not ping anymore"); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + Assertions.assertTrue( + view.listener().events().isEmpty(), "The activation must not be reported"); + Assertions.assertEquals(0, view.reconnectCallsCount(), "The failed startup is not a kill"); + + final CompletableFuture closeFuture = new CompletableFuture<>(); + machine.handle(new StopEvent(closeFuture, null)); + Assertions.assertDoesNotThrow(closeFuture::join); + } + + /** + * Checks that an unexpected error of a started machine kills the connection. + * + *

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 testUnexpectedErrorAfterStartKillsConnection() { + final HeartbeatStateMachine machine = + machine(HeartbeatOpts.getDefault(), new BrokenTimer(this.timer, 1)); + final CompletableFuture startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertSame(HeartbeatConstants.KILL_STATE, view.state()); + Assertions.assertEquals(1, view.listener().heartbeatEventCount(HeartbeatEvent.KILL)); + Assertions.assertEquals(1, view.reconnectCallsCount(), "The restart must be requested once"); + Assertions.assertEquals(0, timer.pendingCount(), "The killed machine must not ping anymore"); + } + + /** + * Checks that the repeated startup of a started machine is completed without side effects. + * + *

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 testRepeatedStartCompletesFutureWithoutSideEffects() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + final CompletableFuture firstStart = new CompletableFuture<>(); + machine.handle(new StartEvent(firstStart)); + Assertions.assertDoesNotThrow(firstStart::join); + final int callsAfterStart = view.calls().size(); + + final CompletableFuture secondStart = new CompletableFuture<>(); + machine.handle(new StartEvent(secondStart)); + + Assertions.assertTrue(secondStart.isDone(), "The repeated start must be completed"); + Assertions.assertFalse(secondStart.isCompletedExceptionally()); + Assertions.assertInstanceOf(RunningState.class, machine.state()); + Assertions.assertEquals(callsAfterStart, view.calls().size(), "The connection is not touched"); + Assertions.assertEquals(1, timer.scheduledCount(), "One more ping must not be scheduled"); + } + + /** + * Checks that the shutdown requested from the start callback is processed after the startup. + * + *

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 testStopFromStartCallbackIsProcessedAfterStartup() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + final CompletableFuture startFuture = new CompletableFuture<>(); + final CompletableFuture closeFuture = new CompletableFuture<>(); + startFuture.whenComplete((unused, error) -> machine.handle(new StopEvent(closeFuture, null))); + + machine.handle(new StartEvent(startFuture)); + + Assertions.assertTrue(startFuture.isDone()); + Assertions.assertFalse(startFuture.isCompletedExceptionally(), "The startup must succeed"); + Assertions.assertInstanceOf(StoppedState.class, machine.state()); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertFalse(closeFuture.isCompletedExceptionally()); + Assertions.assertEquals(0, timer.pendingCount(), "The pending ping must be cancelled"); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + } + + /** + * Checks that the time measurement is stopped if the ping function throws an exception. + * + *

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 testThrownPingStopsTimeMeasurement() { + 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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + + Assertions.assertEquals(0, activeMeasurements(registry), "The measurement must be stopped"); + Assertions.assertEquals(1.0, errors(registry)); + Assertions.assertEquals(0.0, successes(registry)); + Assertions.assertInstanceOf(RunningState.class, machine.state()); + } + + /** + * Checks that the time measurement is stopped if the ping fails. + * + *

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 testFailedPingStopsTimeMeasurement() { + 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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + + Assertions.assertEquals(0, activeMeasurements(registry), "The measurement must be stopped"); + Assertions.assertEquals(1.0, errors(registry)); + Assertions.assertEquals(0.0, successes(registry)); + } + + /** + * Checks that the time measurement lasts while the ping is in flight. + * + *

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 answer = new CompletableFuture<>(); + this.view = viewWith(StubClient.create().nextPingReturnsFuture(answer)); + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault(), registry); + final CompletableFuture startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + + timer.fireNext(); + + Assertions.assertEquals(1, activeMeasurements(registry), "The ping is in flight"); + Assertions.assertEquals(0.0, successes(registry)); + + answer.complete(StubClient.emptyBodyResponse()); + + Assertions.assertEquals(0, activeMeasurements(registry), "The measurement must be stopped"); + Assertions.assertEquals(1.0, successes(registry)); + Assertions.assertEquals(0.0, errors(registry)); + } + + private static int activeMeasurements(SimpleMeterRegistry registry) { + return registry.get(HeartbeatConstants.POOL_HEARTBEAT_TIME).longTaskTimer().activeTasks(); + } + + private static double errors(SimpleMeterRegistry registry) { + return registry.get(HeartbeatConstants.POOL_HEARTBEAT_ERRORS).counter().count(); + } + + private static double successes(SimpleMeterRegistry registry) { + return registry.get(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).counter().count(); + } + + /** Creates a machine over the view of the test with the given options. */ + private HeartbeatStateMachine machine(HeartbeatOpts opts) { + return new HeartbeatStateMachine(this.view, opts, Utils.configure(this.timer, null)); + } + + /** Creates a machine over the view of the test that reports its metrics to the registry. */ + private HeartbeatStateMachine machine(HeartbeatOpts opts, SimpleMeterRegistry registry) { + return new HeartbeatStateMachine(this.view, opts, Utils.configure(this.timer, registry)); + } + + /** Creates a machine over the view of the test that works with the given timer. */ + private HeartbeatStateMachine machine(HeartbeatOpts opts, Timer brokenTimer) { + return new HeartbeatStateMachine(this.view, opts, Utils.configure(brokenTimer, null)); + } + + /** + * A timer that works as the delegate for the given count of the timeouts and fails afterwards. + */ + private static final class BrokenTimer implements Timer { + + private final Timer delegate; + private final int workingTimeouts; + private final AtomicInteger calls = new AtomicInteger(); + + BrokenTimer(Timer delegate, int workingTimeouts) { + this.delegate = delegate; + this.workingTimeouts = workingTimeouts; + } + + @Override + public io.netty.util.Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { + if (this.calls.incrementAndGet() > this.workingTimeouts) { + throw new RuntimeException("the timer is broken"); + } + return this.delegate.newTimeout(task, delay, unit); + } + + @Override + public Set stop() { + return this.delegate.stop(); + } + } + + /** Creates a view with the given client. */ + private RecordingPoolEntryView viewWith(StubClient stub) { + return RecordingPoolEntryView.create( + TAG, IDX, new DefaultNoopAvailabilityPolicy(), stub.client()); + } + + private static Throwable assertFails(CompletableFuture future) { + final ExecutionException ex = + Assertions.assertThrows( + ExecutionException.class, () -> future.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + return ex.getCause(); + } +} From 6a4bea39f78c69f3d64e3bc86f1c411fd2519465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=91=D0=B5?= =?UTF-8?q?=D0=BB=D0=BE=D0=BD=D0=BE=D0=B3=D0=BE=D0=B2?= Date: Mon, 16 Nov 2026 20:50:25 +0300 Subject: [PATCH 3/3] test(heartbeat): add heartbeat window evaluation tests - Added a test class to verify heartbeat window evaluation logic and connection state transitions. --- .../heartbeat/HeartbeatWindowTest.java | 751 ++++++++++++++++++ 1 file changed, 751 insertions(+) create mode 100644 tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatWindowTest.java diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatWindowTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatWindowTest.java new file mode 100644 index 00000000..c07fdeec --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatWindowTest.java @@ -0,0 +1,751 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.msgpack.value.ValueFactory; + +import io.tarantool.core.connection.exceptions.ConnectionException; +import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.pool.HeartbeatEvent; +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.HeartbeatEvent.StopEvent; +import io.tarantool.pool.support.FakeTimer; +import io.tarantool.pool.support.RecordingPoolEntryView; +import io.tarantool.pool.support.StubClient; + +/** + * The unit tests of the sliding window of the heartbeat: the counting of the failed pings and the + * decisions taken on its base. + * + *

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 dataForTestFailedPingAnswers() { + return Stream.of( + Arguments.of(IProtoResponses.error(0x2a, "boom"), "the answer is an error"), + Arguments.of(IProtoResponses.dataArray(ValueFactory.newBoolean(false)), "DATA=[false]"), + Arguments.of(IProtoResponses.dataNotArray(), "DATA is not an array"), + Arguments.of(IProtoResponses.withoutData(), "there is no DATA at all")); + } + + /** + * Checks that the pong that arrives after the shutdown is ignored. + * + *

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 answer = new CompletableFuture<>(); + this.view = viewWith(StubClient.create().nextPingReturnsFuture(answer)); + final HeartbeatStateMachine machine = start(HeartbeatOpts.getDefault()); + + firePings(1); + + final CompletableFuture closeFuture = new CompletableFuture<>(); + machine.handle(new StopEvent(closeFuture, null)); + Assertions.assertDoesNotThrow(closeFuture::join); + + answer.completeExceptionally(new ConnectionException("the connection is dead")); + + Assertions.assertSame( + HeartbeatConstants.INVALIDATE_STATE, + this.view.state(), + "The stopped connection must stay invalidated"); + Assertions.assertEquals( + 0, + this.view.listener().heartbeatEventCount(HeartbeatEvent.KILL), + "The stopped connection must not be killed"); + Assertions.assertEquals( + 0, this.view.reconnectCallsCount(), "The stopped connection must not be restarted"); + Assertions.assertEquals(0, machine.ctx().window.size(), "The shutdown must clear the window"); + Assertions.assertEquals(0, this.timer.pendingCount(), "The heartbeat must not be scheduled"); + } + + /** + * Checks that the error of the ping function is counted as a failed ping. + * + *

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 startFuture = new CompletableFuture<>(); + machine.handle(new StartEvent(startFuture)); + Assertions.assertDoesNotThrow(startFuture::join); + return machine; + } + + /** Fires the given count of the scheduled pings. */ + private void firePings(int count) { + for (int i = 0; i < count; i++) { + Assertions.assertNotNull(this.timer.fireNext(), "The ping must be scheduled"); + } + } + + /** Creates a machine over the view of the test with the given options. */ + private HeartbeatStateMachine machine(HeartbeatOpts opts) { + return new HeartbeatStateMachine(this.view, opts, Utils.configure(this.timer, null)); + } + + /** Creates a view with the given client. */ + private RecordingPoolEntryView viewWith(StubClient stub) { + return RecordingPoolEntryView.create( + TAG, IDX, new DefaultNoopAvailabilityPolicy(), stub.client()); + } +}