diff --git a/tarantool-pooling/pom.xml b/tarantool-pooling/pom.xml index c0d2becb..e076e005 100644 --- a/tarantool-pooling/pom.xml +++ b/tarantool-pooling/pom.xml @@ -47,6 +47,16 @@ io.tarantool testcontainers + + org.mockito + mockito-junit-jupiter + test + + + org.mockito + mockito-inline + test + diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultAvailabilityPolicy.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultAvailabilityPolicy.java new file mode 100644 index 00000000..0a660abe --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultAvailabilityPolicy.java @@ -0,0 +1,202 @@ +/* + * 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.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.LongTaskTimer; +import io.micrometer.core.instrument.MeterRegistry; +import io.netty.util.Timer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.PoolEntryState; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.AvailabilityPolicy; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StopEvent; + +/** + * The default availability policy: it sends pings to the connection and switches the connection + * state between the active, invalidated and killed ones depending on the ping results. + */ +public class DefaultAvailabilityPolicy implements AvailabilityPolicy { + + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAvailabilityPolicy.class); + + private final AtomicReference utils = new AtomicReference<>(null); + + private final Map entries = new ConcurrentHashMap<>(); + + private final HeartbeatOpts opts; + + public DefaultAvailabilityPolicy(HeartbeatOpts opts) { + if (opts == null) { + throw new IllegalArgumentException("Heartbeat options must not be null!"); + } + this.opts = opts; + } + + @Override + public PoolEntryState initState(PoolEntryView view) { + return HeartbeatConstants.ACTIVE_STATE; + } + + @Override + public Duration restartBackoff(PoolEntryView view) { + return Duration.ZERO; + } + + @Override + public CompletionStage start(PoolEntryView view) { + final CompletableFuture cf = new CompletableFuture<>(); + + try { + final HeartbeatStateMachine m = + this.entries.computeIfAbsent( + view, old -> new HeartbeatStateMachine(view, this.opts, this.utils.get())); + m.handle(new StartEvent(cf)); + } catch (Throwable ex) { + cf.completeExceptionally(ex); + } + return cf; + } + + @Override + public CompletionStage stop(PoolEntryView view, Throwable cause) { + final CompletableFuture cf = new CompletableFuture<>(); + + final HeartbeatStateMachine machine = this.entries.remove(view); + if (machine == null) { + cf.complete(null); + return cf; + } + + machine.handle(new StopEvent(cf, cause)); + return cf; + } + + @Override + public void configure(Timer timer, MeterRegistry metrics) { + Objects.requireNonNull(timer, "timer must not be null"); + this.utils.compareAndSet(null, Utils.configure(timer, metrics)); + } + + boolean hasView(PoolEntryView view) { + return this.entries.containsKey(view); + } + + /** + * The internal context of the policy: the timer and the metrics shared between all the + * connections. + */ + static 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 startHeartbeatTimer() { + 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 stopHeartbeatTimer(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/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..dde3b3d9 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachine.java @@ -0,0 +1,227 @@ +/* + * 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.CompletionStage; +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.HeartbeatEvent; +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.availability.heartbeat.DefaultAvailabilityPolicy.Utils; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.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); + + /* + ********************************************************** + * Params + ********************************************************** + */ + private final PoolEntryView view; + + private final Utils utils; + + private final HeartbeatOpts heartbeatOpts; + + private final IProtoRequestOpts heartbeatPingOpts; + + private final String identity; + + /* + ********************************************************** + * State + ********************************************************** + */ + private final CompletableFuture rootCloseFuture = new CompletableFuture<>(); + + private final CompletableFuture rootStartFuture = new CompletableFuture<>(); + + private final HeartbeatCtx ctx; + + private volatile PolicyState state = new NewState(this); + + HeartbeatStateMachine(PoolEntryView view, HeartbeatOpts opts, Utils utils) { + Objects.requireNonNull(view, "view must not be null"); + Objects.requireNonNull(opts, "HeartbeatOpts must not be null!"); + Objects.requireNonNull(utils, "Policy is not configured!"); + Objects.requireNonNull(utils.timer(), "Timer must not be null!"); + + this.view = view; + this.utils = utils; + final Metadata metadata = view.metadata(); + this.identity = metadata.settings().getTag() + '/' + metadata.index(); + + this.heartbeatOpts = opts; + final Deque window = new ArrayDeque<>(opts.getWindowSize()); + this.heartbeatPingOpts = IProtoRequestOpts.empty().withRequestTimeout(opts.getPingInterval()); + this.ctx = new HeartbeatCtx(window, null, 0, 0, 0); + } + + @Override + protected void processEvent(PolicyEvent 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(PolicyState newState) { + this.state = newState; + } + + PolicyState 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; + } + + void linkFuture(CompletionStage root, CompletionStage linkable) { + if (linkable == null) { + return; + } + + root.whenComplete( + (_unused, e) -> { + if (e == null) { + linkable.toCompletableFuture().complete(null); + } else { + linkable.toCompletableFuture().completeExceptionally(e); + } + }); + } + + /** + * 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; + + HeartbeatEvent lastEvent; + + HeartbeatCtx( + Deque window, + Timeout heartbeatTask, + int currentDeathPings, + int currentFailedPings, + long lastPingNanos) { + this.window = window; + this.heartbeatTask = heartbeatTask; + this.currentDeathPings = currentDeathPings; + this.currentFailedPings = currentFailedPings; + this.lastPingNanos = lastPingNanos; + } + + void clear() { + cancelTimer(); + this.window.clear(); + this.heartbeatTask = null; + this.currentDeathPings = 0; + this.currentFailedPings = 0; + this.lastPingNanos = 0; + this.lastEvent = null; + } + + void cancelTimer() { + if (this.heartbeatTask != null) { + this.heartbeatTask.cancel(); + } + } + + void pingTimer(long delta) { + cancelTimer(); + this.heartbeatTask = + utils + .timer() + .newTimeout(_u -> handle(SendPingEvent.INSTANCE), delta, TimeUnit.MILLISECONDS); + } + } + + @Override + public String toString() { + return '[' + this.identity + "][HeartbeatStateMachine]"; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/NewState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/NewState.java new file mode 100644 index 00000000..195a4a79 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/NewState.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.util.concurrent.CompletableFuture; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.pool.HeartbeatOpts; +import io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine.HeartbeatCtx; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StopEvent; + +final class NewState extends PolicyState { + + private static final Logger LOGGER = LoggerFactory.getLogger(NewState.class); + + NewState(HeartbeatStateMachine machine) { + super(machine, "HEARTBEAT_NEW"); + } + + @Override + public void handle(PolicyEvent event) { + super.handle(event); + + if (event instanceof PongEvent + || event instanceof SendPingEvent + || event instanceof ActivateEvent + || event instanceof InvalidateEvent + || event instanceof KillEvent) { + return; + } + + if (event instanceof StartEvent) { + handleStart((StartEvent) event); + return; + } + + if (event instanceof StopEvent) { + handleStop((StopEvent) event); + return; + } + + logUnexpectedEvent(event); + } + + private void handleStart(StartEvent event) { + logStartHandleEvent(event); + + final HeartbeatOpts opts = this.machine.opts(); + + 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.window.clear(); + + // The connection has just been established: the successful connection is the first ping, so + // the window starts with a success mark and no extra ping is needed. + ctx.window.addFirst(0); + final PolicyState newState = new StartedState(this.machine); + transitionTo(newState); + + final CompletableFuture rootStartFuture = this.machine.rootStartFuture(); + this.machine.linkFuture(rootStartFuture, event.startFuture()); + + // TODO may throw + ctx.pingTimer(opts.initialDelay().toMillis()); + + // The library has just established the connection, so it is alive: the entry is activated + // before the startup is reported to the library. + newState.handle(ActivateEvent.INSTANCE); + + rootStartFuture.complete(null); + } + + /** + * This event can arrive in this state only if the stop method has been called between the + * creation of the machine and the start call. In this case the context is not initialized yet and + * there are no futures. + */ + private void handleStop(StopEvent event) { + logStartHandleEvent(event); + + final HeartbeatCtx ctx = this.machine.ctx(); + + ctx.clear(); + final PolicyState newState = new StoppedState(this.machine); + transitionTo(newState); + this.machine.view().changeState(HeartbeatConstants.INVALIDATE_STATE); + + final CompletableFuture rootCloseFuture = this.machine.rootCloseFuture(); + this.machine.linkFuture(rootCloseFuture, event.closeFuture()); + + if (event.cause() != null) { + LOGGER.debug( + "[{}][{}]: stop policy with cause", this.machine.identity(), this, event.cause()); + } + + if (!rootCloseFuture.isDone()) { + rootCloseFuture.complete(null); + } + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PingResult.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PingResult.java index db032b71..b75c5a87 100644 --- a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PingResult.java +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PingResult.java @@ -16,11 +16,11 @@ import io.tarantool.core.protocol.IProtoResponse; import io.tarantool.core.protocol.requests.IProtoConstant; -public final class PingResult { +final class PingResult { private static final Logger LOGGER = LoggerFactory.getLogger(PingResult.class); - public static boolean hasSuccessPingResult(IProtoResponse result, String identity) { + static boolean hasSuccessPingResult(IProtoResponse result, String identity) { if (result == null) { LOGGER.trace("{}: ping response is null", identity); return false; 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/PolicyEvent.java new file mode 100644 index 00000000..aa1b49e1 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyEvent.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.util.concurrent.CompletableFuture; + +import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.core.state.Event; +import io.tarantool.pool.PoolEntryView; + +abstract class PolicyEvent implements Event { + + private final String name; + + PolicyEvent(String name) { + this.name = name; + } + + @Override + public String toString() { + return this.name; + } + + /** An event emitted when {@link DefaultAvailabilityPolicy#start(PoolEntryView)} is called. */ + static final class StartEvent extends PolicyEvent { + + private final CompletableFuture startFuture; + + StartEvent(CompletableFuture startFuture) { + super("HEARTBEAT_START_EVT"); + this.startFuture = startFuture; + } + + CompletableFuture startFuture() { + return this.startFuture; + } + } + + /** An event sent when a response to a ping request is received. */ + static final class PongEvent extends PolicyEvent { + + private final IProtoResponse response; + + private final Throwable ex; + + PongEvent(IProtoResponse response, Throwable ex) { + super("HEARTBEAT_PONG_EVT"); + this.response = response; + this.ex = ex; + } + + IProtoResponse response() { + return this.response; + } + + Throwable exception() { + return this.ex; + } + } + + /** + * 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(); + + private SendPingEvent() { + super("HEARTBEAT_SEND_PING_EVT"); + } + } + + /** An event sent when {@link DefaultAvailabilityPolicy#stop(PoolEntryView)} is called. */ + static final class StopEvent extends PolicyEvent implements Control { + + private final CompletableFuture closeFuture; + + private final Throwable cause; + + StopEvent(CompletableFuture closeFuture, Throwable cause) { + super("HEARTBEAT_STOP_EVT"); + this.closeFuture = closeFuture; + this.cause = cause; + } + + CompletableFuture closeFuture() { + return this.closeFuture; + } + + Throwable cause() { + return this.cause; + } + } + + /** + * An event sent when the connection state must be changed to {@link + * 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(); + + private ActivateEvent() { + super("HEARTBEAT_ACTIVATE_EVT"); + } + } + + /** + * An event sent when the connection state must be changed to {@link + * 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(); + + private InvalidateEvent() { + super("HEARTBEAT_INVALIDATE_EVT"); + } + } + + /** + * 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 PolicyEvent INSTANCE = new KillEvent(); + + private KillEvent() { + super("HEARTBEAT_KILL_EVT"); + } + } + + /** + * A marker interface. All event classes implementing this interface act as control signals and + * have the highest priority over regular events. + */ + private interface Control extends Event { + + @Override + default boolean isControl() { + return true; + } + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyState.java new file mode 100644 index 00000000..8c5e7dde --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/PolicyState.java @@ -0,0 +1,70 @@ +/* + * 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; + +/** + * 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 PolicyState implements State { + + private final Logger logger; + + final HeartbeatStateMachine machine; + private final String name; + + PolicyState(HeartbeatStateMachine machine, String name) { + this.machine = machine; + this.name = name; + this.logger = LoggerFactory.getLogger(getClass()); + } + + @Override + public void handle(PolicyEvent event) { + if (!isValid(event)) { + return; + } + + logReceivedEvent(event); + } + + boolean isValid(PolicyEvent event) { + if (event == null) { + this.logger.debug("[{}][{}]: got a null event. Skipping...", this.machine.identity(), this); + return false; + } + return true; + } + + protected final void logStartHandleEvent(PolicyEvent event) { + this.logger.debug("[{}][{}]: start handle '{}' event", this.machine.identity(), this, event); + } + + protected final void logReceivedEvent(PolicyEvent event) { + this.logger.debug("[{}][{}]: received '{}' event", this.machine.identity(), this, event); + } + + protected final void logUnexpectedEvent(PolicyEvent event) { + this.logger.debug( + "[{}][{}]: received an unexpected '{}' event", this.machine.identity(), this, event); + } + + protected final void transitionTo(PolicyState nextState) { + machine.state(nextState); + this.logger.debug( + "[{}][{}]: transitioned to '{}' state", this.machine.identity(), this, nextState); + } + + @Override + public String toString() { + return this.name; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StartedState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StartedState.java new file mode 100644 index 00000000..96e9c385 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StartedState.java @@ -0,0 +1,281 @@ +/* + * 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.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import io.micrometer.core.instrument.LongTaskTimer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.core.connection.exceptions.ConnectionException; +import io.tarantool.core.exceptions.ShutdownException; +import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.pool.HeartbeatEvent; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.availability.heartbeat.HeartbeatStateMachine.HeartbeatCtx; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StopEvent; + +final class StartedState extends PolicyState { + + private static final Logger LOGGER = LoggerFactory.getLogger(StartedState.class); + + StartedState(HeartbeatStateMachine machine) { + super(machine, "HEARTBEAT_STARTED"); + } + + @Override + public void handle(PolicyEvent event) { + super.handle(event); + + if (event instanceof StartEvent) { + handleStart((StartEvent) event); + return; + } + + if (event instanceof StopEvent) { + handleStop((StopEvent) event); + return; + } + + if (event instanceof SendPingEvent) { + handleSendPing((SendPingEvent) event); + return; + } + + if (event instanceof PongEvent) { + handlePong((PongEvent) event); + return; + } + + if (event instanceof ActivateEvent) { + handleActivate(event); + return; + } + + if (event instanceof InvalidateEvent) { + handleInvalidate(event); + return; + } + + if (event instanceof KillEvent) { + handleKill(event); + return; + } + + logUnexpectedEvent(event); + } + + private void handleStart(StartEvent event) { + logStartHandleEvent(event); + final CompletableFuture rootStartFuture = this.machine.rootStartFuture(); + this.machine.linkFuture(rootStartFuture, event.startFuture()); + } + + private void handleStop(StopEvent event) { + logStartHandleEvent(event); + + final PoolEntryView view = this.machine.view(); + final HeartbeatCtx ctx = this.machine.ctx(); + + final PolicyState newState = new StoppedState(this.machine); + transitionTo(newState); + view.changeState(HeartbeatConstants.INVALIDATE_STATE); + ctx.clear(); + + final CompletableFuture rootCloseFuture = this.machine.rootCloseFuture(); + this.machine.linkFuture(rootCloseFuture, event.closeFuture()); + + if (event.cause() != null) { + LOGGER.debug( + "[{}][{}]: stop policy with cause", this.machine.identity(), this, event.cause()); + } + if (!rootCloseFuture.isDone()) { + rootCloseFuture.complete(null); + } + LOGGER.info("[{}][{}]: availability policy is stopped", this.machine.identity(), this); + } + + private void handleActivate(PolicyEvent event) { + logStartHandleEvent(event); + + final PoolEntryView view = this.machine.view(); + final Metadata metadata = view.metadata(); + final String tag = metadata.settings().getTag(); + final int idx = metadata.index(); + + view.changeState(HeartbeatConstants.ACTIVE_STATE); + + this.machine.ctx().lastEvent = HeartbeatEvent.ACTIVATE; + + view.emit(l -> l.onHeartbeatEvent(tag, idx, HeartbeatEvent.ACTIVATE)); + LOGGER.info("[{}][{}]: connection is OK", this.machine.identity(), this); + } + + private void handleInvalidate(PolicyEvent event) { + logStartHandleEvent(event); + + final PoolEntryView view = this.machine.view(); + final String tag = view.metadata().settings().getTag(); + final int idx = view.metadata().index(); + + view.changeState(HeartbeatConstants.INVALIDATE_STATE); + this.machine.ctx().lastEvent = HeartbeatEvent.INVALIDATE; + + view.emit(l -> l.onHeartbeatEvent(tag, idx, HeartbeatEvent.INVALIDATE)); + LOGGER.info("[{}][{}]: connection is invalid", this.machine.identity(), this); + } + + private void handleKill(PolicyEvent event) { + logStartHandleEvent(event); + + final PoolEntryView view = this.machine.view(); + final String tag = view.metadata().settings().getTag(); + final int index = view.metadata().index(); + + final HeartbeatCtx ctx = this.machine.ctx(); + final PolicyState newState = new StoppedState(this.machine); + transitionTo(newState); + ctx.clear(); + + view.changeState(HeartbeatConstants.KILL_STATE); + ctx.lastEvent = HeartbeatEvent.KILL; + + view.emit(l -> l.onHeartbeatEvent(tag, index, HeartbeatEvent.KILL)); + + LOGGER.warn("[{}][{}]: close connection", this.machine.identity(), this); + view.reconnect(); + } + + private void handleSendPing(SendPingEvent event) { + logStartHandleEvent(event); + + final HeartbeatCtx heartbeatCtx = this.machine.ctx(); + final PoolEntryView view = this.machine.view(); + + heartbeatCtx.lastPingNanos = System.nanoTime(); + + final LongTaskTimer.Sample timer = this.machine.utils().startHeartbeatTimer(); + + CompletableFuture ping; + try { + ping = + Objects.requireNonNull( + this.machine + .opts() + .getPingFunction() + .apply(view.client(), this.machine.heartbeatPingRequestOpts()), + "ping function returned null"); + } catch (Exception e) { + LOGGER.debug( + "[{}][{}]: caught an error while sending the ping...", this.machine.identity(), this, e); + this.machine.utils().stopHeartbeatTimer(timer); + this.machine.handle(new PongEvent(null, e)); + return; + } + + ping.whenComplete( + (result, ex) -> { + this.machine.utils().stopHeartbeatTimer(timer); + this.machine.handle(new PongEvent(result, ex)); + }); + } + + private void handlePong(PongEvent event) { + logStartHandleEvent(event); + final Throwable exc = event.exception(); + final IProtoResponse result = event.response(); + final HeartbeatCtx heartbeatCtx = this.machine.ctx(); + + int failure = 0; + Throwable error = null; + + if (exc != null) { + failure = 1; + error = unwrap(exc); + LOGGER.debug("[{}][{}]: ping failed: {}", this.machine.identity(), this, exc.toString()); + } else if (!PingResult.hasSuccessPingResult(result, this.machine.identity())) { + failure = 1; + } + + this.machine.utils().incHeartbeatCounters(failure); + + if (isTerminalError(error)) { + LOGGER.warn( + "[{}][{}]: connection is dead: {}", this.machine.identity(), this, error.toString()); + this.machine.handle(KillEvent.INSTANCE); + return; + } + + nextPing(); + + heartbeatCtx.window.addFirst(failure); + heartbeatCtx.currentFailedPings += failure; + if (heartbeatCtx.window.size() > this.machine.opts().getWindowSize()) { + heartbeatCtx.currentFailedPings -= heartbeatCtx.window.removeLast(); + } else if (heartbeatCtx.window.size() < this.machine.opts().getWindowSize()) { + return; + } + + if (heartbeatCtx.currentFailedPings >= this.machine.opts().getInvalidationThreshold()) { + if (heartbeatCtx.lastEvent != HeartbeatEvent.INVALIDATE) { + this.machine.handle(InvalidateEvent.INSTANCE); + } + heartbeatCtx.currentDeathPings++; + if (heartbeatCtx.currentDeathPings > this.machine.opts().getDeathThreshold()) { + if (heartbeatCtx.lastEvent != HeartbeatEvent.KILL) { + this.machine.handle(KillEvent.INSTANCE); + } + } + return; + } + + if (heartbeatCtx.lastEvent != HeartbeatEvent.ACTIVATE) { + this.machine.handle(ActivateEvent.INSTANCE); + } + heartbeatCtx.currentDeathPings = 0; + } + + private void nextPing() { + final HeartbeatCtx ctx = this.machine.ctx(); + // The monotonic clock is used: the wall clock may jump (NTP, manual change). + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - ctx.lastPingNanos); + final long delta = this.machine.opts().getPingInterval() - elapsedMillis; + if (delta <= 0) { + this.machine.handle(SendPingEvent.INSTANCE); + } else { + ctx.pingTimer(delta); + } + } + + private static Throwable unwrap(Throwable ex) { + Throwable result = ex; + while ((result instanceof CompletionException || result instanceof ExecutionException) + && result.getCause() != null) { + result = result.getCause(); + } + return result; + } + + // 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..a673826c --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/StoppedState.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat; + +import java.util.concurrent.CompletableFuture; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.pool.availability.heartbeat.PolicyEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StopEvent; +import io.tarantool.pool.availability.heartbeat.exceptions.HeartbeatClosedException; + +final class StoppedState extends PolicyState { + + private static final Logger LOGGER = LoggerFactory.getLogger(StoppedState.class); + + StoppedState(HeartbeatStateMachine machine) { + super(machine, "HEARTBEAT_STOPPED"); + } + + @Override + public void handle(PolicyEvent event) { + super.handle(event); + + if (event instanceof PongEvent + || event instanceof SendPingEvent + || event instanceof ActivateEvent + || event instanceof InvalidateEvent + || event instanceof KillEvent) { + return; + } + + if (event instanceof StartEvent) { + handleStart((StartEvent) event); + return; + } + + if (event instanceof StopEvent) { + handleStop((StopEvent) event); + return; + } + + logUnexpectedEvent(event); + } + + private void handleStart(StartEvent event) { + logStartHandleEvent(event); + + final CompletableFuture startFuture = event.startFuture(); + if (!startFuture.isDone()) { + startFuture.completeExceptionally(new HeartbeatClosedException("Already closed!")); + } + } + + private void handleStop(StopEvent event) { + logStartHandleEvent(event); + + final CompletableFuture rootCloseFuture = this.machine.rootCloseFuture(); + this.machine.linkFuture(rootCloseFuture, event.closeFuture()); + + if (event.cause() != null) { + LOGGER.debug( + "[{}][{}]: stop policy with cause", this.machine.identity(), this, event.cause()); + } + if (!rootCloseFuture.isDone()) { + rootCloseFuture.complete(null); + } + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/exceptions/HeartbeatClosedException.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/exceptions/HeartbeatClosedException.java new file mode 100644 index 00000000..e1b5bab5 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/exceptions/HeartbeatClosedException.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat.exceptions; + +public class HeartbeatClosedException extends HeartbeatException { + + public HeartbeatClosedException() { + super(); + } + + public HeartbeatClosedException(String message) { + super(message); + } + + public HeartbeatClosedException(String message, Throwable cause) { + super(message, cause); + } + + public HeartbeatClosedException(Throwable cause) { + super(cause); + } + + protected HeartbeatClosedException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/exceptions/HeartbeatException.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/exceptions/HeartbeatException.java new file mode 100644 index 00000000..a01b3ba3 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/exceptions/HeartbeatException.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.availability.heartbeat.exceptions; + +public class HeartbeatException extends RuntimeException { + + public HeartbeatException() { + super(); + } + + public HeartbeatException(String message) { + super(message); + } + + public HeartbeatException(String message, Throwable cause) { + super(message, cause); + } + + public HeartbeatException(Throwable cause) { + super(cause); + } + + protected HeartbeatException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} 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..28ee3336 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatStateMachineTest.java @@ -0,0 +1,969 @@ +/* + * 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.DefaultAvailabilityPolicy.Utils; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.ActivateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.InvalidateEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.KillEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.PongEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.SendPingEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.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(StartedState.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 testStartFillsTheWindowWithTheConnection() { + 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 testStopBeforeStartStopsTheMachine() { + 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 testStopCancelsThePendingPing() { + 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(NewState.class, machine.state()); + Assertions.assertTrue(view.calls().isEmpty(), "The connection must not be touched"); + Assertions.assertEquals(0, timer.scheduledCount(), "The machine must not start the heartbeat"); + } + + /** + * Checks that the events of a running heartbeat are ignored after the shutdown. + * + *

The heartbeat is stopped, so the ping and the state events have nothing to do and must be + * dropped silently. + */ + @Test + void testHeartbeatEventsAreIgnoredInStoppedState() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + CompletableFuture 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(NewState.class, machine.state()); + Assertions.assertTrue(view.calls().isEmpty(), "The connection must not be touched"); + } + + /** + * Checks the names of the states. + * + *

The name of the state is used in the logs of the heartbeat, so it must be stable. + */ + @Test + void testStateNames() { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + + Assertions.assertEquals("HEARTBEAT_NEW", new NewState(machine).toString()); + Assertions.assertEquals("HEARTBEAT_STARTED", new StartedState(machine).toString()); + Assertions.assertEquals("HEARTBEAT_STOPPED", new StoppedState(machine).toString()); + } + + /** + * Checks that the concurrent startups start the heartbeat once. + * + *

The library starts the policy once per connection, but the concurrent startups must be safe + * anyway: the machine is shared by all of them, so only the first startup may schedule the ping + * and all the start futures must be completed successfully. + */ + @Test + void testConcurrentStartsStartTheHeartbeatOnce() throws Exception { + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault()); + final int starters = 16; + final CountDownLatch ready = new CountDownLatch(starters); + final CountDownLatch go = new CountDownLatch(1); + final List> 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(StartedState.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 testStopPreemptsTheQueuedEvents() throws Exception { + final CountDownLatch pingStarted = new CountDownLatch(1); + final CountDownLatch releasePing = new CountDownLatch(1); + final HeartbeatOpts opts = + HeartbeatOpts.getDefault() + .withPingFunction( + (client, requestOpts) -> { + pingStarted.countDown(); + try { + releasePing.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return CompletableFuture.completedFuture(StubClient.emptyBodyResponse()); + }); + final HeartbeatStateMachine machine = machine(opts); + final CompletableFuture 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 testActivateIsEmittedBeforeTheStartupIsReported() { + 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 testPolicyDoesNotReportTheConnectionEvents() { + final RuntimeException noAnswer = new RuntimeException("the node does not answer"); + this.view = viewWith(StubClient.failing(noAnswer).nextPingFails(noAnswer).nextPingSucceeds()); + final HeartbeatStateMachine machine = + machine( + HeartbeatOpts.getDefault() + .withWindowSize(1) + .withInvalidationThreshold(1) + .withDeathThreshold(2)); + final CompletableFuture 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 testKillEventIsEmittedAndTheRestartIsRequested() { + this.view = viewWith(StubClient.failing(new RuntimeException("the node does not answer"))); + final HeartbeatStateMachine machine = + machine( + HeartbeatOpts.getDefault() + .withWindowSize(1) + .withInvalidationThreshold(1) + .withDeathThreshold(1)); + final CompletableFuture 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 testNullPingKillsTheConnection() { + 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 testNullPingStopsTheTimeMeasurement() { + final SimpleMeterRegistry registry = new SimpleMeterRegistry(); + final HeartbeatStateMachine machine = + new HeartbeatStateMachine( + this.view, + HeartbeatOpts.getDefault().withPingFunction((client, requestOpts) -> null), + Utils.configure(this.timer, registry)); + final CompletableFuture 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 testFailedStartStopsTheMachine() { + 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 testUnexpectedErrorAfterStartKillsTheConnection() { + 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 testRepeatedStartCompletesTheFutureWithoutSideEffects() { + 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(StartedState.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 testStopFromTheStartCallbackIsProcessedAfterTheStartup() { + 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 testThrownPingStopsTheTimeMeasurement() { + final SimpleMeterRegistry registry = new SimpleMeterRegistry(); + final HeartbeatOpts opts = + HeartbeatOpts.getDefault() + .withPingFunction( + (client, requestOpts) -> { + throw new RuntimeException("cannot send the ping"); + }); + final HeartbeatStateMachine machine = machine(opts, registry); + final CompletableFuture 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(StartedState.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 testFailedPingStopsTheTimeMeasurement() { + final SimpleMeterRegistry registry = new SimpleMeterRegistry(); + this.view = + viewWith( + StubClient.create().nextPingFails(new RuntimeException("the node does not answer"))); + final HeartbeatStateMachine machine = machine(HeartbeatOpts.getDefault(), registry); + final CompletableFuture 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(); + } +} 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..f1bc6137 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/HeartbeatWindowTest.java @@ -0,0 +1,752 @@ +/* + * 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.DefaultAvailabilityPolicy.Utils; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.StartEvent; +import io.tarantool.pool.availability.heartbeat.PolicyEvent.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()); + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/unit/PingResultTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/PingResultTest.java similarity index 86% rename from tarantool-pooling/src/test/java/io/tarantool/pool/unit/PingResultTest.java rename to tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/PingResultTest.java index 07d984f4..f5b78379 100644 --- a/tarantool-pooling/src/test/java/io/tarantool/pool/unit/PingResultTest.java +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/availability/heartbeat/PingResultTest.java @@ -3,7 +3,7 @@ * All Rights Reserved. */ -package io.tarantool.pool.unit; +package io.tarantool.pool.availability.heartbeat; import java.io.IOException; import java.util.stream.Stream; @@ -21,7 +21,6 @@ import io.tarantool.core.protocol.IProtoRawResponse; import io.tarantool.core.protocol.IProtoResponse; import io.tarantool.core.protocol.requests.IProtoConstant; -import io.tarantool.pool.availability.heartbeat.PingResult; class PingResultTest { @@ -73,12 +72,12 @@ final class IProtoResponses { private IProtoResponses() {} - /** Заголовок обычного (не ошибочного) ответа: request type = 0 (IPROTO_OK). */ + /** Normal (non-error) response header: request type = 0 (IPROTO_OK). */ private static final MapValue OK_HEADER = ValueFactory.newMap( ValueFactory.newInteger(IProtoConstant.IPROTO_REQUEST_TYPE), ValueFactory.newInteger(0)); - /** Заголовок ошибочного ответа: 0x8000 | code. */ + /** Error response header: 0x8000 | code. */ private static MapValue errorHeader(int code) { return ValueFactory.newMap( ValueFactory.newInteger(IProtoConstant.IPROTO_REQUEST_TYPE), @@ -86,9 +85,9 @@ private static MapValue errorHeader(int code) { } /** - * Собирает ответ из заголовка и тела. + * Builds a response from a header and a body. * - *

Формат пакета: [заголовок][тело]; {@code headerSize} = длина заголовка. + *

Packet format: [header][body]; {@code headerSize} = header length. */ static IProtoResponse response(MapValue header, Value body) { try (final MessageBufferPacker headerPacker = MessagePack.newDefaultBufferPacker(); @@ -109,12 +108,12 @@ static IProtoResponse response(MapValue header, Value body) { } } - /** Ответ без тела — как от {@code IPROTO_PING}. */ + /** Empty-body response, such as from {@code IPROTO_PING}. */ static IProtoResponse emptyBody() { return response(OK_HEADER, ValueFactory.emptyMap()); } - /** То же, но с произвольным числом элементов в DATA. */ + /** Same, but with an arbitrary number of elements in DATA. */ static IProtoResponse dataArray(Value... values) { final ValueFactory.MapBuilder bodyBuilder = ValueFactory.newMapBuilder(); bodyBuilder.put( @@ -122,7 +121,7 @@ static IProtoResponse dataArray(Value... values) { return response(OK_HEADER, bodyBuilder.build()); } - /** Ответ-ошибка сервера. */ + /** Server error response. */ static IProtoResponse error(int code, String message) { final MapValue body = ValueFactory.newMap( @@ -133,7 +132,7 @@ static IProtoResponse error(int code, String message) { return response(errorHeader(code), body); } - /** Ответ без IPROTO_DATA — например, ответ на IPROTO_ID. */ + /** A response without IPROTO_DATA — for example, a response to IPROTO_ID. */ static IProtoResponse withoutData() { return IProtoResponses.response( OK_HEADER, @@ -142,7 +141,7 @@ static IProtoResponse withoutData() { ValueFactory.newInteger(IProtoConstant.IPROTO_FEATURES), ValueFactory.emptyArray())); } - /** IPROTO_DATA есть, но это не массив. */ + /** IPROTO_DATA is present, but it is not an array. */ static IProtoResponse dataNotArray() { return IProtoResponses.response( OK_HEADER, diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/FakeTimer.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FakeTimer.java new file mode 100644 index 00000000..3441a6cf --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FakeTimer.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.support; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import io.netty.util.Timeout; +import io.netty.util.Timer; +import io.netty.util.TimerTask; + +/** + * A {@link Timer} that fires nothing by itself: the test decides when a scheduled timeout runs. + * + *

The heartbeat policy schedules the next ping through the timer it has been configured with, so + * a manual timer turns the whole heartbeat into a deterministic sequence of steps: the test fires a + * timeout, the policy sends a ping, the test completes the ping future, and the policy reacts to + * the answer. Neither sleeps nor polling are needed. + * + *

The timeouts are fired in the order of their scheduling. A timeout scheduled by a fired task + * is not fired by the same {@link #fireAll()} call, so the test may walk through the heartbeat step + * by step. + */ +public final class FakeTimer implements Timer { + + private final ConcurrentLinkedQueue pending = new ConcurrentLinkedQueue<>(); + private final AtomicInteger scheduled = new AtomicInteger(); + private final AtomicInteger fired = new AtomicInteger(); + private final AtomicInteger cancelled = new AtomicInteger(); + private volatile FakeTimeout lastScheduled; + + @Override + public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { + final FakeTimeout timeout = new FakeTimeout(this, task, unit.toMillis(delay)); + this.pending.add(timeout); + this.scheduled.incrementAndGet(); + this.lastScheduled = timeout; + return timeout; + } + + @Override + public Set stop() { + final Set stopped = new HashSet<>(); + for (final FakeTimeout timeout : pendingTimeouts()) { + if (timeout.cancel()) { + stopped.add(timeout); + } + } + this.pending.clear(); + return stopped; + } + + /** + * Returns the timeouts that are scheduled but neither fired nor cancelled. + * + * @return the immutable snapshot of the pending timeouts + */ + public List pendingTimeouts() { + return Collections.unmodifiableList(new ArrayList<>(this.pending)); + } + + /** + * Returns the count of the timeouts that are scheduled but neither fired nor cancelled. + * + * @return the count of the pending timeouts + */ + public int pendingCount() { + return this.pending.size(); + } + + /** + * Returns the count of all the scheduled timeouts. + * + * @return the count of the scheduled timeouts + */ + public int scheduledCount() { + return this.scheduled.get(); + } + + /** + * Returns the count of the fired timeouts. + * + * @return the count of the fired timeouts + */ + public int firedCount() { + return this.fired.get(); + } + + /** + * Returns the count of the cancelled timeouts. + * + * @return the count of the cancelled timeouts + */ + public int cancelledCount() { + return this.cancelled.get(); + } + + /** + * Returns the timeout that has been scheduled last, no matter whether it is fired or not. + * + * @return the last scheduled timeout or {@code null} if nothing has been scheduled + */ + public FakeTimeout lastScheduled() { + return this.lastScheduled; + } + + /** + * Fires the timeout that has been scheduled first. + * + * @return the fired timeout or {@code null} if there is nothing to fire + */ + public FakeTimeout fireNext() { + final FakeTimeout timeout = this.pending.poll(); + if (timeout == null) { + return null; + } + timeout.fire(); + return timeout; + } + + /** + * Fires all the timeouts that are pending at the moment of the call. + * + *

The timeouts scheduled by the fired tasks stay pending: the test may fire them one by one to + * control the heartbeat step by step. + * + * @return the count of the fired timeouts + */ + public int fireAll() { + int count = 0; + for (final FakeTimeout timeout : pendingTimeouts()) { + if (timeout.fire()) { + count++; + } + } + return count; + } + + /** A timeout scheduled in a {@link FakeTimer}. */ + public static final class FakeTimeout implements Timeout { + + private final FakeTimer timer; + private final TimerTask task; + private final long delayMillis; + private final AtomicBoolean expired = new AtomicBoolean(); + private final AtomicBoolean cancelled = new AtomicBoolean(); + + private FakeTimeout(FakeTimer timer, TimerTask task, long delayMillis) { + this.timer = timer; + this.task = task; + this.delayMillis = delayMillis; + } + + /** + * Returns the delay of the timeout in milliseconds. + * + * @return the delay in milliseconds + */ + public long delayMillis() { + return this.delayMillis; + } + + /** + * Runs the task of the timeout. + * + * @return {@code true} if the task has been run, {@code false} if the timeout has been fired or + * cancelled before + */ + public boolean fire() { + if (!this.expired.compareAndSet(false, true)) { + return false; + } + this.timer.pending.remove(this); + this.timer.fired.incrementAndGet(); + try { + this.task.run(this); + } catch (Exception e) { + throw new IllegalStateException("The timer task has failed", e); + } + return true; + } + + @Override + public Timer timer() { + return this.timer; + } + + @Override + public TimerTask task() { + return this.task; + } + + @Override + public boolean isExpired() { + return this.expired.get(); + } + + @Override + public boolean isCancelled() { + return this.cancelled.get(); + } + + @Override + public boolean cancel() { + if (!this.cancelled.compareAndSet(false, true)) { + return false; + } + this.timer.pending.remove(this); + this.timer.cancelled.incrementAndGet(); + return true; + } + + @Override + public String toString() { + return "FakeTimeout{delayMillis=" + + this.delayMillis + + ", expired=" + + this.expired.get() + + ", cancelled=" + + this.cancelled.get() + + '}'; + } + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/FlakyTimer.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FlakyTimer.java new file mode 100644 index 00000000..2418b01f --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/FlakyTimer.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.support; + +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import io.netty.util.Timeout; +import io.netty.util.Timer; +import io.netty.util.TimerTask; + +/** A timer that fails the given count of the first timeouts and delegates the rest. */ +public class FlakyTimer implements Timer { + + private final Timer delegate; + private final AtomicInteger failuresLeft; + + public FlakyTimer(Timer delegate, int failures) { + this.delegate = delegate; + this.failuresLeft = new AtomicInteger(failures); + } + + @Override + public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { + if (this.failuresLeft.getAndDecrement() > 0) { + throw new RuntimeException("the timer is broken"); + } + return this.delegate.newTimeout(task, delay, unit); + } + + @Override + public Set stop() { + return this.delegate.stop(); + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java new file mode 100644 index 00000000..d0afaa45 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.support; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +import io.tarantool.core.IProtoClient; +import io.tarantool.pool.HeartbeatEvent; +import io.tarantool.pool.InstanceConnectionGroup; +import io.tarantool.pool.PoolEntryState; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.PoolEventListener; +import io.tarantool.pool.availability.AvailabilityPolicy; +import io.tarantool.pool.availability.Metadata; + +/** + * A {@link PoolEntryView} that records every interaction made by a policy. + * + *

The view is intentionally hostile: it throws an exception when the policy passes {@code null} + * to {@link #changeState(PoolEntryState)} or to {@link #emit(Consumer)}, because the real view + * forbids such calls. Every violation is counted as well, so the test may report it even if the + * policy has swallowed the exception. + * + *

The state changes, the emitted events and the reconnects are recorded in the order of their + * occurrence, so the test may assert not only the counts but also the sequence of the actions of + * the policy. + * + *

A fresh connection is closed, so the view starts in the {@link #CLOSED_STATE} and stays there + * until the state is set with {@link #changeState(PoolEntryState)}. The test sets the state + * returned by {@code AvailabilityPolicy#initState(view)} the same way the library does upon the + * creation of a pool entry. + */ +public final class RecordingPoolEntryView implements PoolEntryView { + + /** + * The state of a connection that has not been initialized by the policy yet: the connection is + * closed, so it is not visible to the load balancer. + */ + public static final PoolEntryState CLOSED_STATE = new PoolEntryState("CLOSED", true) {}; + + private final Metadata metadata; + private final IProtoClient client; + private final RecordingPoolEventListener listener = new RecordingPoolEventListener(); + private final List stateChanges = new CopyOnWriteArrayList<>(); + private final List calls = new CopyOnWriteArrayList<>(); + private final AtomicInteger reconnectCalls = new AtomicInteger(); + private final AtomicInteger clientCalls = new AtomicInteger(); + private final AtomicInteger nullStateChanges = new AtomicInteger(); + private final AtomicInteger nullEmitCalls = new AtomicInteger(); + private volatile PoolEntryState state = CLOSED_STATE; + + private RecordingPoolEntryView(Metadata metadata, IProtoClient client) { + this.metadata = metadata; + this.client = client; + } + + /** + * Creates a view for a connection of a group with the given policy. + * + * @param tag the tag of the connection group + * @param index the index of the connection within the group + * @param policy the policy under test, exposed through the group settings + * @param client the client the policy is expected to use to check the availability + * @return the view instance + */ + public static RecordingPoolEntryView create( + String tag, int index, AvailabilityPolicy policy, IProtoClient client) { + return new RecordingPoolEntryView(newMetadata(tag, index, policy), client); + } + + private static Metadata newMetadata(String tag, int index, AvailabilityPolicy policy) { + final InstanceConnectionGroup group = + InstanceConnectionGroup.builder() + .withHost(InstanceConnectionGroup.DEFAULT_HOST) + .withPort(InstanceConnectionGroup.DEFAULT_PORT) + .withSize(1) + .withTag(tag) + .withAvailabilityPolicy(policy) + .build(); + return new Metadata(group, index) {}; + } + + @Override + public void changeState(PoolEntryState newState) { + if (newState == null) { + this.nullStateChanges.incrementAndGet(); + throw new NullPointerException("The connection state must not be null"); + } + this.stateChanges.add(newState); + this.calls.add("changeState:" + newState.name()); + this.state = newState; + } + + @Override + public Metadata metadata() { + return this.metadata; + } + + /** + * Returns the state of the connection. + * + *

Before a state is set the connection is closed, so the view reports {@link #CLOSED_STATE}. + * Afterwards it reports the last state set with {@link #changeState(PoolEntryState)}. + * + * @return the current state of the connection + */ + @Override + public PoolEntryState state() { + return this.state; + } + + @Override + public IProtoClient client() { + this.clientCalls.incrementAndGet(); + this.calls.add("client"); + return this.client; + } + + @Override + public void reconnect() { + this.reconnectCalls.incrementAndGet(); + this.calls.add("reconnect"); + } + + @Override + public void emit(Consumer action) { + if (action == null) { + this.nullEmitCalls.incrementAndGet(); + throw new NullPointerException("The action must not be null"); + } + this.calls.add("emit"); + action.accept(this.listener); + } + + /** + * Returns the listener that receives all the events emitted by the policy. + * + * @return the recording listener + */ + public RecordingPoolEventListener listener() { + return this.listener; + } + + /** + * Returns the states the policy has set, in the order of their occurrence. + * + * @return the list of the state changes + */ + public List stateChanges() { + return this.stateChanges; + } + + /** + * Returns the names of the states the policy has set, in the order of their occurrence. + * + * @return the list of the state names + */ + public List stateChangeNames() { + final List names = new CopyOnWriteArrayList<>(); + for (final PoolEntryState stateChange : this.stateChanges) { + names.add(stateChange.name()); + } + return names; + } + + /** + * Returns the calls the policy has made to the view, in the order of their occurrence. + * + * @return the list of the calls + */ + public List calls() { + return this.calls; + } + + /** + * Returns the count of the {@link #reconnect()} calls. + * + * @return the count of the calls + */ + public int reconnectCallsCount() { + return this.reconnectCalls.get(); + } + + /** + * Returns the count of the {@link #client()} calls. + * + * @return the count of the calls + */ + public int clientCallsCount() { + return this.clientCalls.get(); + } + + /** + * Returns the count of the {@code changeState(null)} calls. + * + * @return the count of the invalid calls + */ + public int nullStateChangesCount() { + return this.nullStateChanges.get(); + } + + /** + * Returns the count of the {@code emit(null)} calls. + * + * @return the count of the invalid calls + */ + public int nullEmitCallsCount() { + return this.nullEmitCalls.get(); + } + + /** A {@link PoolEventListener} that counts the events emitted by a policy. */ + public static final class RecordingPoolEventListener implements PoolEventListener { + + private final AtomicInteger connectionOpened = new AtomicInteger(); + private final AtomicInteger connectionClosed = new AtomicInteger(); + private final AtomicInteger connectionFailed = new AtomicInteger(); + private final AtomicInteger reconnectScheduled = new AtomicInteger(); + private final Map heartbeatEvents = + new EnumMap<>(HeartbeatEvent.class); + private final List events = new CopyOnWriteArrayList<>(); + + /** Creates an empty listener. */ + public RecordingPoolEventListener() { + for (final HeartbeatEvent event : HeartbeatEvent.values()) { + this.heartbeatEvents.put(event, new AtomicInteger()); + } + } + + @Override + public void onConnectionOpened(String tag, int index) { + this.connectionOpened.incrementAndGet(); + this.events.add("onConnectionOpened"); + } + + @Override + public void onConnectionClosed(String tag, int index) { + this.connectionClosed.incrementAndGet(); + this.events.add("onConnectionClosed"); + } + + @Override + public void onConnectionFailed(String tag, int index, Throwable throwable) { + this.connectionFailed.incrementAndGet(); + this.events.add("onConnectionFailed"); + } + + @Override + public void onReconnectScheduled(String tag, int index, long delayMs) { + this.reconnectScheduled.incrementAndGet(); + this.events.add("onReconnectScheduled"); + } + + @Override + public void onHeartbeatEvent(String tag, int index, HeartbeatEvent event) { + this.heartbeatEvents.get(event).incrementAndGet(); + this.events.add("onHeartbeatEvent:" + event.name()); + } + + /** + * Returns the count of the {@code onConnectionOpened} calls. + * + * @return the count of the calls + */ + public int connectionOpenedCount() { + return this.connectionOpened.get(); + } + + /** + * Returns the count of the {@code onConnectionClosed} calls. + * + * @return the count of the calls + */ + public int connectionClosedCount() { + return this.connectionClosed.get(); + } + + /** + * Returns the count of the {@code onConnectionFailed} calls. + * + * @return the count of the calls + */ + public int connectionFailedCount() { + return this.connectionFailed.get(); + } + + /** + * Returns the count of the {@code onReconnectScheduled} calls. + * + * @return the count of the calls + */ + public int reconnectScheduledCount() { + return this.reconnectScheduled.get(); + } + + /** + * Returns the count of the events of the given kind. + * + * @param event the kind of the event + * @return the count of the events + */ + public int heartbeatEventCount(HeartbeatEvent event) { + final AtomicInteger counter = this.heartbeatEvents.get(event); + return counter == null ? 0 : counter.get(); + } + + /** + * Returns the names of the received events, in the order of their occurrence. + * + * @return the list of the event names + */ + public List events() { + return this.events; + } + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java new file mode 100644 index 00000000..6a06254c --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.support; + +import java.io.IOException; +import java.util.Queue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import org.mockito.Mockito; +import org.msgpack.core.MessageBufferPacker; +import org.msgpack.core.MessagePack; +import org.msgpack.value.MapValue; +import org.msgpack.value.ValueFactory; + +import io.tarantool.core.IProtoClient; +import io.tarantool.core.protocol.IProtoRawResponse; +import io.tarantool.core.protocol.IProtoRequestOpts; +import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.core.protocol.requests.IProtoConstant; + +/** + * A stubbed {@link IProtoClient} whose ping answers are scripted by the test. + * + *

The heartbeat policy checks the availability of a node with the client of the connection view, + * so the test must be able to decide what the node answers: a successful ping, a failed ping, a + * ping that hangs forever, a ping with a specific response body, or a ping whose answer is + * delivered by the test at a chosen moment. + * + *

The answers are taken from the queue in the order of their scripting. When the queue is empty, + * the default answer is used: a successful ping for {@link #create()}, a failed ping for {@link + * #failing(Throwable)}. + */ +public final class StubClient { + + private final IProtoClient client; + private final Queue>> outcomes = + new ConcurrentLinkedQueue<>(); + private final AtomicInteger pingCount = new AtomicInteger(); + private volatile Supplier> defaultOutcome; + + private StubClient() { + this.client = Mockito.mock(IProtoClient.class); + this.defaultOutcome = StubClient::okResponse; + Mockito.when(this.client.ping(Mockito.any(IProtoRequestOpts.class))) + .thenAnswer(invocation -> nextOutcome()); + Mockito.when(this.client.ping()).thenAnswer(invocation -> nextOutcome()); + } + + /** + * Creates a stub whose ping always succeeds. + * + * @return the stub instance + */ + public static StubClient create() { + return new StubClient(); + } + + /** + * Creates a stub whose ping always fails with the given cause. + * + * @param cause the cause of the ping failure + * @return the stub instance + */ + public static StubClient failing(Throwable cause) { + final StubClient stub = new StubClient(); + stub.defaultOutcome = () -> failedResponse(cause); + return stub; + } + + /** + * Builds a response with an empty body, just like the one returned by {@code IPROTO_PING}. + * + * @return the response instance + */ + public static IProtoResponse emptyBodyResponse() { + final MapValue header = + ValueFactory.newMap( + ValueFactory.newInteger(IProtoConstant.IPROTO_REQUEST_TYPE), + ValueFactory.newInteger(IProtoConstant.IPROTO_OK)); + try (final MessageBufferPacker packer = MessagePack.newDefaultBufferPacker()) { + packer.packValue(header); + final byte[] headerBytes = packer.toByteArray(); + final byte[] packet = new byte[headerBytes.length + 1]; + System.arraycopy(headerBytes, 0, packet, 0, headerBytes.length); + // an empty map, the body of a successful IPROTO_PING response + packet[headerBytes.length] = (byte) 0x80; + return new IProtoRawResponse(header, packet, headerBytes.length); + } catch (IOException e) { + throw new IllegalStateException("Failed to build a ping response", e); + } + } + + /** + * Returns the stubbed client to be used as the client of a connection view. + * + * @return the stubbed client + */ + public IProtoClient client() { + return this.client; + } + + /** + * Makes the next ping succeed. + * + * @return this stub instance + */ + public StubClient nextPingSucceeds() { + this.outcomes.add(StubClient::okResponse); + return this; + } + + /** + * Makes the next ping fail with the given cause. + * + * @param cause the cause of the ping failure + * @return this stub instance + */ + public StubClient nextPingFails(Throwable cause) { + this.outcomes.add(() -> failedResponse(cause)); + return this; + } + + /** + * Makes the next ping hang: the returned future is never completed. + * + * @return this stub instance + */ + public StubClient nextPingHangs() { + this.outcomes.add(CompletableFuture::new); + return this; + } + + /** + * Makes the next ping return the given response. + * + * @param response the response to return + * @return this stub instance + */ + public StubClient nextPingReturns(IProtoResponse response) { + this.outcomes.add(() -> CompletableFuture.completedFuture(response)); + return this; + } + + /** + * Makes the next ping return the given future. + * + *

The future is returned as is, so the test keeps the control over the moment of the answer: + * the heartbeat reacts to the ping only when the future is completed. A future that is never + * completed makes the ping hang forever. + * + * @param future the future to return from the next ping + * @return this stub instance + */ + public StubClient nextPingReturnsFuture(CompletableFuture future) { + this.outcomes.add(() -> future); + return this; + } + + /** + * Returns the count of the pings that have been sent to the stub. + * + * @return the count of the pings + */ + public int pingCount() { + return this.pingCount.get(); + } + + private static CompletableFuture okResponse() { + return CompletableFuture.completedFuture(emptyBodyResponse()); + } + + private static CompletableFuture failedResponse(Throwable cause) { + final CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally(cause); + return failed; + } + + private CompletableFuture nextOutcome() { + this.pingCount.incrementAndGet(); + final Supplier> outcome = this.outcomes.poll(); + if (outcome == null) { + return this.defaultOutcome.get(); + } + return outcome.get(); + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/unit/availability/DefaultAvailabilityPolicyTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/unit/availability/DefaultAvailabilityPolicyTest.java new file mode 100644 index 00000000..a7ffc787 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/unit/availability/DefaultAvailabilityPolicyTest.java @@ -0,0 +1,666 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.unit.availability; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.IntConsumer; + +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +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.PoolEntryState; +import io.tarantool.pool.availability.heartbeat.DefaultAvailabilityPolicy; +import io.tarantool.pool.availability.heartbeat.HeartbeatConstants; +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.FlakyTimer; +import io.tarantool.pool.support.RecordingPoolEntryView; +import io.tarantool.pool.support.StubClient; + +/** + * The unit tests of the {@link DefaultAvailabilityPolicy} facade. + * + *

The tests cover the lifecycle of a policy: the configuration, the initialization, the startup, + * the shutdown and the restart. The heartbeat itself is covered by the tests of the state machine, + * here it is only used as an observable side effect: the policy must schedule exactly one ping per + * connection and must cancel it on the shutdown. + * + *

The whole test is synchronous: the timer is a {@link FakeTimer}, so the ping is sent only when + * the test fires it, and the stubbed client answers the ping immediately. + */ +@Timeout(value = 30) +@Execution(ExecutionMode.CONCURRENT) +@TestInstance(Lifecycle.PER_METHOD) +public class DefaultAvailabilityPolicyTest { + + private static final String TAG = "node-a"; + private static final int IDX = 1; + private static final Duration TIMEOUT = Duration.ofSeconds(5); + + private FakeTimer timer; + private MeterRegistry registry; + + @BeforeEach + void setUp() { + this.timer = new FakeTimer(); + this.registry = new SimpleMeterRegistry(); + } + + /** + * Checks that a fresh connection is available by default. + * + *

The initial state is returned by {@code initState()} and is applied to the connection by the + * library, so it must be the active one. + */ + @Test + void testInitStateReturnsActiveState() { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + final PoolEntryState state = policy.initState(view); + + Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, state); + Assertions.assertFalse(state.isLocked(), "The connection must be available by default"); + } + + /** + * Checks that the startup of an unconfigured policy fails. + * + *

The policy has no timer and no metrics until it is configured, so it must not start a + * heartbeat: the failure must be reported via the returned stage. + */ + @Test + void testStartBeforeConfigureFails() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + final Throwable cause = assertFails(policy.start(view)); + Assertions.assertInstanceOf(NullPointerException.class, cause); + } + + /** + * Checks that the startup of a policy configured without a timer fails. + * + *

The timer is guaranteed to be non-null by the library, so the policy must not work without + * it, but it must fail gracefully via the returned stage. + */ + @Test + void testStartWithNullTimerFails() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + Assertions.assertThrows(NullPointerException.class, () -> policy.configure(null, null)); + } + + /** + * Checks that the startup with a null view fails. + * + *

The view is never null by the contract of the library, so the policy must not work with it, + * but it must fail gracefully via the returned stage. + */ + @Test + void testStartWithNullViewFails() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + + policy.configure(timer, registry); + final Throwable cause = assertFails(policy.start(null)); + Assertions.assertInstanceOf(NullPointerException.class, cause); + } + + /** + * Checks that the repeated configuration keeps the timer of the first one. + * + *

The policy is configured once per pool, so the repeated configuration is not expected, but + * it must not break the already configured policy: the timer of the first configuration stays in + * use. + */ + @Test + void testRepeatedConfigureKeepsFirstTimer() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = + RecordingPoolEntryView.create(TAG, IDX, policy, StubClient.create().client()); + + final FakeTimer second = new FakeTimer(); + + policy.configure(timer, registry); + policy.configure(second, registry); + + assertSucceeds(policy.start(view)); + + Assertions.assertEquals( + 1, timer.pendingCount(), "The policy must use the timer of the first configuration"); + Assertions.assertEquals( + 0, second.pendingCount(), "The policy must ignore the second configuration"); + } + + /** + * Checks that the repeated configuration keeps the metrics of the first one. + * + *

The counters of the second registry are registered, but they are never incremented, because + * the policy works with the metrics of the first configuration. + */ + @Test + void testRepeatedConfigureKeepsFirstRegistry() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + final MeterRegistry second = new SimpleMeterRegistry(); + + policy.configure(timer, registry); + policy.configure(timer, second); + + assertSucceeds(policy.start(view)); + timer.fireNext(); + + Assertions.assertEquals( + 1, + registry.counter(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).count(), + "The first registry is in use"); + Assertions.assertEquals( + 0, + second.counter(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).count(), + "The second registry is not in use"); + } + + /** Checks that the metrics of the policy are registered in the given registry. */ + @Test + void testMetricsAreRegistered() { + final DefaultAvailabilityPolicy policy = policy(); + + policy.configure(timer, registry); + + Assertions.assertNotNull(registry.find(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).counter()); + Assertions.assertNotNull(registry.find(HeartbeatConstants.POOL_HEARTBEAT_ERRORS).counter()); + Assertions.assertNotNull(registry.find(HeartbeatConstants.POOL_HEARTBEAT_TIME).longTaskTimer()); + } + + /** + * Checks that the policy works without the metrics. + * + *

The registry is passed only if the client has specified one, so the policy must not fail + * without it and must not count the heartbeats. + */ + @Test + void testStartWithoutMetrics() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(timer, null); + + assertSucceeds(policy.start(view)); + timer.fireNext(); + + Assertions.assertEquals(1, timer.firedCount()); + } + + /** + * Checks that the repeated startup of the same connection succeeds. + * + *

The policy is started once per connection, so the repeated startup is not expected, but it + * must not fail and must not start a second heartbeat. + */ + @Test + void testRepeatedStartSucceeds() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(timer, registry); + + final List> stages = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + stages.add(policy.start(view)); + } + + for (final CompletionStage stage : stages) { + assertSucceeds(stage); + } + Assertions.assertEquals( + 1, timer.scheduledCount(), "Only one heartbeat must be started for the connection"); + } + + /** + * Checks that the repeated stop of the same connection succeeds. + * + *

The stop must be idempotent, so the repeated shutdown of the same connection must not fail. + */ + @Test + void testRepeatedStopSucceeds() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(timer, registry); + assertSucceeds(policy.start(view)); + + for (int i = 0; i < 10; i++) { + assertSucceeds(policy.stop(view)); + } + Assertions.assertEquals( + 0, timer.pendingCount(), "The pending ping must be cancelled by the shutdown"); + } + + /** + * Checks that {@code stop()} can be called on a newly created policy object without exceptions. + * + *

The library stops the policy if its startup has failed, so closing a policy that has not + * been started must not fail. + */ + @Test + void testStopWithoutStartSucceeds() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(timer, registry); + + assertSucceeds(policy.stop(view)); + + Assertions.assertTrue(view.calls().isEmpty(), "The policy must not touch the connection"); + } + + /** + * Checks that the policy may be started again after the shutdown. + * + *

The library recycles a connection with a {@code stop -> start} sequence, so the policy must + * survive it. + */ + @Test + void testStartAfterStopSucceeds() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(timer, registry); + + assertSucceeds(policy.start(view)); + assertSucceeds(policy.stop(view)); + assertSucceeds(policy.start(view)); + + Assertions.assertEquals( + 2, timer.scheduledCount(), "The restarted heartbeat must schedule a new ping"); + } + + /** + * Checks that the shutdown with a cause invalidates the connection. + * + *

The cause may be null, so it must not affect the outcome of the shutdown. + */ + @Test + void testStopInvalidatesTheConnection() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(timer, registry); + assertSucceeds(policy.start(view)); + + assertSucceeds(policy.stop(view, new IllegalStateException("the connection is gone"))); + + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + } + + /** + * Checks that the lifecycles of the different connections are independent. + * + *

The shutdown of one connection must not affect the other ones. + */ + @Test + void testViewsAreIndependent() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView first = view(policy, StubClient.create()); + final RecordingPoolEntryView second = view(policy, StubClient.create()); + + policy.configure(timer, registry); + + assertSucceeds(policy.start(first)); + assertSucceeds(policy.start(second)); + Assertions.assertEquals(2, timer.pendingCount(), "Every connection must have its own ping"); + + assertSucceeds(policy.stop(first)); + + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, first.state()); + Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, second.state()); + Assertions.assertEquals( + Collections.singletonList(HeartbeatConstants.ACTIVE_STATE_NAME), + second.stateChangeNames(), + "The shutdown of the first connection must not change the state of the second one"); + Assertions.assertEquals(0, second.reconnectCallsCount()); + Assertions.assertEquals( + 1, timer.pendingCount(), "Only the ping of the stopped connection must be cancelled"); + + // the heartbeat of the second connection keeps working + timer.fireNext(); + Assertions.assertEquals(1, registry.counter(HeartbeatConstants.POOL_HEARTBEAT_SUCCESS).count()); + Assertions.assertEquals( + 1, timer.pendingCount(), "The second connection must schedule the next ping"); + } + + /** + * Checks that the restart backoff is zero and does not touch the connection. + * + *

The policy has no backoff, so the connection must be restarted immediately. + */ + @Test + void testRestartBackoffIsZero() { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + final Duration backoff = policy.restartBackoff(view); + + Assertions.assertEquals(Duration.ZERO, backoff); + Assertions.assertTrue(view.calls().isEmpty(), "The policy must not touch the connection"); + } + + /** + * Checks that the shutdown does not wait for a ping that has not been answered. + * + *

The shutdown must complete in a bounded time even if the node is hung: the ping is in flight + * and is never answered, so the shutdown must not wait for the answer or for the request timeout. + * The stage is completed by the moment the shutdown returns, and the connection is invalidated. + * + *

The late answer must not touch the stopped connection: it is neither a success nor a failure + * for the heartbeat, even a terminal error must not kill the connection that is already closed. + */ + @Test + void testStopDoesNotWaitForHangingPing() { + assertStopCompletesWhilePingHangs(answer -> answer.complete(StubClient.emptyBodyResponse())); + } + + /** + * Checks that the connection can be restarted after a failed startup. + * + *

If the startup has failed, the machine of the connection stays in the policy in the stopped + * state, so the repeated startup fails until the library stops the policy. The library stops the + * policy after every failed startup, so after the shutdown the next startup must succeed with a + * brand-new machine. + */ + @Test + void testStartAfterFailedStartAndStopSucceeds() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + policy.configure(new FlakyTimer(timer, 1), registry); + + // the timer fails while the first ping is being scheduled + final Throwable startCause = assertFails(policy.start(view)); + Assertions.assertInstanceOf(HeartbeatException.class, startCause); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + Assertions.assertTrue( + view.listener().events().isEmpty(), + "The failed startup must not be reported as activation"); + Assertions.assertEquals(0, timer.pendingCount(), "The failed startup must not leave a ping"); + + // the dead machine is still registered: the startup without the shutdown is rejected + Assertions.assertInstanceOf(HeartbeatClosedException.class, assertFails(policy.start(view))); + + // the library stops the policy after the failed startup: the entry must be released + assertSucceeds(policy.stop(view)); + + assertSucceeds(policy.start(view)); + + Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, view.state()); + Assertions.assertEquals( + Collections.singletonList("onHeartbeatEvent:ACTIVATE"), view.listener().events()); + Assertions.assertEquals(1, timer.scheduledCount(), "The new machine must schedule the ping"); + Assertions.assertEquals(1, timer.pendingCount()); + } + + /** Checks that the policy cannot be created without the heartbeat options. */ + @Test + void testConstructorRejectsNullOptions() { + final IllegalArgumentException ex = + Assertions.assertThrows( + IllegalArgumentException.class, () -> new DefaultAvailabilityPolicy(null)); + Assertions.assertEquals("Heartbeat options must not be null!", ex.getMessage()); + } + + /** + * Checks that the options of the policy are passed to the machines of the connections. + * + *

The initial delay is the only option that is observable right after the startup: it is the + * delay of the first scheduled ping. + */ + @Test + void testInitialDelayOfOptionsIsApplied() throws Exception { + final Duration initialDelay = Duration.ofMillis(777); + final DefaultAvailabilityPolicy policy = + new DefaultAvailabilityPolicy(HeartbeatOpts.getDefault().withInitialDelay(initialDelay)); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + policy.configure(timer, registry); + + assertSucceeds(policy.start(view)); + + Assertions.assertEquals(initialDelay.toMillis(), timer.lastScheduled().delayMillis()); + } + + /** + * Checks that the thresholds of the options are applied: the connection is invalidated and killed + * exactly as the options of the policy say. + */ + @Test + void testThresholdsOfOptionsAreApplied() throws Exception { + final DefaultAvailabilityPolicy policy = + new DefaultAvailabilityPolicy( + HeartbeatOpts.getDefault() + .withWindowSize(1) + .withInvalidationThreshold(1) + .withDeathThreshold(1)); + final RecordingPoolEntryView view = + view(policy, StubClient.failing(new RuntimeException("the node does not answer"))); + policy.configure(timer, registry); + assertSucceeds(policy.start(view)); + + timer.fireNext(); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + Assertions.assertEquals(0, view.reconnectCallsCount(), "The death threshold is not reached"); + + timer.fireNext(); + Assertions.assertSame(HeartbeatConstants.KILL_STATE, view.state()); + Assertions.assertEquals(1, view.reconnectCallsCount()); + } + + /** + * Checks that a failed startup of an unconfigured policy does not break the policy. + * + *

The machine cannot be created before the policy is configured, so nothing must be registered + * for the connection. After the configuration the same connection must start normally, without + * the shutdown in between. + */ + @Test + void testStartAfterFailedStartBeforeConfigureSucceeds() throws Exception { + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + + final Throwable cause = assertFails(policy.start(view)); + Assertions.assertInstanceOf(NullPointerException.class, cause); + Assertions.assertTrue( + view.calls().isEmpty(), "The failed startup must not touch the connection"); + Assertions.assertEquals(0, timer.scheduledCount(), "The failed startup must not ping"); + + policy.configure(timer, registry); + + assertSucceeds(policy.start(view)); + + Assertions.assertSame(HeartbeatConstants.ACTIVE_STATE, view.state()); + Assertions.assertEquals( + Collections.singletonList("onHeartbeatEvent:ACTIVATE"), view.listener().events()); + Assertions.assertEquals(1, timer.scheduledCount()); + Assertions.assertEquals(1, timer.pendingCount()); + } + + /** + * Checks that a terminal failure of the hanging ping, that comes after the shutdown, is ignored. + * + * @see #testStopDoesNotWaitForHangingPing() + */ + @Test + void testTerminalFailureOfHangingPingAfterStopIsIgnored() { + assertStopCompletesWhilePingHangs( + answer -> answer.completeExceptionally(new ConnectionException("the connection is dead"))); + } + + /** + * Checks that the concurrent configuration is applied once. + * + *

All the threads try to configure the policy with their own timer, but only one timer must + * win: the connection that starts afterwards schedules its ping with it and with no other. + */ + @Test + void testConcurrentConfigureAppliesOneTimer() throws Exception { + final int threads = 16; + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + final List timers = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + timers.add(new FakeTimer()); + } + + runConcurrently(threads, i -> policy.configure(timers.get(i), registry)); + assertSucceeds(policy.start(view)); + + Assertions.assertEquals( + 1, + timers.stream().mapToInt(FakeTimer::pendingCount).sum(), + "Exactly one ping must be scheduled by the winner of the configuration"); + Assertions.assertEquals( + 1, + timers.stream().filter(t -> t.scheduledCount() > 0).count(), + "Only one timer must be in use"); + } + + /** + * Checks that the concurrent startups of the same connection run one heartbeat. + * + *

The machine is created by {@code computeIfAbsent}, so all the callers must share it. + */ + @Test + void testConcurrentStartsOfTheSameConnectionShareOneMachine() throws Exception { + final int threads = 16; + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = view(policy, StubClient.create()); + policy.configure(timer, registry); + final List> stages = Collections.synchronizedList(new ArrayList<>()); + + runConcurrently(threads, i -> stages.add(policy.start(view))); + + Assertions.assertEquals(threads, stages.size()); + for (final CompletionStage stage : stages) { + assertSucceeds(stage); + } + Assertions.assertEquals(1, timer.scheduledCount(), "Only one heartbeat must be started"); + Assertions.assertEquals( + 1, + view.listener().heartbeatEventCount(HeartbeatEvent.ACTIVATE), + "The connection must be activated once"); + } + + /** + * Runs the action in the given count of the threads that are released simultaneously. + * + *

Every task reports that it has started and then waits for the common gate, so the gate is + * opened only when all the threads are really running. + */ + private static void runConcurrently(int threads, IntConsumer action) throws Exception { + final ExecutorService executor = Executors.newFixedThreadPool(threads); + final CompletableFuture gate = new CompletableFuture<>(); + final List> started = new ArrayList<>(); + final List> finished = new ArrayList<>(); + try { + for (int i = 0; i < threads; i++) { + final int index = i; + final CompletableFuture ready = new CompletableFuture<>(); + started.add(ready); + finished.add( + CompletableFuture.runAsync( + () -> { + ready.complete(null); + gate.join(); + action.accept(index); + }, + executor)); + } + awaitAll(started); + gate.complete(null); + awaitAll(finished); + } finally { + gate.complete(null); + executor.shutdownNow(); + } + } + + private static void awaitAll(List> futures) throws Exception { + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) + .get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + + private void assertStopCompletesWhilePingHangs( + Consumer> lateAnswer) { + final CompletableFuture answer = new CompletableFuture<>(); + final DefaultAvailabilityPolicy policy = policy(); + final RecordingPoolEntryView view = + view(policy, StubClient.create().nextPingReturnsFuture(answer)); + policy.configure(timer, registry); + policy.start(view).toCompletableFuture().join(); + + timer.fireNext(); + + final CompletableFuture closeFuture = policy.stop(view).toCompletableFuture(); + + Assertions.assertTrue(closeFuture.isDone(), "The shutdown must not wait for the ping"); + Assertions.assertFalse(closeFuture.isCompletedExceptionally()); + Assertions.assertSame(HeartbeatConstants.INVALIDATE_STATE, view.state()); + + final int callsAfterStop = view.calls().size(); + lateAnswer.accept(answer); + + Assertions.assertEquals( + callsAfterStop, view.calls().size(), "The late answer must not touch the connection"); + Assertions.assertEquals(0, view.reconnectCallsCount(), "The stopped connection is not killed"); + Assertions.assertEquals(0, timer.pendingCount(), "The stopped policy must not ping anymore"); + } + + /** Creates {@link DefaultAvailabilityPolicy} with {@link HeartbeatOpts#getDefault()}. */ + private DefaultAvailabilityPolicy policy() { + return new DefaultAvailabilityPolicy(HeartbeatOpts.getDefault()); + } + + /** Creates {@link RecordingPoolEntryView} with {@link #TAG}, {@link #IDX}. */ + private RecordingPoolEntryView view(DefaultAvailabilityPolicy policy, StubClient client) { + return RecordingPoolEntryView.create(TAG, IDX, policy, client.client()); + } + + private static void assertSucceeds(CompletionStage stage) throws Exception { + Assertions.assertNotNull(stage, "The policy must return a stage"); + stage.toCompletableFuture().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + + private static Throwable assertFails(CompletionStage stage) throws Exception { + Assertions.assertNotNull(stage, "The policy must return a stage"); + final CompletableFuture future = stage.toCompletableFuture(); + final ExecutionException ex = + Assertions.assertThrows( + ExecutionException.class, () -> future.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + return ex.getCause(); + } +}