connects, int count) {
for (int i = connects.size() - 1; i >= count; i--) {
PoolEntry entry = connects.remove(i);
if (entry != null) {
- entry.unlock();
entry.close();
}
}
diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntry.java b/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntry.java
index 2cacdd2d..fe1aa291 100644
--- a/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntry.java
+++ b/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntry.java
@@ -5,9 +5,12 @@
package io.tarantool.pool;
-import java.util.ArrayDeque;
+import java.time.Duration;
+import java.util.Objects;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import io.micrometer.core.instrument.Counter;
@@ -15,158 +18,129 @@
import io.micrometer.core.instrument.MeterRegistry;
import io.netty.util.Timeout;
import io.netty.util.Timer;
-import org.msgpack.value.impl.ImmutableBooleanValueImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static io.tarantool.core.protocol.requests.IProtoConstant.IPROTO_DATA;
import io.tarantool.core.IProtoClient;
import io.tarantool.core.IProtoClientImpl;
import io.tarantool.core.WatcherOptions;
import io.tarantool.core.connection.ConnectionCloseEvent;
import io.tarantool.core.connection.ConnectionFactory;
-import io.tarantool.core.connection.exceptions.ConnectionException;
import io.tarantool.core.protocol.Handlers;
-import io.tarantool.core.protocol.IProtoRequestOpts;
import io.tarantool.core.protocol.IProtoResponse;
import io.tarantool.pool.IProtoClientPoolImpl.ConnectionStatistics;
+import io.tarantool.pool.availability.AvailabilityPolicy;
+import io.tarantool.pool.availability.Metadata;
+import io.tarantool.pool.entry.ConnectionMetrics;
+import io.tarantool.pool.entry.ConnectionSession;
+import io.tarantool.pool.entry.ConnectionSession.SessionOutcome;
+import io.tarantool.pool.exceptions.PoolClosedException;
/**
* Client/connection controller for pool.
*
- * This class manages its own instance of {@link io.tarantool.core.IProtoClient}, starts
- * heartbeats if need, controls invalidation and reconnection process.
+ *
This class is a long-living supervisor: it owns the {@link IProtoClient}, the current {@link
+ * PoolEntryState} and the statistics. Every connection attempt is a one-shot {@link
+ * ConnectionSession}, which connects the client and manages the {@link AvailabilityPolicy}
+ * lifecycle. When a session finishes with a failure, the entry waits {@code reconnectAfter} and
+ * creates a new one. Reconnection is infinite. Every session has its own {@link PoolEntryView}, so
+ * a stale task of the policy of a finished session cannot affect the next one.
*
* @author Ivan Bannikov
*/
-final class PoolEntry {
-
- /**
- * IProto options for first request for checking connection liveness.
- *
- * @see io.tarantool.core.protocol.IProtoRequestOpts
- */
- private static final IProtoRequestOpts firstPingOpts =
- IProtoRequestOpts.empty().withRequestTimeout(1000);
+final class PoolEntry implements AutoCloseable {
/** Logger instance. */
- private static final Logger log = LoggerFactory.getLogger(PoolEntry.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(PoolEntry.class);
- /** Deque for sliding window. */
- private final ArrayDeque window;
+ /** The time {@link #close()} waits for the current session to finish. */
+ private static final Duration CLOSE_TIMEOUT = Duration.ofSeconds(30);
+ /** Statistics on unavailable and reconnecting connections. Shared by all entries, thread-safe. */
private final ConnectionStatistics connectionStatistics;
- /**
- * Options for heartbeats.
- *
- * @see io.tarantool.pool.HeartbeatOpts
- */
- private final HeartbeatOpts heartbeatOpts;
-
- /** Instance of {@link io.tarantool.core.IProtoClient}. */
- private final IProtoClient client;
-
- /**
- * IProto options for ping requests,
- *
- * @see io.tarantool.core.protocol.IProtoRequestOpts
- */
- private final IProtoRequestOpts heartbeatPingOpts;
-
- /** Handlers for request/response lifecycle events. */
- private final Handlers handlers;
-
- /** Instance of {@link io.tarantool.pool.InstanceConnectionGroup}. */
- private final InstanceConnectionGroup group;
-
- /** Tag from group. */
- private final String tag;
+ /** Metrics of {@link PoolEntry}. May be null. */
+ private final PoolEntryMetrics metrics;
- /**
- * Instance of netty HashedWheelTimer.
- *
- * Required for heartbeats and reconnecting tasks.
- */
+ /** Instance of netty HashedWheelTimer. Required for reconnecting tasks and for sessions. */
private final Timer timerService;
- /** Flag for graceful shutdown handling. */
- private final boolean gracefulShutdown;
-
- /** Index of entry within group. */
- private final int index;
-
/** Time in milliseconds after that reconnect task will be executed. */
private final long reconnectAfter;
- /** Parameter that will say tarantool not to use Tuple Extension. */
- private final boolean useTupleExtension;
+ /** Connect timeout in milliseconds. Sets by pool, is applied to the next session. */
+ private volatile long connectTimeout;
- /** Metrics registry. */
- private final MeterRegistry metricsRegistry;
+ /** Instance of {@link io.tarantool.core.IProtoClient}. It outlives the sessions. */
+ private final IProtoClient client;
+
+ /** Flag for graceful shutdown handling. */
+ private final boolean gracefulShutdown;
/** Optional listener for pool events. */
private final PoolEventListener poolEventListener;
- /**
- * Connection future.
- *
- *
It will be returned to all out clients wanting to obtain this client. It is recreated only
- * if client is reconnected.
- */
- private CompletableFuture connectFuture;
+ /** The group of the entry and the index of the entry within the group. */
+ private final Metadata metadata;
- /** Last heartbeat state/event. */
- private HeartbeatEvent lastHeartbeatEvent;
+ private final String identity;
- /** Heartbeat timer/task. */
- private Timeout heartbeatTask;
+ /**
+ * The availability policy of the entry. It is started for every session and stopped when the
+ * session finishes; it controls the availability state of the entry through the session view.
+ */
+ private final AvailabilityPolicy policy;
- /** Reconnection task. */
- private Timeout reconnectTask;
+ /**
+ * The view that was passed to {@link AvailabilityPolicy#initState(PoolEntryView)}. It is handed
+ * over to the first session, so the initial view is the view of the first session. Every next
+ * session gets its own view. Guarded by {@link #lock}.
+ */
+ private SessionView initialView;
- /** Flag signaling if heartbeat started or not. */
- private boolean isHeartbeatStarted;
+ /**
+ * Guards {@link #isClosed}, {@link #isReconnecting}, {@link #reconnectTask}, {@link #initialView}
+ * and the statistics.
+ */
+ private final Object lock = new Object();
/**
- * Flag signaling if connection is available or not.
- *
- * When connection comes to invalidated state or killed, pool entry is locked and connection
- * will not be returned to outer client.
+ * The current availability state. The only source of truth for {@link #isLocked()}. The initial
+ * value is set by the policy, then it is changed by the policy and by the sessions.
*/
- private boolean isLocked;
+ private volatile PoolEntryState state;
- /** Count of failed pings occurred in invalidated state. */
- private int currentDeathPings;
+ /** The current session. The client close events are routed to it. */
+ private volatile ConnectionSession session;
- /** Count of failed pings within window. */
- private int currentFailedPings;
+ /**
+ * The connect future of the current session. It is returned to all outer clients wanting to
+ * obtain this client. It is recreated for every session.
+ */
+ private volatile CompletableFuture connectFuture;
- /** Unix timestamp for correcting ping scheduling. */
- private long lastPingTs;
+ /** Reconnection task. Guarded by {@link #lock}. */
+ private Timeout reconnectTask;
/**
- * Connect timeout in milliseconds.
- *
- * Sets by pool.
+ * True from the first failed session until the next successful connect (or close). It is the
+ * source of the {@code reconnecting} statistics. Guarded by {@link #lock}.
*/
- private long connectTimeout;
+ private boolean isReconnecting;
- /** Metrics of {@link PoolEntry}. */
- private final PoolEntryMetrics metrics;
+ /** True after {@link #close()}. Guarded by {@link #lock}. */
+ private boolean isClosed;
/**
* Constructor for PoolEntry.
*
* @param factory instance of {@link io.tarantool.core.connection.ConnectionFactory}
* @param timerService instance of HashedWheelTimer
- * @param group instance of {@link io.tarantool.pool.InstanceConnectionGroup}
- * @param index index of pool entry within group
+ * @param metadata the group and the index of the entry within the group
* @param gracefulShutdown a boolean flag for graceful shutdown
* @param connectTimeout connection timeout in milliseconds
* @param reconnectAfter reconnect time in milliseconds
- * @param heartbeatOpts options for heartbeats, instance of {@link
- * io.tarantool.pool.HeartbeatOpts}
+ * @param policy the availability policy of the entry
* @param watcherOpts options for connection watcher, instance of {@link
* io.tarantool.core.WatcherOptions}
* @param connectionStatistics statistics on unavailable and reconnecting connections. Class is
@@ -179,12 +153,11 @@ final class PoolEntry {
public PoolEntry(
ConnectionFactory factory,
Timer timerService,
- InstanceConnectionGroup group,
- int index,
+ Metadata metadata,
boolean gracefulShutdown,
long connectTimeout,
long reconnectAfter,
- HeartbeatOpts heartbeatOpts,
+ AvailabilityPolicy policy,
WatcherOptions watcherOpts,
ConnectionStatistics connectionStatistics,
MeterRegistry registry,
@@ -193,46 +166,105 @@ public PoolEntry(
boolean useTupleExtension,
PoolEventListener poolEventListener,
PoolEntryMetrics metrics) {
- this.metrics = metrics;
- this.metricsRegistry = registry;
- this.handlers = handlers;
- this.client =
+ this(
new IProtoClientImpl(
factory,
timerService,
watcherOpts,
registry,
- group.getFlushConsolidationHandler(),
- useTupleExtension);
+ Objects.requireNonNull(metadata, "metadata must not be null!")
+ .settings()
+ .getFlushConsolidationHandler(),
+ useTupleExtension),
+ timerService,
+ metadata,
+ gracefulShutdown,
+ connectTimeout,
+ reconnectAfter,
+ policy,
+ connectionStatistics,
+ registry,
+ ignoredPacketsHandler,
+ handlers,
+ poolEventListener,
+ metrics);
+ }
+
+ /**
+ * Constructor for PoolEntry with a ready client.
+ *
+ *
The entry works with the given client instead of creating its own one. It is intended for
+ * tests that need to script the client, so they do not need a network. The client must not be
+ * shared with another entry.
+ *
+ * @param client the client of the entry. The entry registers its listeners and handlers in it and
+ * closes it when the entry is closed
+ * @param timerService instance of HashedWheelTimer
+ * @param metadata the group and the index of the entry within the group
+ * @param gracefulShutdown a boolean flag for graceful shutdown
+ * @param connectTimeout connection timeout in milliseconds
+ * @param reconnectAfter reconnect time in milliseconds
+ * @param policy the availability policy of the entry
+ * @param connectionStatistics statistics on unavailable and reconnecting connections. Class is
+ * thread-safe.
+ * @param registry instance of {@code io.micrometer.core.instrument.MeterRegistry}, may be null
+ * @param ignoredPacketsHandler callback for accepting packets which were ignored by IProtoClient
+ * connections, may be null.
+ * @param handlers handlers for the request/response lifecycle events, may be null
+ * @param poolEventListener optional listener for pool events
+ * @param metrics metrics of the entry, may be null
+ */
+ PoolEntry(
+ IProtoClient client,
+ Timer timerService,
+ Metadata metadata,
+ boolean gracefulShutdown,
+ long connectTimeout,
+ long reconnectAfter,
+ AvailabilityPolicy policy,
+ ConnectionStatistics connectionStatistics,
+ MeterRegistry registry,
+ TripleConsumer ignoredPacketsHandler,
+ Handlers handlers,
+ PoolEventListener poolEventListener,
+ PoolEntryMetrics metrics) {
+ this.metadata = Objects.requireNonNull(metadata, "metadata must not be null!");
+ this.policy = Objects.requireNonNull(policy, "policy must not be null!");
+ this.metrics = metrics;
+ this.client = Objects.requireNonNull(client, "client must not be null!");
this.client.withHandlers(handlers);
- // heartbeat related
- this.isHeartbeatStarted = false;
- this.lastHeartbeatEvent = HeartbeatEvent.KILL;
- this.heartbeatOpts = heartbeatOpts;
- if (heartbeatOpts != null) {
- this.window = new ArrayDeque<>(heartbeatOpts.getWindowSize());
- this.heartbeatPingOpts =
- IProtoRequestOpts.empty().withRequestTimeout(heartbeatOpts.getPingInterval());
- } else {
- this.window = null;
- this.heartbeatPingOpts = null;
- }
this.connectTimeout = connectTimeout;
this.gracefulShutdown = gracefulShutdown;
- this.group = group;
- this.index = index;
- this.isLocked = false;
this.reconnectAfter = reconnectAfter;
- this.tag = group.getTag();
this.timerService = timerService;
this.connectionStatistics = connectionStatistics;
- this.client.onClose(ConnectionCloseEvent.CLOSE_BY_REMOTE, this::handleConnectError);
- this.client.onClose(ConnectionCloseEvent.CLOSE_BY_SHUTDOWN, this::handleConnectError);
- this.useTupleExtension = useTupleExtension;
this.poolEventListener = poolEventListener;
+ // The listeners cannot be removed from the client, so they are registered once and routed to
+ // the current session. A stale event can not reach a newer session: the client fires the close
+ // event before it allows the next connect.
+ this.client.onClose(ConnectionCloseEvent.CLOSE_BY_REMOTE, (c, exc) -> onRemoteClosed(exc));
+ this.client.onClose(ConnectionCloseEvent.CLOSE_BY_SHUTDOWN, (c, exc) -> onRemoteClosed(exc));
if (ignoredPacketsHandler != null) {
- client.onIgnoredPacket(packet -> ignoredPacketsHandler.accept(this.tag, this.index, packet));
+ final String tag = this.metadata.settings().getTag();
+ final int index = this.metadata.index();
+ client.onIgnoredPacket(p -> ignoredPacketsHandler.accept(tag, index, p));
+ }
+
+ this.identity = this.metadata.settings().getTag() + '/' + this.metadata.index();
+ this.policy.configure(this.timerService, registry);
+ final SessionView view = new SessionView();
+ // The state does not exist yet: the policy must return it instead of changing it.
+ view.forbidMutations();
+ try {
+ this.state =
+ Objects.requireNonNull(this.policy.initState(view), "initial state must not be null!");
+ } finally {
+ view.allowMutations();
+ }
+ this.initialView = view;
+ if (this.state.isLocked()) {
+ this.connectionStatistics.incrementUnavailable();
}
}
@@ -241,347 +273,371 @@ public PoolEntry(
*
* @return instance of {@link io.tarantool.core.IProtoClient}
*/
- public IProtoClient getClient() {
+ public IProtoClient client() {
return client;
}
/**
- * Method for locking pool entry.
+ * Whether the entry is hidden from the load balancer.
*
- * Also increments count of unavailable clients.
+ * @return {@code true} if the current {@link PoolEntryState} is locked.
*/
- public void lock() {
- if (!isLocked) {
- this.connectionStatistics.incrementUnavailable();
- isLocked = true;
- }
+ public boolean isLocked() {
+ return this.state.isLocked();
}
/**
- * Method for unlocking pool entry.
+ * Setter for {@link #connectTimeout}. It is applied to the next connection attempt.
*
- *
Also decrements count of unavailable clients and cancels reconnect task.
+ * @param timeout connect timeout in milliseconds
*/
- public void unlock() {
- if (isLocked) {
- stopReconnectTask();
- this.connectionStatistics.decrementUnavailable();
- isLocked = false;
- }
+ public void setConnectTimeout(long timeout) {
+ this.connectTimeout = timeout;
}
/**
- * Getter for {@link #isLocked}.
+ * Starts the connection process (once) and returns the future of the current session.
+ *
+ *
The future is completed when the client is connected, without waiting for the availability
+ * policy. While the entry waits for a reconnect, the future of the failed session is returned.
*
- * @return {@link #isLocked} value.
+ * @return {@link java.util.concurrent.CompletableFuture} with client
*/
- public boolean isLocked() {
- return isLocked;
- }
-
- /** Closes client and stops heartbeat and reconnect tasks if started. */
- public void close() {
- stopReconnectTask();
- shutdown();
- }
-
- /** Closes client and stops heartbeat task is started. */
- public void shutdown() {
- connectFuture = null;
- stopHeartbeat();
- try {
- client.close();
- } catch (Exception e) {
- log.warn("Cannot close client in pool", e);
+ public CompletableFuture connect() {
+ final CompletableFuture result = new CompletableFuture<>();
+ final ConnectionSession s;
+ synchronized (this.lock) {
+ if (this.isClosed) {
+ result.completeExceptionally(new PoolClosedException("Pool entry is closed!"));
+ return result;
+ }
+ if (this.connectFuture != null) {
+ return this.connectFuture;
+ }
+ s = createSessionLocked(result);
}
- emit(listener -> listener.onConnectionClosed(tag, index));
+ runSession(s, result);
+ return result;
}
/**
- * Start client connection process and returns futures.
- *
- * @return {@link java.util.concurrent.CompletableFuture} with client
+ * Closes the session and stops the reconnect task. Waits up to {@link #CLOSE_TIMEOUT} minutes for
+ * the session to finish: the policy is stopped and the client is closed. Does not throw, a
+ * failure or a timeout is logged. Must not be called from an event loop thread.
*/
- public synchronized CompletableFuture connect() {
- if (connectFuture != null) {
- return connectFuture;
+ @Override
+ public void close() {
+ try {
+ closeAsync().get(CLOSE_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ LOGGER.warn("Interrupted while closing the pool entry {}", this.identity, e);
+ } catch (ExecutionException | TimeoutException e) {
+ LOGGER.warn("Cannot close the pool entry {} properly", this.identity, e);
}
- return internalConnect();
}
/**
- * Setter for {@link #connectTimeout}.
+ * Closes the entry for good: stops the reconnect task and closes the current session (the policy
+ * is stopped, then the client is closed). Idempotent.
*
- * @param timeout connect timeout in milliseconds
+ * @return the future that is completed when the session is finished
*/
- public void setConnectTimeout(long timeout) {
- this.connectTimeout = timeout;
- }
-
- /** Heartbeat starter. */
- public void startHeartbeat() {
- if (isHeartbeatStarted || heartbeatOpts == null) {
- return;
+ CompletableFuture closeAsync() {
+ final ConnectionSession s;
+ synchronized (this.lock) {
+ if (this.isClosed) {
+ return CompletableFuture.completedFuture(null);
+ }
+ this.isClosed = true;
+ cancelReconnectLocked();
+ // the entry is leaving the pool: it must not be counted as unavailable anymore.
+ if (this.state.isLocked()) {
+ this.connectionStatistics.decrementUnavailable();
+ }
+ s = this.session;
+ }
+ if (s != null) {
+ return s.close();
}
- log.info(
- "heartbeat: start for {}/{}: failures = {}, interval = {}, death pings = {}",
- tag,
- index,
- heartbeatOpts.getInvalidationThreshold(),
- heartbeatOpts.getPingInterval(),
- heartbeatOpts.getDeathThreshold());
- isHeartbeatStarted = true;
- window.clear();
- // heartbeat is being started immediately after first check so it is
- // not neccessary to send yet another ping again but just put success
- // mark to window
- window.addFirst(0);
- currentDeathPings = 0;
- currentFailedPings = 0;
- fire(HeartbeatEvent.ACTIVATE);
- heartbeatTask =
- timerService.newTimeout(
- this::ping, heartbeatOpts.initialDelay().toNanos(), TimeUnit.NANOSECONDS);
+ final String tag = this.metadata.settings().getTag();
+ final int index = this.metadata.index();
+ emit(listener -> listener.onConnectionClosed(tag, index));
+ return CompletableFuture.completedFuture(null);
}
- /** Heartbeat stopper. */
- public void stopHeartbeat() {
- isHeartbeatStarted = false;
- if (heartbeatTask != null) {
- heartbeatTask.cancel();
- heartbeatTask = null;
- }
+ /** Must be called under {@link #lock}. The session must be started by {@link #runSession}. */
+ private ConnectionSession createSessionLocked(CompletableFuture result) {
+ final SessionView sessionView = this.initialView != null ? this.initialView : new SessionView();
+ this.initialView = null;
+ final ConnectionSession s =
+ new ConnectionSession(
+ sessionView,
+ this.policy,
+ this.timerService,
+ this.connectTimeout,
+ this.gracefulShutdown,
+ this.metrics,
+ outcome -> {
+ // The view must be closed before the entry reacts: from now on a stale task of the
+ // policy can not change the state, even while the entry waits for the reconnect.
+ sessionView.markFinished();
+ onSessionFinished(outcome);
+ });
+ sessionView.bind(s);
+ this.session = s;
+ this.connectFuture = result;
+ return s;
}
- /**
- * Internal method used by reconnect task and public connect.
- *
- * @return {@link java.util.concurrent.CompletableFuture} with client
- */
- private CompletableFuture internalConnect() {
- log.info("connect {}/{}", tag, index);
- final LongTaskTimer.Sample timer =
- this.metrics != null ? this.metrics.poolConnectTime.start() : null;
- CompletableFuture> future =
- client.connect(group.getAddress(), connectTimeout, gracefulShutdown);
- String user = group.getUser();
- connectFuture =
- future
- .thenCompose(
- greeting -> {
- PoolEntryMetrics.stopTimer(timer);
- if (user != null) {
- return client.authorize(user, group.getPassword(), group.getAuthType());
+ /** Starts the session outside the lock: the session calls listeners and the policy. */
+ private void runSession(ConnectionSession s, CompletableFuture result) {
+ s.connect()
+ .whenComplete(
+ (c, ex) -> {
+ if (ex == null) {
+ synchronized (this.lock) {
+ if (this.isReconnecting) {
+ this.isReconnecting = false;
+ this.connectionStatistics.decrementReconnecting();
}
- return client.ping(firstPingOpts);
- })
- .thenCompose(r -> client.awaitConnectionReady())
- .thenApply(r -> client)
- .whenComplete(this::onConnectComplete);
- return connectFuture;
+ }
+ result.complete(c);
+ } else {
+ result.completeExceptionally(ex);
+ }
+ });
}
- /**
- * Callback for {@link java.util.concurrent.CompletableFuture#whenComplete}.
- *
- * Handles connection error if occurred, starts heartbeat.
- *
- * @param r any result of connection operation
- * @param exc exception occurred during connection process
- */
- private void onConnectComplete(Object r, Throwable exc) {
- if (this.metrics != null) {
- this.metrics.incrementPoolConnectMetrics(exc);
+ /** The client has been closed by the remote side or by a shutdown. */
+ private void onRemoteClosed(Throwable exc) {
+ final ConnectionSession s = this.session;
+ if (s != null) {
+ s.remoteClosed(exc);
}
+ }
- if (exc != null) {
- handleConnectError(r, exc);
+ /** Is called by a finished session from its event loop: must not block. */
+ private void onSessionFinished(SessionOutcome outcome) {
+ if (outcome.isClosedByUser()) {
return;
}
- startHeartbeat();
- unlock();
- log.info("connected {}/{}", tag, index);
- emit(listener -> listener.onConnectionOpened(tag, index));
+ final String tag = this.metadata.settings().getTag();
+ final int index = this.metadata.index();
+ final Throwable cause = outcome.cause();
+
+ final boolean scheduled;
+ synchronized (this.lock) {
+ if (this.isClosed) {
+ return;
+ }
+ scheduled = scheduleReconnectLocked();
+ }
+ if (cause != null) {
+ emit(listener -> listener.onConnectionFailed(tag, index, cause));
+ }
+ if (scheduled) {
+ LOGGER.info("reconnect {}/{} after {} ms", tag, index, this.reconnectAfter);
+ emit(listener -> listener.onReconnectScheduled(tag, index, this.reconnectAfter));
+ }
}
/**
- * Handler for connection close.
+ * Schedules the reconnect. The entry is counted as reconnecting only if the reconnect is really
+ * scheduled. Must be called under {@link #lock}.
*
- * @param r connection instance
- * @param exc exception which led to connection close
+ * @return {@code false} if the timer has refused the task (it is stopped: the pool is closing).
+ * Nothing is going to reconnect the entry then, so it is not counted as reconnecting.
*/
- private void handleConnectError(Object r, Throwable exc) {
- if (exc == null) {
- return;
+ private boolean scheduleReconnectLocked() {
+ try {
+ this.reconnectTask =
+ this.timerService.newTimeout(
+ timeout -> reconnect(), this.reconnectAfter, TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ LOGGER.warn("Cannot schedule the reconnect of {}", this.identity, e);
+ if (this.isReconnecting) {
+ this.isReconnecting = false;
+ this.connectionStatistics.decrementReconnecting();
+ }
+ return false;
}
- Throwable failure = exc.getCause() != null ? exc.getCause() : exc;
- connectFuture = null;
- log.error("connect error {}/{}: {}", tag, index, failure.toString());
- emit(listener -> listener.onConnectionFailed(tag, index, failure));
- lock();
- shutdown();
- connectAfter();
- }
-
- /** Reconnect task scheduler. */
- private void connectAfter() {
- log.info("reconnect {}/{} after {} ms", tag, index, reconnectAfter);
- if (reconnectTask == null) {
+ if (!this.isReconnecting) {
+ this.isReconnecting = true;
this.connectionStatistics.incrementReconnecting();
}
- reconnectTask =
- timerService.newTimeout(
- timeout -> internalConnect(), reconnectAfter, TimeUnit.MILLISECONDS);
- emit(listener -> listener.onReconnectScheduled(tag, index, reconnectAfter));
+ return true;
}
- /**
- * Run ping request.
- *
- * @param handler timeout handler
- */
- private void ping(Timeout handler) {
- lastPingTs = System.currentTimeMillis();
- final LongTaskTimer.Sample timer =
- this.metrics != null ? this.metrics.heartbeatTime.start() : null;
- heartbeatOpts
- .getPingFunction()
- .apply(client, this.heartbeatPingOpts)
- .whenComplete(
- (r, exc) -> {
- PoolEntryMetrics.stopTimer(timer);
- pong(r, exc);
- });
+ private void reconnect() {
+ final CompletableFuture result = new CompletableFuture<>();
+ final ConnectionSession s;
+ synchronized (this.lock) {
+ if (this.isClosed) {
+ return;
+ }
+ this.reconnectTask = null;
+ s = createSessionLocked(result);
+ }
+ runSession(s, result);
}
- /** Schedules next ping. */
- private void nextPing() {
- long delta = heartbeatOpts.getPingInterval() - (System.currentTimeMillis() - lastPingTs);
- if (delta <= 0) {
- ping(null);
- } else {
- heartbeatTask = timerService.newTimeout(this::ping, delta, TimeUnit.MILLISECONDS);
+ /** Must be called under {@link #lock}. */
+ private void cancelReconnectLocked() {
+ if (this.reconnectTask != null) {
+ this.reconnectTask.cancel();
+ this.reconnectTask = null;
+ }
+ if (this.isReconnecting) {
+ this.isReconnecting = false;
+ this.connectionStatistics.decrementReconnecting();
}
}
/**
- * Handler for ping response.
- *
- * @param result result of ping operation
- * @param exc exception
+ * Sets a new availability state. Idempotent. The {@code unavailable} statistics are updated when
+ * the locked flag changes. After {@link #close()} the statistics are not touched.
*/
- private void pong(IProtoResponse result, Throwable exc) {
- nextPing();
-
- int failure = 0;
- if (exc != null) {
- failure = 1;
- Throwable error = exc.getCause();
- if (error instanceof ConnectionException) {
- String msg = error.getMessage();
- if (msg.startsWith("Connection")) {
- stopHeartbeat();
- return;
+ private void changeState(PoolEntryState newState) {
+ Objects.requireNonNull(newState, "state must not be null!");
+ final PoolEntryState old;
+ synchronized (this.lock) {
+ old = this.state;
+ if (old.equals(newState)) {
+ return;
+ }
+ this.state = newState;
+ if (!this.isClosed) {
+ if (old.isLocked() && !newState.isLocked()) {
+ this.connectionStatistics.decrementUnavailable();
+ } else if (!old.isLocked() && newState.isLocked()) {
+ this.connectionStatistics.incrementUnavailable();
}
}
- } else if (!result.isBodyEmpty()
- && !result.getBodyArrayValue(IPROTO_DATA).get(0).equals(ImmutableBooleanValueImpl.TRUE)) {
- failure = 1;
- }
- PoolEntryMetrics.incrementHeartbeatMetrics(this.metrics, failure);
-
- window.addFirst(failure);
- currentFailedPings += failure;
- if (window.size() > heartbeatOpts.getWindowSize()) {
- currentFailedPings -= window.removeLast();
- } else if (window.size() < heartbeatOpts.getWindowSize()) {
- return;
}
+ LOGGER.debug("[{}]: state {} -> {}", this.identity, old.name(), newState.name());
+ }
- if (currentFailedPings >= heartbeatOpts.getInvalidationThreshold()) {
- fire(HeartbeatEvent.INVALIDATE);
- currentDeathPings++;
- if (currentDeathPings > heartbeatOpts.getDeathThreshold()) {
- fire(HeartbeatEvent.KILL);
+ /**
+ * Calls listener callback if listener present.
+ *
+ * @param action action to perform
+ */
+ private void emit(Consumer action) {
+ if (poolEventListener != null) {
+ try {
+ action.accept(poolEventListener);
+ } catch (Exception e) {
+ LOGGER.error(
+ "An unexpected exception was caught while executing an alert in PoolEventListener."
+ + " Ignoring...",
+ e);
}
- return;
}
-
- fire(HeartbeatEvent.ACTIVATE);
- currentDeathPings = 0;
}
/**
- * Switcher for connection states.
+ * The view of a single session, for the availability policy and for the session itself.
*
- * @param event value of {@link io.tarantool.pool.HeartbeatEvent} enum.
+ * The mutating calls ({@code changeState}, {@code reconnect}, {@code emit}) of a view whose
+ * session is not the current one anymore are ignored: a stale policy task must not affect a newer
+ * session. The calls made before the view is bound to its session are accepted, except for the
+ * calls made inside {@link AvailabilityPolicy#initState(PoolEntryView)}: the entry has no state
+ * yet, so such calls fail with {@link IllegalStateException}.
*/
- private void fire(HeartbeatEvent event) {
- if (lastHeartbeatEvent == event) {
- return;
+ private final class SessionView implements PoolEntryView {
+
+ private volatile ConnectionSession boundSession;
+
+ /** True while the policy computes the initial state. */
+ private volatile boolean mutationsForbidden;
+
+ /** True after the session is finished: all the mutating calls are ignored. */
+ private volatile boolean finished;
+
+ void markFinished() {
+ this.finished = true;
}
- lastHeartbeatEvent = event;
- emit(listener -> listener.onHeartbeatEvent(tag, index, event));
- switch (event) {
- case INVALIDATE:
- lock();
- log.info("heartbeat: connection {}/{} is invalid", tag, index);
- break;
- case ACTIVATE:
- unlock();
- log.info("heartbeat: connection {}/{} is ok", tag, index);
- break;
- case KILL:
- shutdown();
- log.warn("heartbeat: close connection {}/{}", tag, index);
- connectAfter();
- break;
+ void bind(ConnectionSession session) {
+ this.boundSession = session;
}
- }
- /** Stops reconnecting task if it is active. */
- private void stopReconnectTask() {
- if (reconnectTask != null) {
- this.connectionStatistics.decrementReconnecting();
- reconnectTask.cancel();
- reconnectTask = null;
+ void forbidMutations() {
+ this.mutationsForbidden = true;
}
- }
- /**
- * Calls listener callback if listener present.
- *
- * @param action action to perform
- */
- private void emit(Consumer action) {
- if (poolEventListener != null) {
- action.accept(poolEventListener);
+ void allowMutations() {
+ this.mutationsForbidden = false;
}
- }
- /** {@link PoolEntry} metrics. */
- static class PoolEntryMetrics {
+ private void checkMutationsAllowed(String method) {
+ if (this.mutationsForbidden) {
+ throw new IllegalStateException(
+ method
+ + " is not allowed in AvailabilityPolicy#initState: return the initial state"
+ + " instead.");
+ }
+ }
- static final String POOL_HEARTBEAT_SUCCESS_METRIC = "pool.heartbeat.success";
- static final String POOL_HEARTBEAT_SUCCESS_METRIC_DESC =
- "Total count of successful heartbeat ping requests";
+ private boolean isStale() {
+ if (this.finished) {
+ return true;
+ }
+ final ConnectionSession bound = this.boundSession;
+ return bound != null && bound != PoolEntry.this.session;
+ }
- /** Count of successful heartbeat ping requests. */
- private final Counter heartbeatSuccess;
+ @Override
+ public void changeState(PoolEntryState state) {
+ checkMutationsAllowed("changeState()");
+ if (isStale()) {
+ LOGGER.debug(
+ "[{}]: ignore changeState({}) from a stale view", PoolEntry.this.identity, state);
+ return;
+ }
+ PoolEntry.this.changeState(state);
+ }
- static final String POOL_HEARTBEAT_ERRORS_METRIC = "pool.heartbeat.errors";
- static final String POOL_HEARTBEAT_ERRORS_METRIC_DESC =
- "Total count of failed heartbeat ping requests";
+ @Override
+ public Metadata metadata() {
+ return PoolEntry.this.metadata;
+ }
- /** Count of failed heartbeat ping requests. */
- private final Counter heartbeatErrors;
+ @Override
+ public PoolEntryState state() {
+ return PoolEntry.this.state;
+ }
- static final String POOL_HEARTBEAT_TIME_METRIC = "pool.heartbeat.time";
- static final String POOL_HEARTBEAT_TIME_METRIC_DESC = "Time of ping request";
+ @Override
+ public IProtoClient client() {
+ return PoolEntry.this.client;
+ }
- /** Time of ping request. */
- private final LongTaskTimer heartbeatTime;
+ @Override
+ public void reconnect() {
+ checkMutationsAllowed("reconnect()");
+ final ConnectionSession s = this.boundSession;
+ if (s == null || isStale()) {
+ LOGGER.debug(
+ "[{}]: ignore reconnect() from a stale or unbound view", PoolEntry.this.identity);
+ return;
+ }
+ s.reconnect(null);
+ }
+
+ @Override
+ public void emit(Consumer action) {
+ checkMutationsAllowed("emit()");
+ if (isStale()) {
+ return;
+ }
+ PoolEntry.this.emit(action);
+ }
+ }
+
+ /** {@link PoolEntry} metrics. */
+ static class PoolEntryMetrics implements ConnectionMetrics {
static final String POOL_CONNECT_SUCCESS_METRIC = "pool.connect.success";
static final String POOL_CONNECT_SUCCESS_METRIC_DESC = "Total count of succeeded connects";
@@ -603,21 +659,6 @@ static class PoolEntryMetrics {
public PoolEntryMetrics(MeterRegistry registry) {
- this.heartbeatSuccess =
- Counter.builder(POOL_HEARTBEAT_SUCCESS_METRIC)
- .description(POOL_HEARTBEAT_SUCCESS_METRIC_DESC)
- .register(registry);
-
- this.heartbeatErrors =
- Counter.builder(POOL_HEARTBEAT_ERRORS_METRIC)
- .description(POOL_HEARTBEAT_ERRORS_METRIC_DESC)
- .register(registry);
-
- this.heartbeatTime =
- LongTaskTimer.builder(POOL_HEARTBEAT_TIME_METRIC)
- .description(POOL_HEARTBEAT_TIME_METRIC_DESC)
- .register(registry);
-
this.poolConnectSuccess =
Counter.builder(POOL_CONNECT_SUCCESS_METRIC)
.description(POOL_CONNECT_SUCCESS_METRIC_DESC)
@@ -634,33 +675,24 @@ public PoolEntryMetrics(MeterRegistry registry) {
.register(registry);
}
- /**
- * Increment {@link #poolConnectSuccess} if exception is null and increment {@link
- * #poolConnectErrors} if exception is not null.
- */
- private void incrementPoolConnectMetrics(Throwable exception) {
- if (exception != null) {
- this.poolConnectErrors.increment();
- } else {
- this.poolConnectSuccess.increment();
- }
+ @Override
+ public LongTaskTimer.Sample startConnectTimer() {
+ return this.poolConnectTime.start();
}
- /**
- * Increments heartbeat related metrics.
- *
- * @param fail if ping is failed then this value is 1, otherwise this value is 0.
- */
- private static void incrementHeartbeatMetrics(PoolEntryMetrics metrics, int fail) {
- if (metrics == null) {
- return;
- }
+ @Override
+ public void stopConnectTimer(LongTaskTimer.Sample sample) {
+ stopTimer(sample);
+ }
- if (fail != 0) {
- metrics.heartbeatErrors.increment();
- } else {
- metrics.heartbeatSuccess.increment();
- }
+ @Override
+ public void connectSucceeded() {
+ this.poolConnectSuccess.increment();
+ }
+
+ @Override
+ public void connectFailed(Throwable cause) {
+ this.poolConnectErrors.increment();
}
/**
diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntryView.java b/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntryView.java
index 126c0526..1858e002 100644
--- a/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntryView.java
+++ b/tarantool-pooling/src/main/java/io/tarantool/pool/PoolEntryView.java
@@ -16,6 +16,13 @@
*
* All methods provided by this interface are guaranteed by the library to be non-blocking
* and are safe to invoke directly from any thread, including internal IO threads.
+ *
+ *
A new view is created for every connection session (every connect/reconnect cycle of the
+ * entry). The view passed to {@link io.tarantool.pool.availability.AvailabilityPolicy#initState} is
+ * the view of the first session. The {@link #changeState(PoolEntryState)}, {@link #reconnect()} and
+ * {@link #emit(Consumer)} calls made through a view of a finished session are ignored, so a stale
+ * task of a policy can not affect a newer session. A policy may use the view as a key of its
+ * per-connection data: it is released by {@code stop}.
*/
public interface PoolEntryView {
diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/AvailabilityPolicy.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/AvailabilityPolicy.java
index ac9ce0e9..71d0b647 100644
--- a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/AvailabilityPolicy.java
+++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/AvailabilityPolicy.java
@@ -42,7 +42,16 @@ public interface AvailabilityPolicy {
* connection object creation.
*
* @apiNote Execution of the method for the current view is independent of the execution of this
- * method for another view.
+ * method for another view. The passed view is the view of the first connection session; a new
+ * view is created for every next session (see {@link PoolEntryView}). The state returned here
+ * is only the very first state: after a reconnect the connection is hidden from the load
+ * balancer, and the policy itself must make it available again via {@link
+ * PoolEntryView#changeState(PoolEntryState)} when it is started for the new session.
+ * @implNote The connection has no state yet, so the implementation must not call {@link
+ * PoolEntryView#changeState(PoolEntryState)}, {@link PoolEntryView#reconnect()} or {@link
+ * PoolEntryView#emit(java.util.function.Consumer)} here: such calls fail with {@link
+ * IllegalStateException}. Return the initial state instead. Reading {@link
+ * PoolEntryView#metadata()} and {@link PoolEntryView#client()} is allowed.
* @param view never null.
*/
PoolEntryState initState(PoolEntryView view);
@@ -56,9 +65,9 @@ public interface AvailabilityPolicy {
* Return {@link Duration#ZERO} for an immediate restart. Never null.
* @implSpec This method can be invoked by the library at any time from any thread. The library
* guarantees that this method will be invoked strictly after {@link
- * #initState(PoolEntryView)} has been executed for the provided connection view. The
- * implementation must be strictly non-blocking, thread-safe, and return the value
- * immediately (O(1)) without performing heavy computations or network calls.
+ * #initState(PoolEntryView)} has been executed for the connection that owns the provided
+ * view. The implementation must be strictly non-blocking, thread-safe, and return the
+ * value immediately (O(1)) without performing heavy computations or network calls.
* @apiNote Execution of the method for the current view is independent of the execution of this
* method for another view.
*/
@@ -78,6 +87,11 @@ public interface AvailabilityPolicy {
* the background task must happen asynchronously and complete the stage later. Must be
* idempotent. All exceptions (including RuntimeExceptions) thrown synchronously must be
* caught and handled internally within the policy or reflected safely via the returned stage.
+ * The method is called after every successful connect of the connection, including the
+ * reconnects. The connection is unavailable at this moment (except for the very first
+ * connect, when it has the state returned by {@link #initState(PoolEntryView)}), so the
+ * policy must change the state via {@link PoolEntryView#changeState(PoolEntryState)}
+ * to make the connection available.
* @apiNote Note that this method will be called concurrently by multiple {@code PoolEntry}
* instances if the same policy object is selected for different connections. At least, this
* method will be invoked for each connection within a single {@link InstanceConnectionGroup}.
diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultNoopAvailabilityPolicy.java b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultNoopAvailabilityPolicy.java
index c35863d9..bbaef2ec 100644
--- a/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultNoopAvailabilityPolicy.java
+++ b/tarantool-pooling/src/main/java/io/tarantool/pool/availability/heartbeat/DefaultNoopAvailabilityPolicy.java
@@ -19,8 +19,9 @@
import io.tarantool.pool.availability.AvailabilityPolicy;
/**
- * A policy that neither checks nor modifies the connection availability state for the load
- * balancer. The initial state is always {@link HeartbeatConstants#ACTIVE_STATE}.
+ * A policy that never checks the connection: the connection is always available for the load
+ * balancer while it is connected. The initial state is {@link HeartbeatConstants#ACTIVE_STATE}, and
+ * the same state is set every time the policy is started (after a reconnect).
*/
public class DefaultNoopAvailabilityPolicy implements AvailabilityPolicy {
@@ -47,6 +48,9 @@ public CompletionStage start(PoolEntryView view) {
"[{}/{}][Noop policy]: started",
view.metadata().settings().getTag(),
view.metadata().index());
+ // After a reconnect the connection is hidden from the load balancer by the library, so the
+ // policy must make it available again, as required by AvailabilityPolicy#start.
+ view.changeState(HeartbeatConstants.ACTIVE_STATE);
return CompletableFuture.completedFuture(null);
}
diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/PoolEntryTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/PoolEntryTest.java
new file mode 100644
index 00000000..851b5525
--- /dev/null
+++ b/tarantool-pooling/src/test/java/io/tarantool/pool/PoolEntryTest.java
@@ -0,0 +1,960 @@
+/*
+ * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY
+ * All Rights Reserved.
+ */
+
+package io.tarantool.pool;
+
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+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.TimeoutException;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import io.netty.util.Timer;
+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.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import io.tarantool.core.IProtoClient;
+import io.tarantool.core.connection.ConnectionCloseEvent;
+import io.tarantool.core.protocol.IProtoResponse;
+import io.tarantool.pool.IProtoClientPoolImpl.ConnectionStatistics;
+import io.tarantool.pool.PoolEntry.PoolEntryMetrics;
+import io.tarantool.pool.availability.AvailabilityPolicy;
+import io.tarantool.pool.availability.Metadata;
+import io.tarantool.pool.availability.heartbeat.DefaultNoopAvailabilityPolicy;
+import io.tarantool.pool.exceptions.PoolClosedException;
+import io.tarantool.pool.support.FakeTimer;
+import io.tarantool.pool.support.FakeTimer.FakeTimeout;
+import io.tarantool.pool.support.FlakyTimer;
+import io.tarantool.pool.support.RecordingPoolEntryView;
+import io.tarantool.pool.support.RecordingPoolEntryView.RecordingPoolEventListener;
+import io.tarantool.pool.support.ScriptedPolicy;
+import io.tarantool.pool.support.StubClient;
+
+/**
+ * Unit tests of the reconnection of {@link PoolEntry}.
+ *
+ * The entry works with a scripted client and a manual timer, so the tests do not need a network:
+ * a connect that fails, the moment when the reconnect timer fires and the moment of the close are
+ * chosen by the test.
+ */
+@TestInstance(Lifecycle.PER_METHOD)
+@Execution(ExecutionMode.CONCURRENT)
+@Timeout(value = 20, unit = TimeUnit.SECONDS)
+public class PoolEntryTest {
+
+ private static final String TAG = "node-a";
+ private static final int IDX = 0;
+ private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(1);
+ private static final Duration RECONNECT_AFTER_TIMEOUT = Duration.ofMillis(500);
+ private static final Duration NEXT_CONNECT_TIMEOUT = Duration.ofMillis(2_500);
+ private static final Duration WAIT_TIMEOUT = Duration.ofSeconds(5);
+ private static final Duration BLOCKED_CHECK_TIMEOUT = Duration.ofMillis(300);
+ private static final PoolEntryState UNLOCKED = ScriptedPolicy.INITIAL_STATE;
+ private static final PoolEntryState LOCKED = new PoolEntryState("TEST_LOCKED", true) {};
+
+ private FakeTimer timer;
+ private StubClient client;
+ private ScriptedPolicy policy;
+ private RecordingPoolEventListener listener;
+ private ConnectionStatistics statistics;
+
+ @BeforeEach
+ void setUp() {
+ this.timer = new FakeTimer();
+ this.client = StubClient.create();
+ this.policy = new ScriptedPolicy();
+ this.listener = new RecordingPoolEventListener();
+ this.statistics = new ConnectionStatistics();
+ }
+
+ /**
+ * Checks that a failed session schedules the reconnect and tells the listener about it.
+ *
+ *
The reconnect must be scheduled with the {@code reconnectAfter} delay, the listener must get
+ * the failure and the scheduled reconnect, and the statistics must count the entry as unavailable
+ * and reconnecting.
+ */
+ @Test
+ void testFailedSessionSchedulesReconnect() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+
+ final CompletableFuture cf = entry.connect();
+
+ Assertions.assertTrue(cf.isCompletedExceptionally(), "The connect future must fail");
+ Assertions.assertEquals(1, this.timer.pendingCount(), "The reconnect must be scheduled");
+ Assertions.assertEquals(
+ RECONNECT_AFTER_TIMEOUT, Duration.ofMillis(this.timer.lastScheduled().delayMillis()));
+ Assertions.assertEquals(
+ Arrays.asList("onConnectionClosed", "onConnectionFailed", "onReconnectScheduled"),
+ this.listener.events());
+ Assertions.assertEquals(1, this.statistics.unavailable());
+ Assertions.assertEquals(1, this.statistics.reconnecting());
+ Assertions.assertTrue(entry.isLocked(), "The entry must be hidden from the load balancer");
+ }
+ }
+
+ /** Checks that the fired reconnect timer starts a new session. */
+ @Test
+ void testReconnectTimerStartsNewSession() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+
+ this.timer.fireNext();
+
+ Assertions.assertEquals(
+ 2, this.client.connectCalls(), "A new session must connect the client");
+ }
+ }
+
+ /**
+ * Checks that a series of failed sessions does not leak timers or counters.
+ *
+ * Every failure schedules exactly one reconnect, which is the only pending timer. The entry is
+ * counted as reconnecting once, not once per failure.
+ */
+ @Test
+ void testReconnectIsInfiniteAndDoesNotLeak() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ final int failures = 20;
+ entry.connect();
+
+ for (int i = 1; i < failures; i++) {
+ Assertions.assertEquals(1, this.timer.pendingCount(), "Failure " + i);
+ this.timer.fireNext();
+ }
+
+ Assertions.assertEquals(failures, this.client.connectCalls());
+ Assertions.assertEquals(1, this.timer.pendingCount());
+ Assertions.assertEquals(failures, this.timer.scheduledCount(), "One timer per failure");
+ Assertions.assertEquals(0, this.timer.cancelledCount());
+ Assertions.assertEquals(failures, this.listener.connectionFailedCount());
+ Assertions.assertEquals(failures, this.listener.connectionClosedCount());
+ Assertions.assertEquals(failures, this.listener.reconnectScheduledCount());
+ Assertions.assertEquals(1, this.statistics.reconnecting());
+ Assertions.assertEquals(1, this.statistics.unavailable());
+ }
+ }
+
+ /** Checks that the close cancels the reconnect timer and settles the statistics. */
+ @Test
+ void testCloseWhileWaitingForReconnectCancelsTimer() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final FakeTimeout reconnect = this.timer.lastScheduled();
+
+ entry.close();
+
+ Assertions.assertTrue(reconnect.isCancelled(), "The reconnect timer must be cancelled");
+ Assertions.assertEquals(0, this.timer.pendingCount());
+ Assertions.assertEquals(0, this.statistics.reconnecting());
+ Assertions.assertEquals(0, this.statistics.unavailable());
+ Assertions.assertEquals(1, this.client.connectCalls(), "No new session must be created");
+ }
+ }
+
+ /** Checks that a reconnect timer that fires after the close does not start a session. */
+ @Test
+ void testReconnectFiredAfterCloseDoesNotStartSession() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final FakeTimeout reconnect = this.timer.lastScheduled();
+ entry.close();
+
+ reconnect.fire();
+
+ Assertions.assertEquals(
+ 1, this.client.connectCalls(), "No session must start after the close");
+ Assertions.assertEquals(0, this.timer.pendingCount());
+ Assertions.assertEquals(0, this.statistics.reconnecting());
+ }
+ }
+
+ /**
+ * Checks the close of the session that the fired reconnect timer has just started.
+ *
+ *
The timer fires first and the new session is waiting for the connect, then the entry is
+ * closed. The session must be closed without scheduling one more reconnect.
+ */
+ @Test
+ void testCloseRightAfterReconnectFiredClosesNewSession() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ this.client.connectReturns(new CompletableFuture<>());
+ this.timer.fireNext();
+ Assertions.assertEquals(2, this.client.connectCalls());
+
+ entry.close();
+
+ Assertions.assertEquals(2, this.client.closeCalls(), "The new session must close the client");
+ Assertions.assertEquals(0, this.timer.pendingCount(), "No reconnect must be scheduled");
+ Assertions.assertEquals(0, this.statistics.reconnecting());
+ Assertions.assertEquals(0, this.statistics.unavailable());
+ }
+ }
+
+ /**
+ * Checks the race between the reconnect timer and the close, many times in a row.
+ *
+ *
Whatever happens first, there must be at most one more session, no timer must be left and
+ * the statistics must be settled.
+ */
+ @Test
+ void testReconnectRacingWithCloseLeavesNothingBehind() throws Exception {
+ final ExecutorService pool = Executors.newFixedThreadPool(2);
+ try {
+ for (int i = 0; i < 200; i++) {
+ setUp();
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final FakeTimeout reconnect = this.timer.lastScheduled();
+ final CountDownLatch start = new CountDownLatch(1);
+
+ final CompletableFuture fire =
+ CompletableFuture.runAsync(() -> run(start, reconnect::fire), pool);
+ final CompletableFuture close =
+ CompletableFuture.runAsync(() -> run(start, entry::close), pool);
+ start.countDown();
+ CompletableFuture.allOf(fire, close).get(WAIT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+
+ final String iteration = "Iteration " + i;
+ Assertions.assertTrue(this.client.connectCalls() <= 2, iteration);
+ Assertions.assertEquals(0, this.timer.pendingCount(), iteration);
+ Assertions.assertEquals(0, this.statistics.reconnecting(), iteration);
+ Assertions.assertEquals(0, this.statistics.unavailable(), iteration);
+ }
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ /**
+ * Checks that a timer that cannot schedule the reconnect does not break the entry.
+ *
+ * The exception must not leave the entry, and the {@code reconnecting} statistics must be
+ * consistent with the timer: the entry must not be counted as reconnecting if nothing is going to
+ * reconnect it. The close must leave the statistics settled.
+ */
+ @Test
+ void testTimerFailureWhileSchedulingReconnectKeepsStatisticsConsistent() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(new FlakyTimer(this.timer, 1))) {
+
+ final CompletableFuture cf = Assertions.assertDoesNotThrow(entry::connect);
+
+ Assertions.assertTrue(cf.isCompletedExceptionally());
+ final int scheduled = this.timer.pendingCount();
+ Assertions.assertEquals(
+ scheduled,
+ this.statistics.reconnecting(),
+ "The entry must be counted as reconnecting only if a reconnect is scheduled");
+
+ Assertions.assertDoesNotThrow(entry::close);
+
+ Assertions.assertEquals(0, this.statistics.reconnecting());
+ Assertions.assertEquals(0, this.statistics.unavailable());
+ }
+ }
+
+ /**
+ * Checks that a new connect timeout is applied to the next session only.
+ *
+ * The first session is waiting for to connect when the timeout is changed: it must keep the
+ * old timeout. The session started by the reconnect must use the new one.
+ */
+ @Test
+ void testConnectTimeoutIsAppliedToNextSession() {
+ final CompletableFuture firstConnect = new CompletableFuture<>();
+ this.client.connectReturns(firstConnect);
+ try (PoolEntry entry = newEntry(this.timer)) {
+ final InetSocketAddress address = metadata().settings().getAddress();
+ entry.connect();
+
+ entry.setConnectTimeout(NEXT_CONNECT_TIMEOUT.toMillis());
+
+ Mockito.verify(this.client.client()).connect(address, CONNECT_TIMEOUT.toMillis(), true);
+ Mockito.verify(this.client.client(), Mockito.never())
+ .connect(address, NEXT_CONNECT_TIMEOUT.toMillis(), true);
+
+ firstConnect.completeExceptionally(new TimeoutException("connect"));
+ this.timer.fireNext();
+
+ Mockito.verify(this.client.client()).connect(address, NEXT_CONNECT_TIMEOUT.toMillis(), true);
+ }
+ }
+
+ /**
+ * Checks that a repeated connect returns the future of the running session.
+ *
+ * The second call must not start a new session: the client is connected once, and the future
+ * stays the same after to connect has completed.
+ */
+ @Test
+ void testRepeatedConnectReturnsSameFuture() {
+ final CompletableFuture connect = new CompletableFuture<>();
+ this.client.connectReturns(connect);
+ try (PoolEntry entry = newEntry(this.timer)) {
+ final CompletableFuture first = entry.connect();
+
+ Assertions.assertSame(first, entry.connect());
+ Assertions.assertEquals(1, this.client.connectCalls());
+
+ connect.complete(null);
+
+ Assertions.assertTrue(first.isDone());
+ Assertions.assertFalse(first.isCompletedExceptionally());
+ Assertions.assertSame(first, entry.connect());
+ Assertions.assertEquals(1, this.client.connectCalls());
+ }
+ }
+
+ /**
+ * Checks that a connect while the entry waits for the reconnect does not start a new attempt.
+ *
+ * The future of the failed session is returned: the reconnect is the business of the timer.
+ */
+ @Test
+ void testConnectWhileWaitingForReconnectReturnsFailedFuture() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ final CompletableFuture failed = entry.connect();
+ Assertions.assertTrue(failed.isCompletedExceptionally());
+
+ final CompletableFuture again = entry.connect();
+
+ Assertions.assertSame(failed, again);
+ Assertions.assertEquals(1, this.client.connectCalls(), "No new attempt must be started");
+ Assertions.assertEquals(1, this.timer.pendingCount(), "The reconnect must stay scheduled");
+ }
+ }
+
+ /** Checks that a connect of an entry that has never been connected fails after the close. */
+ @Test
+ void testConnectAfterCloseFailsWithPoolClosedException() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.close();
+
+ final CompletableFuture cf = entry.connect();
+
+ assertPoolClosed(cf);
+ Assertions.assertEquals(0, this.client.connectCalls(), "The client must not be connected");
+ }
+ }
+
+ /** Checks that a connect after the close of a connected entry fails and does not reconnect. */
+ @Test
+ void testConnectAfterCloseOfConnectedEntryFailsWithPoolClosedException() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ Assertions.assertFalse(entry.connect().isCompletedExceptionally());
+ entry.close();
+
+ final CompletableFuture cf = entry.connect();
+
+ assertPoolClosed(cf);
+ Assertions.assertEquals(1, this.client.connectCalls(), "No new session must be started");
+ }
+ }
+
+ /**
+ * Checks that connects from many threads at once start exactly one session.
+ *
+ * All the callers must get the same future, and the client must be connected once.
+ */
+ @Test
+ void testConcurrentConnectsStartOneSession() throws Exception {
+ final CompletableFuture connect = new CompletableFuture<>();
+ this.client.connectReturns(connect);
+ final int threads = 16;
+ final ExecutorService pool = Executors.newFixedThreadPool(threads);
+ try (PoolEntry entry = newEntry(this.timer)) {
+ final CountDownLatch start = new CountDownLatch(1);
+ final List>> calls = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ calls.add(
+ CompletableFuture.supplyAsync(
+ () -> {
+ run(start, () -> {});
+ return entry.connect();
+ },
+ pool));
+ }
+ start.countDown();
+
+ final CompletableFuture first =
+ calls.get(0).get(WAIT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ for (final CompletableFuture> call : calls) {
+ Assertions.assertSame(first, call.get(WAIT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS));
+ }
+ Assertions.assertEquals(1, this.client.connectCalls(), "Exactly one session must connect");
+
+ connect.complete(null);
+
+ Assertions.assertTrue(first.isDone());
+ Assertions.assertFalse(first.isCompletedExceptionally());
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ /**
+ * Checks that the calls made through the view of a finished session are ignored.
+ *
+ * A stale task of the policy must not change the state of the entry, recycle the new session
+ * or notify the listener on behalf of it. The view of the current session keeps working.
+ */
+ @Test
+ void testStaleViewCallsAreIgnored() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final PoolEntryView stale = this.policy.startViews().get(0);
+ stale.reconnect();
+ this.timer.fireNext();
+ Assertions.assertEquals(2, this.policy.startCalls(), "The second session must be running");
+ final PoolEntryView current = this.policy.startViews().get(1);
+ Assertions.assertNotSame(stale, current, "Every session must have its own view");
+ current.changeState(UNLOCKED);
+ final int closeCalls = this.client.closeCalls();
+ final int opened = this.listener.connectionOpenedCount();
+
+ stale.changeState(LOCKED);
+ stale.reconnect();
+ stale.emit(listener -> listener.onConnectionOpened(TAG, IDX));
+
+ Assertions.assertFalse(entry.isLocked(), "A stale view must not change the state");
+ Assertions.assertEquals(0, this.statistics.unavailable());
+ Assertions.assertEquals(closeCalls, this.client.closeCalls(), "The session must stay alive");
+ Assertions.assertEquals(1, this.policy.stopCalls(), "Only the first session is stopped");
+ Assertions.assertEquals(opened, this.listener.connectionOpenedCount());
+
+ current.changeState(LOCKED);
+
+ Assertions.assertTrue(entry.isLocked(), "The current view must keep working");
+ }
+ }
+
+ /**
+ * Checks that a view that is not bound to a session yet can be used.
+ *
+ *
The view passed to {@code initState} is bound to the first session only when the entry
+ * connects, but the policy may keep it and use it before.
+ */
+ @Test
+ void testViewCallsBeforeBindingAreAccepted() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ final PoolEntryView initial = this.policy.initViews().get(0);
+
+ Assertions.assertDoesNotThrow(() -> initial.changeState(LOCKED));
+ Assertions.assertTrue(entry.isLocked());
+ Assertions.assertEquals(1, this.statistics.unavailable());
+ Assertions.assertDoesNotThrow(() -> initial.emit(l -> l.onConnectionOpened(TAG, IDX)));
+ Assertions.assertEquals(1, this.listener.connectionOpenedCount());
+ Assertions.assertDoesNotThrow(initial::reconnect);
+ Assertions.assertEquals(0, this.client.connectCalls(), "There is no session to recycle");
+ }
+ }
+
+ /** Checks that the policy cannot change the entry from {@code initState}: it has no state yet. */
+ @Test
+ void testViewMutationsInInitStateAreForbidden() {
+ final List> mutations =
+ Arrays.asList(
+ view -> view.changeState(LOCKED),
+ PoolEntryView::reconnect,
+ view -> view.emit(listener -> listener.onConnectionOpened(TAG, IDX)));
+
+ for (final Consumer mutation : mutations) {
+ this.policy.initStateAction(mutation);
+
+ Assertions.assertThrows(IllegalStateException.class, () -> newEntry(this.timer));
+ }
+ Assertions.assertEquals(0, this.statistics.unavailable());
+ Assertions.assertEquals(0, this.listener.connectionOpenedCount());
+ }
+
+ /**
+ * Checks that {@code initState} is called once for the whole life of the entry.
+ *
+ * Its view is the view of the first session, and every next session gets its own one.
+ */
+ @Test
+ void testInitStateIsCalledOnceAndItsViewBelongsToFirstSession() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ Assertions.assertEquals(1, this.policy.initViews().size());
+ entry.connect();
+ this.policy.startViews().get(0).reconnect();
+ this.timer.fireNext();
+ this.policy.startViews().get(1).reconnect();
+ this.timer.fireNext();
+
+ Assertions.assertEquals(3, this.policy.startCalls());
+ Assertions.assertEquals(1, this.policy.initViews().size(), "initState must be called once");
+ Assertions.assertSame(this.policy.initViews().get(0), this.policy.startViews().get(0));
+ Assertions.assertNotSame(this.policy.initViews().get(0), this.policy.startViews().get(1));
+ Assertions.assertNotSame(this.policy.startViews().get(1), this.policy.startViews().get(2));
+ }
+ }
+
+ /** Checks that a policy that returns no initial state is rejected with a clear message. */
+ @Test
+ void testNullInitialStateIsRejected() {
+ this.policy.initialState(null);
+
+ final NullPointerException e =
+ Assertions.assertThrows(NullPointerException.class, () -> newEntry(this.timer));
+
+ Assertions.assertTrue(e.getMessage().contains("initial state"), e.getMessage());
+ Assertions.assertEquals(0, this.statistics.unavailable());
+ }
+
+ /*
+ **********************************************************
+ * The statistics
+ **********************************************************
+ */
+
+ /**
+ * Checks the statistics through a failed connect and the successful reconnect after it.
+ *
+ *
The failure counts the entry as unavailable and reconnecting. The successful connect stops
+ * the reconnecting, but the entry stays unavailable until the policy makes it available.
+ */
+ @Test
+ void testStatisticsOnFirstFailureAndSuccessAfterIt() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ assertStatistics(1, 1);
+
+ this.client.connectReturns(CompletableFuture.completedFuture(null));
+ this.timer.fireNext();
+ assertStatistics(1, 0);
+
+ this.policy.startViews().get(0).changeState(UNLOCKED);
+ assertStatistics(0, 0);
+ }
+ }
+
+ /** Checks that the statistics follow the states set by the policy and ignore repeated ones. */
+ @Test
+ void testStatisticsFollowPolicyStateChanges() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final PoolEntryView view = this.policy.startViews().get(0);
+ assertStatistics(0, 0);
+
+ view.changeState(LOCKED);
+ assertStatistics(1, 0);
+
+ view.changeState(LOCKED);
+ assertStatistics(1, 0);
+
+ view.changeState(UNLOCKED);
+ assertStatistics(0, 0);
+ }
+ }
+
+ /** Checks that the close of a locked entry takes it out of the statistics. */
+ @Test
+ void testCloseOfLockedEntrySettlesStatistics() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ this.policy.startViews().get(0).changeState(LOCKED);
+ assertStatistics(1, 0);
+
+ entry.close();
+
+ assertStatistics(0, 0);
+ }
+ }
+
+ /** Checks that a state set after the close does not touch the statistics. */
+ @Test
+ void testChangeStateAfterCloseDoesNotTouchStatistics() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final PoolEntryView view = this.policy.startViews().get(0);
+ entry.close();
+
+ view.changeState(LOCKED);
+ assertStatistics(0, 0);
+
+ view.changeState(UNLOCKED);
+ assertStatistics(0, 0);
+ }
+ }
+
+ /** Checks that a repeated close does not take the entry out of the statistics twice. */
+ @Test
+ void testDoubleCloseDoesNotDecrementStatisticsTwice() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ assertStatistics(1, 1);
+
+ entry.close();
+ assertStatistics(0, 0);
+
+ entry.close();
+ assertStatistics(0, 0);
+ }
+ }
+
+ /*
+ **********************************************************
+ * The availability state
+ **********************************************************
+ */
+
+ /** Checks that the noop policy makes the entry available again after a reconnect. */
+ @Test
+ void testNoopPolicyMakesEntryAvailableAfterReconnect() {
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(new DefaultNoopAvailabilityPolicy())) {
+ entry.connect();
+ Assertions.assertTrue(entry.isLocked(), "A failed connect must hide the entry");
+
+ this.client.connectReturns(CompletableFuture.completedFuture(null));
+ this.timer.fireNext();
+
+ Assertions.assertFalse(entry.isLocked(), "The reconnected entry must be available");
+ assertStatistics(0, 0);
+ }
+ }
+
+ /** Checks that {@code isLocked} follows the state on every stage of the life of the entry. */
+ @Test
+ void testIsLockedFollowsTheState() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ Assertions.assertFalse(entry.isLocked(), "Before the first connect");
+
+ entry.connect();
+ final PoolEntryView first = this.policy.startViews().get(0);
+ Assertions.assertFalse(entry.isLocked(), "Connected, the policy has not changed anything");
+
+ first.changeState(LOCKED);
+ Assertions.assertTrue(entry.isLocked(), "The policy has invalidated the entry");
+
+ first.changeState(UNLOCKED);
+ Assertions.assertFalse(entry.isLocked(), "The policy has activated the entry");
+
+ first.reconnect();
+ Assertions.assertTrue(entry.isLocked(), "Waiting for the reconnect");
+
+ this.timer.fireNext();
+ Assertions.assertTrue(entry.isLocked(), "Reconnected, the policy has not activated it yet");
+
+ this.policy.startViews().get(1).changeState(UNLOCKED);
+ Assertions.assertFalse(entry.isLocked(), "Reconnected and activated by the policy");
+
+ entry.close();
+ Assertions.assertTrue(entry.isLocked(), "A closed entry must not be handed out");
+ }
+ }
+
+ /** Checks that an entry whose policy starts it locked is hidden and counted from the start. */
+ @Test
+ void testLockedInitialStateHidesEntryBeforeConnect() {
+ this.policy.initialState(LOCKED);
+ try (PoolEntry entry = newEntry(this.timer)) {
+ Assertions.assertTrue(entry.isLocked());
+ assertStatistics(1, 0);
+ }
+ }
+
+ /*
+ **********************************************************
+ * The listener and the metrics
+ **********************************************************
+ */
+
+ /** Checks the events of a connected entry that loses the connection with a reason. */
+ @Test
+ void testRemoteCloseReportsFailureAndSchedulesReconnect() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ @SuppressWarnings("unchecked")
+ final ArgumentCaptor> remoteClose =
+ ArgumentCaptor.forClass(BiConsumer.class);
+ Mockito.verify(this.client.client())
+ .onClose(Mockito.eq(ConnectionCloseEvent.CLOSE_BY_REMOTE), remoteClose.capture());
+
+ remoteClose.getValue().accept(this.client.client(), new TimeoutException("reset"));
+
+ Assertions.assertEquals(
+ Arrays.asList(
+ "onConnectionOpened",
+ "onConnectionClosed",
+ "onConnectionFailed",
+ "onReconnectScheduled"),
+ this.listener.events());
+ Assertions.assertEquals(1, this.timer.pendingCount());
+ }
+ }
+
+ /** Checks that a reconnect requested by the policy has no failure: there is no cause. */
+ @Test
+ void testReconnectRequestedByPolicyReportsNoFailure() {
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+
+ this.policy.startViews().get(0).reconnect();
+
+ Assertions.assertEquals(
+ Arrays.asList("onConnectionOpened", "onConnectionClosed", "onReconnectScheduled"),
+ this.listener.events());
+ }
+ }
+
+ /** Checks that a listener that fails on every event does not break sessions or reconnects. */
+ @Test
+ void testFailingListenerDoesNotBreakReconnect() {
+ final PoolEventListener failing =
+ Mockito.mock(
+ PoolEventListener.class,
+ invocation -> {
+ throw new IllegalStateException("listener failed");
+ });
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(failing)) {
+ Assertions.assertDoesNotThrow(entry::connect);
+ Assertions.assertEquals(1, this.timer.pendingCount(), "The reconnect must be scheduled");
+
+ this.client.connectReturns(CompletableFuture.completedFuture(null));
+ this.timer.fireNext();
+
+ Assertions.assertEquals(2, this.client.connectCalls());
+ Assertions.assertEquals(1, this.policy.startCalls(), "The second session must be running");
+ assertStatistics(1, 0);
+ }
+ }
+
+ /** Checks the connect metrics of a successful connect, including the measurement of its time. */
+ @Test
+ void testConnectMetricsOnSuccess() {
+ final SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ final CompletableFuture connect = new CompletableFuture<>();
+ this.client.connectReturns(connect);
+ try (PoolEntry entry = newEntry(new PoolEntryMetrics(registry))) {
+ entry.connect();
+ Assertions.assertEquals(1, activeConnectMeasurements(registry), "The connect is measured");
+
+ connect.complete(null);
+
+ Assertions.assertEquals(0, activeConnectMeasurements(registry), "The measurement is over");
+ Assertions.assertEquals(
+ 1.0, connectCount(registry, PoolEntryMetrics.POOL_CONNECT_SUCCESS_METRIC));
+ Assertions.assertEquals(
+ 0.0, connectCount(registry, PoolEntryMetrics.POOL_CONNECT_ERRORS_METRIC));
+ }
+ }
+
+ /** Checks the connect metrics of a failed connect, including the measurement of its time. */
+ @Test
+ void testConnectMetricsOnFailure() {
+ final SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ this.client.connectFails(new TimeoutException("connect"));
+ try (PoolEntry entry = newEntry(new PoolEntryMetrics(registry))) {
+ entry.connect();
+
+ Assertions.assertEquals(0, activeConnectMeasurements(registry), "The measurement is over");
+ Assertions.assertEquals(
+ 0.0, connectCount(registry, PoolEntryMetrics.POOL_CONNECT_SUCCESS_METRIC));
+ Assertions.assertEquals(
+ 1.0, connectCount(registry, PoolEntryMetrics.POOL_CONNECT_ERRORS_METRIC));
+ }
+ }
+
+ /** Checks that the handler of the ignored packets gets the tag and the index of the entry. */
+ @Test
+ void testIgnoredPacketsHandlerGetsTagAndIndex() {
+ final List received = new CopyOnWriteArrayList<>();
+ final List packets = new CopyOnWriteArrayList<>();
+ final TripleConsumer handler =
+ (tag, index, packet) -> {
+ received.add(tag + '/' + index);
+ packets.add(packet);
+ };
+ try (PoolEntry ignored1 = newEntry(handler)) {
+ @SuppressWarnings("unchecked")
+ final ArgumentCaptor> ignored =
+ ArgumentCaptor.forClass(Consumer.class);
+ Mockito.verify(this.client.client()).onIgnoredPacket(ignored.capture());
+ final IProtoResponse packet = StubClient.emptyBodyResponse();
+
+ ignored.getValue().accept(packet);
+
+ Assertions.assertEquals(Collections.singletonList(TAG + '/' + IDX), received);
+ Assertions.assertSame(packet, packets.get(0));
+ }
+ }
+
+ /*
+ **********************************************************
+ * The close
+ **********************************************************
+ */
+
+ /**
+ * Checks that the close waits for the policy to stop and does not throw.
+ *
+ * The stop of the policy hangs: the close must still be blocked after a while and must finish
+ * once the stop completes.
+ */
+ @Test
+ void testCloseWaitsForPolicyStop() {
+ final CompletableFuture stop = new CompletableFuture<>();
+ this.policy.nextStopReturns(stop);
+ final ExecutorService pool = Executors.newSingleThreadExecutor();
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+ final CompletableFuture closing = CompletableFuture.runAsync(entry::close, pool);
+
+ Assertions.assertThrows(
+ TimeoutException.class,
+ () -> closing.get(BLOCKED_CHECK_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS),
+ "The close must wait for the stop of the policy");
+
+ stop.complete(null);
+
+ Assertions.assertDoesNotThrow(
+ () -> closing.get(WAIT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS));
+ Assertions.assertEquals(1, this.client.closeCalls());
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ /**
+ * Checks that {@code closeAsync} is idempotent.
+ *
+ * The first call returns the future of the finish of the session. A repeated call returns a
+ * completed future even if the session is still finishing, and nothing is stopped twice.
+ */
+ @Test
+ void testCloseAsyncIsIdempotent() {
+ final CompletableFuture stop = new CompletableFuture<>();
+ this.policy.nextStopReturns(stop);
+ try (PoolEntry entry = newEntry(this.timer)) {
+ entry.connect();
+
+ final CompletableFuture first = entry.closeAsync();
+ final CompletableFuture second = entry.closeAsync();
+
+ Assertions.assertFalse(first.isDone(), "The session waits for the stop of the policy");
+ Assertions.assertTrue(second.isDone(), "A repeated call must not wait");
+ Assertions.assertFalse(second.isCompletedExceptionally());
+
+ stop.complete(null);
+
+ Assertions.assertTrue(first.isDone());
+ Assertions.assertFalse(first.isCompletedExceptionally());
+ Assertions.assertTrue(entry.closeAsync().isDone());
+ Assertions.assertEquals(1, this.policy.stopCalls(), "The policy must be stopped once");
+ Assertions.assertEquals(1, this.client.closeCalls(), "The client must be closed once");
+ }
+ }
+
+ private void assertStatistics(int unavailable, int reconnecting) {
+ Assertions.assertEquals(unavailable, this.statistics.unavailable(), "unavailable");
+ Assertions.assertEquals(reconnecting, this.statistics.reconnecting(), "reconnecting");
+ }
+
+ private static int activeConnectMeasurements(SimpleMeterRegistry registry) {
+ return registry.get(PoolEntryMetrics.POOL_CONNECT_TIME_METRIC).longTaskTimer().activeTasks();
+ }
+
+ private static double connectCount(SimpleMeterRegistry registry, String name) {
+ return registry.get(name).counter().count();
+ }
+
+ private static void assertPoolClosed(CompletableFuture cf) {
+ Assertions.assertTrue(cf.isCompletedExceptionally(), "The connect future must fail");
+ final ExecutionException e = Assertions.assertThrows(ExecutionException.class, cf::get);
+ Assertions.assertInstanceOf(PoolClosedException.class, e.getCause());
+ }
+
+ private PoolEntry newEntry(Timer entryTimer) {
+ return newEntry(entryTimer, this.policy, this.listener, null, null);
+ }
+
+ private PoolEntry newEntry(AvailabilityPolicy entryPolicy) {
+ return newEntry(this.timer, entryPolicy, this.listener, null, null);
+ }
+
+ private PoolEntry newEntry(PoolEventListener entryListener) {
+ return newEntry(this.timer, this.policy, entryListener, null, null);
+ }
+
+ private PoolEntry newEntry(PoolEntryMetrics entryMetrics) {
+ return newEntry(this.timer, this.policy, this.listener, entryMetrics, null);
+ }
+
+ private PoolEntry newEntry(TripleConsumer packetsHandler) {
+ return newEntry(this.timer, this.policy, this.listener, null, packetsHandler);
+ }
+
+ private PoolEntry newEntry(
+ Timer entryTimer,
+ AvailabilityPolicy entryPolicy,
+ PoolEventListener entryListener,
+ PoolEntryMetrics entryMetrics,
+ TripleConsumer ignoredPacketsHandler) {
+ return new PoolEntry(
+ this.client.client(),
+ entryTimer,
+ metadata(),
+ true,
+ CONNECT_TIMEOUT.toMillis(),
+ RECONNECT_AFTER_TIMEOUT.toMillis(),
+ entryPolicy,
+ this.statistics,
+ null,
+ ignoredPacketsHandler,
+ null,
+ entryListener,
+ entryMetrics);
+ }
+
+ private Metadata metadata() {
+ return RecordingPoolEntryView.create(TAG, IDX, this.policy, this.client.client()).metadata();
+ }
+
+ private static void run(CountDownLatch start, Runnable action) {
+ try {
+ start.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ action.run();
+ }
+}
diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/integration/PoolEntryLifecycleTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/integration/PoolEntryLifecycleTest.java
new file mode 100644
index 00000000..7c6d1e9a
--- /dev/null
+++ b/tarantool-pooling/src/test/java/io/tarantool/pool/integration/PoolEntryLifecycleTest.java
@@ -0,0 +1,678 @@
+/*
+ * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY
+ * All Rights Reserved.
+ */
+
+package io.tarantool.pool.integration;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicReference;
+
+import io.micrometer.core.instrument.MeterRegistry;
+import io.netty.util.HashedWheelTimer;
+import io.netty.util.Timer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+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.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+import org.mockito.verification.VerificationAfterDelay;
+import org.mockito.verification.VerificationWithTimeout;
+import org.testcontainers.DockerClientFactory;
+import org.testcontainers.containers.tarantool.TarantoolContainer;
+import org.testcontainers.containers.utils.TarantoolContainerClientHelper;
+import org.testcontainers.shaded.org.awaitility.Awaitility;
+
+import io.tarantool.core.IProtoClient;
+import io.tarantool.core.ManagedResource;
+import io.tarantool.core.connection.ConnectionFactory;
+import io.tarantool.pool.IProtoClientPool;
+import io.tarantool.pool.IProtoClientPoolImpl;
+import io.tarantool.pool.InstanceConnectionGroup;
+import io.tarantool.pool.PoolEventListener;
+import io.tarantool.pool.support.ScriptedPolicy;
+
+/**
+ * The lifecycle of a pool entry as it is seen through the pool: connect, failure, reconnect and
+ * close in every phase. The pool has no heartbeat, so the entries use the noop availability policy
+ * unless a test sets its own policy. The events of the entries are checked on a mock of {@link
+ * PoolEventListener}, the waits are done by Awaitility and by the timeouts of the verifications.
+ *
+ * Two kinds of nodes are used:
+ *
+ *
+ * - the proxy node lives for the whole class. The proxy of the node loses the requests of the
+ * clients after {@code lock_pipe(true)}, so the node looks like a hung one. The server
+ * connections of the pool can be dropped by the server without restarting the node;
+ *
- the fixed node is started and stopped by the tests, it always listens to the same port, so
+ * the pool can find it again after the restart.
+ *
+ *
+ * The connections of the pool are lazy: an entry connects when {@code pool.get} is called for
+ * it. The tests share the node and the pipe lock, so they must not run concurrently.
+ */
+@Timeout(value = 180)
+@TestInstance(Lifecycle.PER_METHOD)
+@Execution(ExecutionMode.SAME_THREAD)
+public class PoolEntryLifecycleTest extends BasePoolTest {
+
+ private static final String TAG = "node-a";
+
+ private static final int PROXY_PORT = 3305;
+ private static final int FIXED_PORT = 3311;
+
+ private static final int SIZE = 3;
+ private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(1);
+ private static final Duration RECONNECT_AFTER = Duration.ofMillis(500);
+
+ /** The connect timeout that is never reached by the tests: the node is hung for good. */
+ private static final Duration HUNG_CONNECT_TIMEOUT = Duration.ofSeconds(30);
+
+ /** The connect timeout of the tests that connect to a live node. */
+ private static final Duration POLICY_CONNECT_TIMEOUT = Duration.ofSeconds(5);
+
+ /** The time to wait for an event that must happen. */
+ private static final Duration EVENT_TIMEOUT = Duration.ofSeconds(30);
+
+ /** The time to wait for a quick local action. */
+ private static final Duration SHORT_TIMEOUT = Duration.ofSeconds(10);
+
+ /** The time the close of a pool must fit in. */
+ private static final Duration CLOSE_TIMEOUT = Duration.ofSeconds(15);
+
+ /** The time to wait for the threads of an executor. */
+ private static final Duration EXECUTOR_TIMEOUT = Duration.ofSeconds(30);
+
+ /** The time to wait for a single attempt to get a client. */
+ private static final Duration POLL_GET_TIMEOUT = Duration.ofSeconds(2);
+
+ private static final Duration POLL_INTERVAL = Duration.ofMillis(100);
+
+ /** The time to watch that an event must not happen. */
+ private static final Duration QUIET_PERIOD = RECONNECT_AFTER.multipliedBy(3);
+
+ /** The time a connect to a hung node may take at most. */
+ private static final Duration MAX_FAILED_CONNECT = Duration.ofSeconds(8);
+
+ /** Drops all the connections that go through the proxy of the node: the node stays alive. */
+ private static final String DROP_PROXY_CONNECTIONS = "return drop_proxy_connections()";
+
+ private static final String USER = "pool_user";
+
+ private static TarantoolContainer> proxyNode;
+ private static String proxyHost;
+ private static int proxyPort;
+
+ private TarantoolContainer> fixedNode;
+ private final List pools = new ArrayList<>();
+
+ @BeforeAll
+ static void beforeAll() {
+ proxyNode =
+ TarantoolContainerClientHelper.createTarantoolContainer(PROXY_PORT).withEnv(ENV_MAP);
+ proxyNode.start();
+ TarantoolContainerClientHelper.execInitScript(proxyNode);
+ proxyHost = proxyNode.getHost();
+ proxyPort = proxyNode.getMappedPort(PROXY_PORT);
+ }
+
+ @AfterAll
+ static void afterAll() {
+ proxyNode.stop();
+ }
+
+ @BeforeEach
+ void setUp() {
+ execLua(proxyNode, "lock_pipe(false)");
+ }
+
+ @AfterEach
+ void tearDown() {
+ execLua(proxyNode, "lock_pipe(false)");
+ execLua(proxyNode, "box.schema.user.drop('" + USER + "', {if_exists = true}); return true");
+ for (IProtoClientPool pool : pools) {
+ try {
+ pool.close();
+ } catch (Exception ignored) {
+ // the test may have closed the pool already
+ }
+ }
+ pools.clear();
+ stopFixedNode();
+ }
+
+ /**
+ * The node is down when the pool is created. The first connect fails, the entry schedules the
+ * reconnects by itself and connects when the node appears, without any new request of the user.
+ */
+ @Test
+ void testFirstConnectFailsThenNodeStarts() throws Exception {
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ MeterRegistry registry = createMetricsRegistry();
+ IProtoClientPool pool = newPool(listener, registry, true, CONNECT_TIMEOUT);
+ pool.setGroups(Collections.singletonList(group(fixedHost(), FIXED_PORT, 1, null, null)));
+
+ CompletableFuture first = pool.get(TAG, 0);
+ Assertions.assertNotNull(first);
+ assertFailed(first);
+
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeastOnce())
+ .onConnectionFailed(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), ArgumentMatchers.any());
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeastOnce())
+ .onReconnectScheduled(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), ArgumentMatchers.anyLong());
+ Awaitility.await()
+ .atMost(SHORT_TIMEOUT)
+ .untilAsserted(
+ () -> Assertions.assertTrue(registry.get("pool.reconnecting").gauge().value() > 0));
+
+ startFixedNode();
+ IProtoClient client = awaitClient(pool, 0);
+ Assertions.assertTrue(pingClients(Collections.singletonList(client)));
+
+ Mockito.verify(listener, within(EVENT_TIMEOUT).times(1)).onConnectionOpened(TAG, 0);
+ awaitNotReconnecting(registry);
+ Assertions.assertTrue(registry.get("pool.connect.errors").counter().count() > 0);
+ Assertions.assertEquals(1, registry.get("pool.connect.success").counter().count());
+ }
+
+ /**
+ * The server drops the connections of the pool, the node stays alive. Every entry reconnects by
+ * itself, the clients of the user stay the same objects and keep working.
+ */
+ @Test
+ void testServerDropsConnectionsWithoutRestart() throws Exception {
+ int baseline = getActiveConnectionsCount(proxyNode);
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ MeterRegistry registry = createMetricsRegistry();
+ IProtoClientPool pool = newPool(listener, registry, true, CONNECT_TIMEOUT);
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, SIZE, null, null)));
+
+ List clients = getConnects(pool, TAG, SIZE);
+ Assertions.assertTrue(pingClients(clients));
+ Assertions.assertEquals(SIZE, getActiveConnectionsCountDelta(proxyNode, baseline));
+ Mockito.verify(listener, Mockito.times(SIZE))
+ .onConnectionOpened(ArgumentMatchers.eq(TAG), ArgumentMatchers.anyInt());
+
+ dropProxyConnections(SIZE);
+
+ List restored = new ArrayList<>();
+ for (int i = 0; i < SIZE; i++) {
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeastOnce())
+ .onReconnectScheduled(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(i), ArgumentMatchers.anyLong());
+ restored.add(awaitClient(pool, i));
+ Assertions.assertSame(clients.get(i), restored.get(i), "the client of the entry " + i);
+ }
+ Assertions.assertTrue(pingClients(restored));
+ Mockito.verify(listener, within(EVENT_TIMEOUT).times(2 * SIZE))
+ .onConnectionOpened(ArgumentMatchers.eq(TAG), ArgumentMatchers.anyInt());
+ Assertions.assertEquals(SIZE, getActiveConnectionsCountDelta(proxyNode, baseline));
+ awaitNotReconnecting(registry);
+ }
+
+ /**
+ * A graceful shutdown of the node (the node sends the shutdown event before it closes the
+ * connections) is handled as a lost connection: the entry reconnects when the node is back.
+ */
+ @Test
+ void testNodeRestartWithGracefulShutdown() {
+ checkNodeRestart(true);
+ }
+
+ /** The same as {@link #testNodeRestartWithGracefulShutdown()}, but the pool ignores the event. */
+ @Test
+ void testNodeRestartWithoutGracefulShutdown() {
+ checkNodeRestart(false);
+ }
+
+ private void checkNodeRestart(boolean gracefulShutdown) {
+ startFixedNode();
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ MeterRegistry registry = createMetricsRegistry();
+ IProtoClientPool pool = newPool(listener, registry, gracefulShutdown, CONNECT_TIMEOUT);
+ pool.setGroups(
+ Collections.singletonList(group(fixedNode.getHost(), FIXED_PORT, 1, null, null)));
+
+ IProtoClient client = awaitClient(pool, 0);
+ Assertions.assertTrue(pingClients(Collections.singletonList(client)));
+
+ stopFixedNode();
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeastOnce())
+ .onReconnectScheduled(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), ArgumentMatchers.anyLong());
+
+ startFixedNode();
+ IProtoClient restored = awaitClient(pool, 0);
+ Assertions.assertSame(client, restored);
+ Assertions.assertTrue(pingClients(Collections.singletonList(restored)));
+ Mockito.verify(listener, within(EVENT_TIMEOUT).times(2)).onConnectionOpened(TAG, 0);
+ awaitNotReconnecting(registry);
+ }
+
+ /**
+ * The node accepts the connection but never answers. The connect fails by the timeout, the next
+ * attempt is made after {@code reconnectAfter}, and the entry connects when the node is back.
+ */
+ @Test
+ void testConnectToHungNodeFailsAndRetries() throws Exception {
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ MeterRegistry registry = createMetricsRegistry();
+ IProtoClientPool pool = newPool(listener, registry, true, CONNECT_TIMEOUT);
+ execLua(proxyNode, "lock_pipe(true)");
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, 1, null, null)));
+
+ long start = System.nanoTime();
+ CompletableFuture first = pool.get(TAG, 0);
+ Assertions.assertNotNull(first);
+ assertFailed(first);
+ Duration elapsed = Duration.ofNanos(System.nanoTime() - start);
+ Assertions.assertTrue(
+ elapsed.compareTo(CONNECT_TIMEOUT.multipliedBy(8).dividedBy(10)) >= 0,
+ "failed too early: " + elapsed);
+ Assertions.assertTrue(elapsed.compareTo(MAX_FAILED_CONNECT) < 0, "failed too late: " + elapsed);
+
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeast(2))
+ .onConnectionFailed(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), ArgumentMatchers.any());
+ ArgumentCaptor delays = ArgumentCaptor.forClass(Long.class);
+ Mockito.verify(listener, Mockito.atLeastOnce())
+ .onReconnectScheduled(ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), delays.capture());
+ for (long delay : delays.getAllValues()) {
+ Assertions.assertEquals(RECONNECT_AFTER, Duration.ofMillis(delay));
+ }
+ Assertions.assertTrue(registry.get("pool.connect.errors").counter().count() >= 2);
+
+ execLua(proxyNode, "lock_pipe(false)");
+ IProtoClient client = awaitClient(pool, 0);
+ Assertions.assertTrue(pingClients(Collections.singletonList(client)));
+ }
+
+ /**
+ * The password is wrong: the entry keeps trying. After the password is fixed on the server, the
+ * entry connects without any action of the user.
+ */
+ @Test
+ void testBadCredentialsRecoverAfterPasswordFix() throws Exception {
+ execLua(
+ proxyNode,
+ "box.schema.user.create('"
+ + USER
+ + "', {password = 'right', if_not_exists = true});"
+ + " box.schema.user.passwd('"
+ + USER
+ + "', 'right'); return true");
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ IProtoClientPool pool = newPool(listener, createMetricsRegistry(), true, CONNECT_TIMEOUT);
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, 1, USER, "wrong")));
+
+ assertFailed(pool.get(TAG, 0));
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeast(2))
+ .onConnectionFailed(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), ArgumentMatchers.any());
+ Mockito.verify(listener, Mockito.never()).onConnectionOpened(TAG, 0);
+
+ execLua(proxyNode, "box.schema.user.passwd('" + USER + "', 'wrong'); return true");
+
+ IProtoClient client = awaitClient(pool, 0);
+ Assertions.assertTrue(client.isConnected());
+ Mockito.verify(listener, within(EVENT_TIMEOUT).times(1)).onConnectionOpened(TAG, 0);
+ }
+
+ /**
+ * The pool is closed while the entry is connecting (the node does not answer). The close does not
+ * hang, the pending future fails and the entry does not connect after the node is back.
+ */
+ @Test
+ void testCloseWhileConnecting() throws Exception {
+ int baseline = getActiveConnectionsCount(proxyNode);
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ MeterRegistry registry = createMetricsRegistry();
+ try (IProtoClientPool pool = newPool(listener, registry, true, HUNG_CONNECT_TIMEOUT)) {
+ execLua(proxyNode, "lock_pipe(true)");
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, 1, null, null)));
+
+ CompletableFuture pending = pool.get(TAG, 0);
+ Assertions.assertNotNull(pending);
+ Assertions.assertFalse(pending.isDone(), "the node is hung: the connect must be in progress");
+
+ Assertions.assertTimeoutPreemptively(CLOSE_TIMEOUT, pool::close);
+ assertFailed(pending);
+
+ execLua(proxyNode, "lock_pipe(false)");
+ Mockito.verify(listener, quietFor(QUIET_PERIOD).never())
+ .onConnectionOpened(ArgumentMatchers.any(), ArgumentMatchers.anyInt());
+ Assertions.assertEquals(0, getActiveConnectionsCountDelta(proxyNode, baseline));
+ Assertions.assertEquals(0, registry.get("pool.reconnecting").gauge().value());
+ }
+ }
+
+ /**
+ * The pool is closed while the entry waits for the next reconnect. The reconnect is canceled: the
+ * entry does not connect when the node appears.
+ */
+ @Test
+ void testCloseWhileWaitingForReconnect() throws Exception {
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ MeterRegistry registry = createMetricsRegistry();
+ IProtoClientPool pool = newPool(listener, registry, true, CONNECT_TIMEOUT);
+ pool.setGroups(Collections.singletonList(group(fixedHost(), FIXED_PORT, 1, null, null)));
+
+ assertFailed(pool.get(TAG, 0));
+ Mockito.verify(listener, within(EVENT_TIMEOUT).atLeastOnce())
+ .onReconnectScheduled(
+ ArgumentMatchers.eq(TAG), ArgumentMatchers.eq(0), ArgumentMatchers.anyLong());
+
+ pool.close();
+ Assertions.assertEquals(0, registry.get("pool.reconnecting").gauge().value());
+
+ startFixedNode();
+ Mockito.verify(listener, quietFor(QUIET_PERIOD).never())
+ .onConnectionOpened(ArgumentMatchers.any(), ArgumentMatchers.anyInt());
+ Assertions.assertEquals(0, getActiveConnectionsCount(fixedNode));
+ }
+
+ /**
+ * The pool is closed while the availability policy is starting (its start never completes). The
+ * policy is stopped exactly once and the connection is closed.
+ */
+ @Test
+ void testCloseWhilePolicyIsStarting() throws Exception {
+ int baseline = getActiveConnectionsCount(proxyNode);
+ ScriptedPolicy policy = new ScriptedPolicy().nextStartReturns(new CompletableFuture<>());
+ try (IProtoClientPool pool =
+ newPool(
+ Mockito.mock(PoolEventListener.class),
+ createMetricsRegistry(),
+ true,
+ POLICY_CONNECT_TIMEOUT)) {
+ InstanceConnectionGroup group =
+ InstanceConnectionGroup.builder()
+ .withHost(proxyHost)
+ .withPort(proxyPort)
+ .withSize(1)
+ .withTag(TAG)
+ .withAvailabilityPolicy(policy)
+ .build();
+ pool.setGroups(Collections.singletonList(group));
+
+ // the connect future does not wait for the policy
+ CompletableFuture connected = pool.get(TAG, 0);
+ Assertions.assertNotNull(connected);
+ getWithin(connected, SHORT_TIMEOUT);
+ Awaitility.await().atMost(SHORT_TIMEOUT).until(() -> policy.startCalls() == 1);
+
+ Assertions.assertTimeoutPreemptively(CLOSE_TIMEOUT, pool::close);
+
+ Assertions.assertEquals(Arrays.asList("start", "stop"), policy.calls());
+ Awaitility.await()
+ .atMost(SHORT_TIMEOUT)
+ .untilAsserted(
+ () ->
+ Assertions.assertEquals(0, getActiveConnectionsCountDelta(proxyNode, baseline)));
+ }
+ }
+
+ /**
+ * The pool is closed twice and from several threads at once. Every call completes, and every
+ * entry (the connected one and the entries that never connected) reports the close once.
+ */
+ @Test
+ void testCloseIsIdempotentAndThreadSafe() throws Exception {
+ int baseline = getActiveConnectionsCount(proxyNode);
+ PoolEventListener listener = Mockito.mock(PoolEventListener.class);
+ IProtoClientPool pool = newPool(listener, createMetricsRegistry(), true, CONNECT_TIMEOUT);
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, SIZE, null, null)));
+ // only the first entry connects: the entries are lazy
+ getWithin(pool.get(TAG, 0), SHORT_TIMEOUT);
+
+ int threads = 4;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ try {
+ CyclicBarrier barrier = new CyclicBarrier(threads);
+ List> closes = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ closes.add(
+ executor.submit(
+ () -> {
+ awaitBarrier(barrier);
+ pool.close();
+ return null;
+ }));
+ }
+ for (Future> close : closes) {
+ getWithin(close, EXECUTOR_TIMEOUT);
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ pool.close();
+
+ for (int i = 0; i < SIZE; i++) {
+ Mockito.verify(listener, Mockito.times(1)).onConnectionClosed(TAG, i);
+ }
+ Assertions.assertEquals(0, getActiveConnectionsCountDelta(proxyNode, baseline));
+ }
+
+ /*
+ **********************************************************
+ * Concurrency and the client of the entry
+ **********************************************************
+ */
+
+ /**
+ * Many threads ask for the same connecting entry at once. Everybody gets the same client, and
+ * only one connection is made.
+ */
+ @Test
+ void testConcurrentGetsShareOneConnection() throws Exception {
+ int baseline = getActiveConnectionsCount(proxyNode);
+ MeterRegistry registry = createMetricsRegistry();
+ try (IProtoClientPool pool =
+ newPool(Mockito.mock(PoolEventListener.class), registry, true, CONNECT_TIMEOUT)) {
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, 1, null, null)));
+
+ int threads = 32;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ try {
+ CyclicBarrier barrier = new CyclicBarrier(threads);
+ List>> gets = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ gets.add(
+ executor.submit(
+ () -> {
+ awaitBarrier(barrier);
+ return pool.get(TAG, 0);
+ }));
+ }
+ IProtoClient first = null;
+ for (Future> get : gets) {
+ CompletableFuture future = getWithin(get, EXECUTOR_TIMEOUT);
+ Assertions.assertNotNull(future);
+ IProtoClient client = getWithin(future, SHORT_TIMEOUT);
+ if (first == null) {
+ first = client;
+ }
+ Assertions.assertSame(first, client);
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ Assertions.assertEquals(1, getActiveConnectionsCountDelta(proxyNode, baseline));
+ Assertions.assertEquals(1, registry.get("pool.connect.success").counter().count());
+ }
+ }
+
+ /**
+ * A request is in flight when the server drops the connection. The request fails instead of
+ * hanging, and the same client object serves the requests after the reconnect.
+ */
+ @Test
+ void testInFlightRequestFailsOnDropAndClientSurvives() throws Exception {
+ int baseline = getActiveConnectionsCount(proxyNode);
+ IProtoClientPool pool =
+ newPool(
+ Mockito.mock(PoolEventListener.class), createMetricsRegistry(), true, CONNECT_TIMEOUT);
+ pool.setGroups(Collections.singletonList(group(proxyHost, proxyPort, 1, null, null)));
+ IProtoClient client = awaitClient(pool, 0);
+ Assertions.assertTrue(pingClients(Collections.singletonList(client)));
+
+ execLua(proxyNode, "lock_pipe(true)");
+ CompletableFuture> inFlight = client.ping();
+ Assertions.assertFalse(inFlight.isDone(), "the pipe is locked: the request must be in flight");
+
+ dropProxyConnections(1);
+ assertFailed(inFlight);
+
+ execLua(proxyNode, "lock_pipe(false)");
+ IProtoClient restored = awaitClient(pool, 0);
+ Assertions.assertSame(client, restored);
+ Assertions.assertTrue(pingClients(Collections.singletonList(restored)));
+ Assertions.assertEquals(1, getActiveConnectionsCountDelta(proxyNode, baseline));
+ }
+
+ /*
+ **********************************************************
+ * Helpers
+ **********************************************************
+ */
+
+ private IProtoClientPool newPool(
+ PoolEventListener listener,
+ MeterRegistry registry,
+ boolean gracefulShutdown,
+ Duration connectTimeout) {
+ ManagedResource timerResource =
+ ManagedResource.owned(new HashedWheelTimer(), Timer::stop);
+ ConnectionFactory factory = new ConnectionFactory(bootstrap, timerResource.get());
+ IProtoClientPoolImpl pool =
+ new IProtoClientPoolImpl(
+ factory, timerResource, gracefulShutdown, null, null, registry, null, false, listener);
+ // the entries read the timings when they are created: set them before the groups
+ pool.setConnectTimeout(connectTimeout.toMillis());
+ pool.setReconnectAfter(RECONNECT_AFTER.toMillis());
+ this.pools.add(pool);
+ return pool;
+ }
+
+ private static InstanceConnectionGroup group(
+ String host, int port, int size, String user, String password) {
+ InstanceConnectionGroup.Builder builder =
+ InstanceConnectionGroup.builder().withHost(host).withPort(port).withSize(size).withTag(TAG);
+ if (user != null) {
+ builder.withUser(user).withPassword(password);
+ }
+ return builder.build();
+ }
+
+ /** The host of the fixed node: it is known even when the node is not started. */
+ private static String fixedHost() {
+ return DockerClientFactory.instance().dockerHostIpAddress();
+ }
+
+ private void startFixedNode() {
+ this.fixedNode =
+ TarantoolContainerClientHelper.createTarantoolContainer()
+ .withEnv(ENV_MAP)
+ .withFixedExposedPort(FIXED_PORT, 3301);
+ this.fixedNode.start();
+ TarantoolContainerClientHelper.execInitScript(this.fixedNode);
+ }
+
+ private void stopFixedNode() {
+ if (this.fixedNode != null) {
+ this.fixedNode.stop();
+ this.fixedNode = null;
+ }
+ }
+
+ /** Asks the pool for the entry until the entry is available and connected. */
+ private IProtoClient awaitClient(IProtoClientPool pool, int index) {
+ AtomicReference client = new AtomicReference<>();
+ Awaitility.await()
+ .atMost(EVENT_TIMEOUT)
+ .pollInterval(POLL_INTERVAL)
+ .ignoreExceptions()
+ .until(
+ () -> {
+ CompletableFuture future = pool.get(TAG, index);
+ if (future == null) {
+ return false;
+ }
+ client.set(getWithin(future, POLL_GET_TIMEOUT));
+ return true;
+ });
+ return client.get();
+ }
+
+ private static void awaitNotReconnecting(MeterRegistry registry) {
+ Awaitility.await()
+ .atMost(SHORT_TIMEOUT)
+ .untilAsserted(
+ () -> Assertions.assertEquals(0, registry.get("pool.reconnecting").gauge().value()));
+ }
+
+ /**
+ * Closes the connections of the pool on the proxy side, the node itself stays alive. Only the
+ * connections of the pool go through the proxy, so their count is known.
+ */
+ private void dropProxyConnections(int expected) throws Exception {
+ List> result =
+ TarantoolContainerClientHelper.executeCommandDecoded(proxyNode, DROP_PROXY_CONNECTIONS);
+ Assertions.assertEquals(expected, ((Number) result.get(0)).intValue());
+ }
+
+ /** The future must complete exceptionally in time: neither succeed nor hang. */
+ private static void assertFailed(CompletableFuture> future) throws Exception {
+ try {
+ getWithin(future, SHORT_TIMEOUT);
+ Assertions.fail("The future is completed successfully");
+ } catch (ExecutionException | CancellationException expected) {
+ // expected
+ } catch (TimeoutException e) {
+ Assertions.fail("The future is still pending", e);
+ }
+ }
+
+ /** The only place that converts the timeout of a blocking wait: the JDK 8 API takes a unit. */
+ private static T getWithin(Future future, Duration timeout) throws Exception {
+ return future.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
+ }
+
+ private static void awaitBarrier(CyclicBarrier barrier) throws Exception {
+ barrier.await(SHORT_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS);
+ }
+
+ /** The mockito verification that waits for the call at most the given time. */
+ private static VerificationWithTimeout within(Duration timeout) {
+ return Mockito.timeout(timeout.toMillis());
+ }
+
+ /** The mockito verification that checks the calls after the given time has passed. */
+ private static VerificationAfterDelay quietFor(Duration period) {
+ return Mockito.after(period.toMillis());
+ }
+}
diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/ScriptedPolicy.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/ScriptedPolicy.java
index caf67c51..e738a661 100644
--- a/tarantool-pooling/src/test/java/io/tarantool/pool/support/ScriptedPolicy.java
+++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/ScriptedPolicy.java
@@ -13,6 +13,7 @@
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
import java.util.function.Supplier;
import io.micrometer.core.instrument.MeterRegistry;
@@ -44,10 +45,14 @@ public final class ScriptedPolicy implements AvailabilityPolicy {
new ConcurrentLinkedQueue<>();
private final List calls = new CopyOnWriteArrayList<>();
private final List stopCauses = new CopyOnWriteArrayList<>();
+ private final List initViews = new CopyOnWriteArrayList<>();
+ private final List startViews = new CopyOnWriteArrayList<>();
private final AtomicInteger startCalls = new AtomicInteger();
private final AtomicInteger stopCalls = new AtomicInteger();
private final AtomicInteger backoffCalls = new AtomicInteger();
private volatile Supplier backoff = () -> Duration.ZERO;
+ private volatile PoolEntryState initialState = INITIAL_STATE;
+ private volatile Consumer initStateAction = view -> {};
/** The next {@code start} fails asynchronously with the given cause. */
public ScriptedPolicy nextStartFails(Throwable cause) {
@@ -106,6 +111,28 @@ public ScriptedPolicy backoffThrows(RuntimeException exception) {
return this;
}
+ /** {@code initState} returns the given state (may be null). */
+ public ScriptedPolicy initialState(PoolEntryState state) {
+ this.initialState = state;
+ return this;
+ }
+
+ /** {@code initState} runs the given action with the view before it returns the state. */
+ public ScriptedPolicy initStateAction(Consumer action) {
+ this.initStateAction = action;
+ return this;
+ }
+
+ /** The views passed to {@code initState}, in the order of the calls. */
+ public List initViews() {
+ return this.initViews;
+ }
+
+ /** The views passed to {@code start}, in the order of the calls: one per session. */
+ public List startViews() {
+ return this.startViews;
+ }
+
/** The recorded lifecycle calls in the order of their occurrence: {@code start}, {@code stop}. */
public List calls() {
return this.calls;
@@ -133,7 +160,9 @@ public void configure(Timer timer, MeterRegistry metrics) {}
@Override
public PoolEntryState initState(PoolEntryView view) {
- return INITIAL_STATE;
+ this.initViews.add(view);
+ this.initStateAction.accept(view);
+ return this.initialState;
}
@Override
@@ -146,6 +175,7 @@ public Duration restartBackoff(PoolEntryView view) {
public CompletionStage start(PoolEntryView view) {
this.startCalls.incrementAndGet();
this.calls.add("start");
+ this.startViews.add(view);
return next(this.startOutcomes);
}
diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/unit/IProtoClientPoolTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/unit/IProtoClientPoolTest.java
index 5ec65c11..d220841f 100644
--- a/tarantool-pooling/src/test/java/io/tarantool/pool/unit/IProtoClientPoolTest.java
+++ b/tarantool-pooling/src/test/java/io/tarantool/pool/unit/IProtoClientPoolTest.java
@@ -5,18 +5,24 @@
package io.tarantool.pool.unit;
+import java.time.Duration;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
+import java.util.stream.Collectors;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.LongTaskTimer;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.MultiThreadIoEventLoopGroup;
@@ -24,8 +30,14 @@
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
+import org.junit.jupiter.api.AfterEach;
+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.parallel.Execution;
+import org.junit.jupiter.api.parallel.ExecutionMode;
import io.tarantool.core.IProtoClient;
import io.tarantool.core.ManagedResource;
@@ -33,10 +45,21 @@
import io.tarantool.pool.IProtoClientPool;
import io.tarantool.pool.IProtoClientPoolImpl;
import io.tarantool.pool.InstanceConnectionGroup;
+import io.tarantool.pool.PoolEntryView;
import io.tarantool.pool.exceptions.PoolClosedException;
+import io.tarantool.pool.support.ScriptedPolicy;
+@TestInstance(Lifecycle.PER_METHOD)
+@Execution(ExecutionMode.CONCURRENT)
public class IProtoClientPoolTest {
+ /** The node that does not exist: the connection to it is refused at once. */
+ private static final String UNREACHABLE_HOST = "127.0.0.1";
+
+ private static final int UNREACHABLE_PORT = 1;
+ private static final Duration WAIT_TIMEOUT = Duration.ofSeconds(10);
+ private static final Duration POLL_INTERVAL = Duration.ofMillis(20);
+
protected static final Bootstrap bootstrap =
new Bootstrap()
.group(new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()))
@@ -46,58 +69,63 @@ public class IProtoClientPoolTest {
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
- private ManagedResource timerResource;
protected ConnectionFactory factory;
protected IProtoClientPool pool;
@BeforeEach
public void setUp() {
- timerResource = ManagedResource.owned(new HashedWheelTimer(), Timer::stop);
+ ManagedResource timerResource =
+ ManagedResource.owned(new HashedWheelTimer(), Timer::stop);
factory = new ConnectionFactory(bootstrap, timerResource.get());
pool = new IProtoClientPoolImpl(factory, timerResource);
}
+ @AfterEach
+ public void tearDown() throws Exception {
+ pool.close();
+ }
+
@Test
public void testConnectionTimeoutGetterAndSetter() {
long timeout = 1000;
pool.setConnectTimeout(timeout);
- assertEquals(timeout, pool.getConnectTimeout());
+ Assertions.assertEquals(timeout, pool.getConnectTimeout());
}
@Test
public void testConnectionTimeoutWithInvalidValue() {
- assertThrows(IllegalArgumentException.class, () -> pool.setConnectTimeout(-1));
- assertThrows(IllegalArgumentException.class, () -> pool.setConnectTimeout(0));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> pool.setConnectTimeout(-1));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> pool.setConnectTimeout(0));
}
@Test
public void testReconnectAfterGetterAndSetter() {
long reconnectAfter = 2000;
pool.setReconnectAfter(reconnectAfter);
- assertEquals(reconnectAfter, pool.getReconnectAfter());
+ Assertions.assertEquals(reconnectAfter, pool.getReconnectAfter());
}
@Test
public void testReconnectAfterWithInvalidValue() {
- assertThrows(IllegalArgumentException.class, () -> pool.setReconnectAfter(-1));
- assertThrows(IllegalArgumentException.class, () -> pool.setReconnectAfter(0));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> pool.setReconnectAfter(-1));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> pool.setReconnectAfter(0));
}
@Test
public void testHasAvailableClientsInitially() {
- assertFalse(pool.hasAvailableClients());
+ Assertions.assertFalse(pool.hasAvailableClients());
}
@Test
public void testAvailableConnectionsInitially() {
- assertEquals(0, pool.availableConnections());
+ Assertions.assertEquals(0, pool.availableConnections());
}
@Test
public void testGetTagsWhenNoGroups() {
List tags = pool.getTags();
- assertNotNull(tags);
- assertTrue(tags.isEmpty());
+ Assertions.assertNotNull(tags);
+ Assertions.assertTrue(tags.isEmpty());
}
@Test
@@ -120,19 +148,20 @@ public void testGetTagsReturnsCorrectTags() {
pool.setGroups(groups);
List tags = pool.getTags();
- assertEquals(2, tags.size());
- assertTrue(tags.contains("node-1"));
- assertTrue(tags.contains("node-2"));
+ Assertions.assertEquals(2, tags.size());
+ Assertions.assertTrue(tags.contains("node-1"));
+ Assertions.assertTrue(tags.contains("node-2"));
}
@Test
public void testGetGroupSizeWithNonExistentTag() {
- assertThrows(NoSuchElementException.class, () -> pool.getGroupSize("non-existent-tag"));
+ Assertions.assertThrows(
+ NoSuchElementException.class, () -> pool.getGroupSize("non-existent-tag"));
}
@Test
public void testPoolGetWithNonExistentTag() {
- assertThrows(NoSuchElementException.class, () -> pool.get("non-existent-tag", 0));
+ Assertions.assertThrows(NoSuchElementException.class, () -> pool.get("non-existent-tag", 0));
}
@Test
@@ -149,7 +178,7 @@ public void testPoolGetWithValidTagButInvalidIndex() {
pool.setGroups(groups);
// Valid tag, but index out of bounds
- assertThrows(IndexOutOfBoundsException.class, () -> pool.get("node-1", 5));
+ Assertions.assertThrows(IndexOutOfBoundsException.class, () -> pool.get("node-1", 5));
}
@Test
@@ -166,7 +195,7 @@ public void testPoolGetWithValidParametersReturnsFuture() {
pool.setGroups(groups);
CompletableFuture future = pool.get("node-1", 0);
- assertNotNull(future);
+ Assertions.assertNotNull(future);
}
@Test
@@ -187,12 +216,12 @@ public void testForEachExecutesActionOnAllClients() {
pool.forEach(countingConsumer);
- assertEquals(2, counter[0]);
+ Assertions.assertEquals(2, counter[0]);
}
@Test
public void testGetFactory() {
- assertEquals(factory, pool.getFactory());
+ Assertions.assertEquals(factory, pool.getFactory());
}
@Test
@@ -209,12 +238,12 @@ public void testClosePool() throws Exception {
pool.setGroups(groups);
// Pool should work before closing
- assertEquals(2, pool.getGroupSize("node-1"));
+ Assertions.assertEquals(2, pool.getGroupSize("node-1"));
pool.close();
// After closing, getting a client should throw PoolClosedException
- assertThrows(PoolClosedException.class, () -> pool.get("node-1", 0));
+ Assertions.assertThrows(PoolClosedException.class, () -> pool.get("node-1", 0));
}
@Test
@@ -236,8 +265,8 @@ public void testSetGroupsWhenRemovingGroupEntirely() {
pool.setGroups(initialGroups);
- assertEquals(3, pool.getGroupSize("node-1"));
- assertEquals(2, pool.getGroupSize("node-2"));
+ Assertions.assertEquals(3, pool.getGroupSize("node-1"));
+ Assertions.assertEquals(2, pool.getGroupSize("node-2"));
// Remove one group entirely
List reducedGroups =
@@ -251,8 +280,8 @@ public void testSetGroupsWhenRemovingGroupEntirely() {
pool.setGroups(reducedGroups);
- assertEquals(3, pool.getGroupSize("node-1"));
- assertThrows(NoSuchElementException.class, () -> pool.getGroupSize("node-2"));
+ Assertions.assertEquals(3, pool.getGroupSize("node-1"));
+ Assertions.assertThrows(NoSuchElementException.class, () -> pool.getGroupSize("node-2"));
}
@Test
@@ -279,9 +308,9 @@ public void testSetGroupsWithInvalidIndexAfterResize() {
pool.setGroups(reducedGroups);
- assertEquals(1, pool.getGroupSize("node-1"));
+ Assertions.assertEquals(1, pool.getGroupSize("node-1"));
- assertThrows(IndexOutOfBoundsException.class, () -> pool.get("node-1", 1));
+ Assertions.assertThrows(IndexOutOfBoundsException.class, () -> pool.get("node-1", 1));
}
@Test
@@ -304,7 +333,7 @@ public void testSetGroupsExpandAndShrinkMultipleTimes() {
.build());
pool.setGroups(groups);
- assertEquals(size, pool.getGroupSize(tag));
+ Assertions.assertEquals(size, pool.getGroupSize(tag));
}
}
@@ -320,12 +349,12 @@ public void testSetGroupsWithEmptyListRemovesAllGroups() {
.build());
pool.setGroups(initialGroups);
- assertEquals(1, pool.getTags().size());
+ Assertions.assertEquals(1, pool.getTags().size());
pool.setGroups(Collections.emptyList());
- assertEquals(0, pool.getTags().size());
- assertThrows(NoSuchElementException.class, () -> pool.getGroupSize("node-1"));
+ Assertions.assertEquals(0, pool.getTags().size());
+ Assertions.assertThrows(NoSuchElementException.class, () -> pool.getGroupSize("node-1"));
}
@Test
@@ -347,7 +376,230 @@ public void testAvailableConnectionsAfterSettingGroups() {
pool.setGroups(groups);
- assertEquals(5, pool.availableConnections());
- assertTrue(pool.hasAvailableClients());
+ Assertions.assertEquals(5, pool.availableConnections());
+ Assertions.assertTrue(pool.hasAvailableClients());
+ }
+
+ @Test
+ public void testGroupPolicyIsInitializedForEveryEntry() {
+ ScriptedPolicy policy = new ScriptedPolicy();
+
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", "localhost", 3301, 2).withAvailabilityPolicy(policy).build()));
+
+ Assertions.assertEquals(2, policy.initViews().size());
+ Assertions.assertEquals(new HashSet<>(Arrays.asList(0, 1)), indexesOf(policy));
+ for (PoolEntryView view : policy.initViews()) {
+ Assertions.assertEquals("node-1", view.metadata().settings().getTag());
+ }
+ }
+
+ @Test
+ public void testExpandInitializesOnlyNewEntries() {
+ ScriptedPolicy policy = new ScriptedPolicy();
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", "localhost", 3301, 2).withAvailabilityPolicy(policy).build()));
+
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", "localhost", 3301, 4).withAvailabilityPolicy(policy).build()));
+
+ Assertions.assertEquals(4, policy.initViews().size(), "The old entries must be kept");
+ Assertions.assertEquals(new HashSet<>(Arrays.asList(0, 1, 2, 3)), indexesOf(policy));
+ }
+
+ @Test
+ public void testSameGroupKeepsEntries() {
+ ScriptedPolicy policy = new ScriptedPolicy();
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", "localhost", 3301, 2).withAvailabilityPolicy(policy).build()));
+
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", "localhost", 3301, 2).withAvailabilityPolicy(policy).build()));
+
+ Assertions.assertEquals(2, policy.initViews().size(), "An unchanged group must not be rebuilt");
+ }
+
+ @Test
+ public void testChangedAddressRecreatesEntries() {
+ ScriptedPolicy policy = new ScriptedPolicy();
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", "localhost", 3301, 2).withAvailabilityPolicy(policy).build()));
+ InstanceConnectionGroup changed =
+ builder("node-1", "localhost", 3302, 2).withAvailabilityPolicy(policy).build();
+
+ pool.setGroups(Collections.singletonList(changed));
+
+ Assertions.assertEquals(4, policy.initViews().size(), "The entries must be recreated");
+ for (PoolEntryView view : policy.initViews().subList(2, 4)) {
+ Assertions.assertEquals(changed.getAddress(), view.metadata().settings().getAddress());
+ }
+ }
+
+ @Test
+ public void testChangedTagReplacesGroup() {
+ pool.setGroups(Collections.singletonList(builder("node-1", "localhost", 3301, 2).build()));
+
+ pool.setGroups(Collections.singletonList(builder("node-2", "localhost", 3301, 2).build()));
+
+ Assertions.assertEquals(Collections.singletonList("node-2"), pool.getTags());
+ Assertions.assertThrows(NoSuchElementException.class, () -> pool.get("node-1", 0));
+ Assertions.assertNotNull(pool.get("node-2", 0));
+ }
+
+ @Test
+ public void testGetOfLockedEntryReturnsNullAndIsCounted() throws Exception {
+ SimpleMeterRegistry registry = newRegistry();
+ try (IProtoClientPool registryPool = newPool(registry)) {
+ registryPool.setGroups(
+ Collections.singletonList(
+ builder("node-1", UNREACHABLE_HOST, UNREACHABLE_PORT, 2).build()));
+ CompletableFuture failing = registryPool.get("node-1", 0);
+ awaitFailure(failing);
+
+ Assertions.assertNull(registryPool.get("node-1", 0), "A failed entry must not be handed out");
+ Assertions.assertNotNull(
+ registryPool.get("node-1", 1), "An entry that has not failed must be");
+
+ Assertions.assertEquals(1.0, registry.get("pool.request.unavail").counter().count());
+ waitFor(
+ () ->
+ Assertions.assertEquals(1.0, registry.get("pool.request.errors").counter().count()));
+ }
+ }
+
+ @Test
+ public void testFailedConnectionsAreNotAvailable() throws Exception {
+ SimpleMeterRegistry registry = newRegistry();
+ try (IProtoClientPool registryPool = newPool(registry)) {
+ registryPool.setGroups(
+ Collections.singletonList(
+ builder("node-1", UNREACHABLE_HOST, UNREACHABLE_PORT, 2).build()));
+ Assertions.assertEquals(2, registryPool.availableConnections());
+ Assertions.assertEquals(2.0, registry.get("pool.size").gauge().value());
+
+ awaitFailure(registryPool.get("node-1", 0));
+ awaitFailure(registryPool.get("node-1", 1));
+
+ waitFor(
+ () -> {
+ Assertions.assertEquals(0, registryPool.availableConnections());
+ Assertions.assertFalse(registryPool.hasAvailableClients());
+ Assertions.assertEquals(2.0, registry.get("pool.size").gauge().value());
+ Assertions.assertEquals(0.0, registry.get("pool.available").gauge().value());
+ Assertions.assertEquals(2.0, registry.get("pool.unavailable").gauge().value());
+ Assertions.assertEquals(2.0, registry.get("pool.reconnecting").gauge().value());
+ Assertions.assertEquals(0.0, registry.get("pool.invalidated").gauge().value());
+ });
+ }
+ }
+
+ @Test
+ public void testForEachVisitsClientsOfFailedEntries() {
+ pool.setGroups(
+ Collections.singletonList(
+ builder("node-1", UNREACHABLE_HOST, UNREACHABLE_PORT, 2).build()));
+ awaitFailure(pool.get("node-1", 0));
+ List visited = new ArrayList<>();
+
+ Assertions.assertDoesNotThrow(() -> pool.forEach(visited::add));
+
+ Assertions.assertEquals(2, visited.size());
+ }
+
+ @Test
+ public void testRepeatedCloseIsSafe() throws Exception {
+ pool.setGroups(Collections.singletonList(builder("node-1", "localhost", 3301, 2).build()));
+
+ pool.close();
+
+ Assertions.assertDoesNotThrow(() -> pool.close());
+ }
+
+ @Test
+ public void testSetGroupsAfterCloseFailsWithPoolClosedException() throws Exception {
+ pool.close();
+
+ Assertions.assertThrows(
+ PoolClosedException.class,
+ () ->
+ pool.setGroups(
+ Collections.singletonList(builder("node-1", "localhost", 3301, 1).build())));
+ Assertions.assertTrue(pool.getTags().isEmpty());
+ }
+
+ /** The client requires its metrics to be registered before it is created. */
+ private static SimpleMeterRegistry newRegistry() {
+ SimpleMeterRegistry registry = new SimpleMeterRegistry();
+ LongTaskTimer.builder("request.timer").register(registry);
+ Counter.builder("request.counter").register(registry);
+ Counter.builder("response.success").register(registry);
+ Counter.builder("response.errors").register(registry);
+ Counter.builder("response.ignored").register(registry);
+ return registry;
+ }
+
+ private IProtoClientPool newPool(SimpleMeterRegistry registry) {
+ return new IProtoClientPoolImpl(
+ factory,
+ ManagedResource.owned(new HashedWheelTimer(), Timer::stop),
+ true,
+ null,
+ null,
+ registry,
+ null,
+ null,
+ false,
+ null);
+ }
+
+ private static InstanceConnectionGroup.Builder builder(
+ String tag, String host, int port, int size) {
+ return InstanceConnectionGroup.builder()
+ .withHost(host)
+ .withPort(port)
+ .withSize(size)
+ .withTag(tag);
+ }
+
+ private static Set indexesOf(ScriptedPolicy policy) {
+ return policy.initViews().stream()
+ .map(view -> view.metadata().index())
+ .collect(Collectors.toSet());
+ }
+
+ private static void awaitFailure(CompletableFuture future) {
+ Assertions.assertThrows(
+ ExecutionException.class, () -> future.get(WAIT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS));
+ }
+
+ /** Repeats the check until it passes: the counters of the pool are updated asynchronously. */
+ private static void waitFor(Runnable check) throws InterruptedException {
+ final long deadline = System.nanoTime() + WAIT_TIMEOUT.toNanos();
+ while (true) {
+ try {
+ check.run();
+ return;
+ } catch (AssertionError e) {
+ if (System.nanoTime() > deadline) {
+ throw e;
+ }
+ TimeUnit.NANOSECONDS.sleep(POLL_INTERVAL.toNanos());
+ }
+ }
+ }
+
+ private static void awaitStart(CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
}
}
diff --git a/tarantool-shared-resources/server.lua b/tarantool-shared-resources/server.lua
index b15b42fe..737ff1a3 100644
--- a/tarantool-shared-resources/server.lua
+++ b/tarantool-shared-resources/server.lua
@@ -131,6 +131,13 @@ local function pipe(stopper, from, to, convertor)
end
end
+-- Stoppers of the active proxy connections. Setting `active = true` makes both
+-- pipes of a connection finish: the proxy closes its sockets, so the client
+-- sees a closed connection while the node itself keeps working.
+-- The table is global on purpose (like `pipe_lock`): tarantool3/init.lua is also
+-- executed on the node after this script and must see the same connections.
+proxy_connections = proxy_connections or {}
+
-- Makes socket handler for generic proxy. It accepts two callbacks - one for
-- handling data transmitting from client ot server, the second one is for data
-- transmitting from server to client. It allows perform different kind of
@@ -139,6 +146,7 @@ end
local function create_proxy(client2srv, srv2client)
return function(client)
local stopper = { active = false }
+ proxy_connections[stopper] = true
local proxy = socket.tcp_connect('127.0.0.1', 3301)
local p1 = fiber.create(pipe, stopper, client, proxy, client2srv)
local p2 = fiber.create(pipe, stopper, proxy, client, srv2client)
@@ -147,6 +155,7 @@ local function create_proxy(client2srv, srv2client)
p1:join()
p2:join()
proxy:close()
+ proxy_connections[stopper] = nil
end
end
@@ -290,6 +299,17 @@ function lock_pipe(flag)
pipe_lock = flag
end
+-- Closes all the connections that go through the proxies (ports 3304-3306)
+-- without touching the node itself. Returns the count of the dropped ones.
+function drop_proxy_connections()
+ local count = 0
+ for stopper in pairs(proxy_connections) do
+ stopper.active = true
+ count = count + 1
+ end
+ return count
+end
+
function stuck()
fiber.create(function()
fiber.sleep(1)
diff --git a/tarantool-shared-resources/tarantool3/init.lua b/tarantool-shared-resources/tarantool3/init.lua
index fbb4b3d2..0e84bb71 100644
--- a/tarantool-shared-resources/tarantool3/init.lua
+++ b/tarantool-shared-resources/tarantool3/init.lua
@@ -108,6 +108,14 @@ function pipe(stopper, from, to, convertor)
end
end
+-- Stoppers of the active proxy connections. Setting `active = true` makes both
+-- pipes of a connection finish: the proxy closes its sockets, so the client
+-- sees a closed connection while the node itself keeps working.
+-- The table is global on purpose (like `pipe_lock`): this script is also executed
+-- on the nodes of Tarantool 2 after server.lua, which has already started the
+-- proxies, and must see the same connections.
+proxy_connections = proxy_connections or {}
+
-- Makes socket handler for generic proxy. It accepts two callbacks - one for
-- handling data transmitting from client ot server, the second one is for data
-- transmitting from server to client. It allows perform different kind of
@@ -116,6 +124,7 @@ end
function create_proxy(client2srv, srv2client)
return function(client)
local stopper = { active = false }
+ proxy_connections[stopper] = true
local proxy = socket.tcp_connect('127.0.0.1', 3301)
local p1 = fiber.create(pipe, stopper, client, proxy, client2srv)
local p2 = fiber.create(pipe, stopper, proxy, client, srv2client)
@@ -124,6 +133,7 @@ function create_proxy(client2srv, srv2client)
p1:join()
p2:join()
proxy:close()
+ proxy_connections[stopper] = nil
end
end
@@ -266,6 +276,17 @@ function lock_pipe(flag)
pipe_lock = flag
end
+-- Closes all the connections that go through the proxies (ports 3304-3306)
+-- without touching the node itself. Returns the count of the dropped ones.
+function drop_proxy_connections()
+ local count = 0
+ for stopper in pairs(proxy_connections) do
+ stopper.active = true
+ count = count + 1
+ end
+ return count
+end
+
function stuck()
fiber.create(function()
fiber.sleep(1)